@gitkraken/core-gitlens 0.38.1 → 0.38.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,194 @@
1
+ import { isNotFound } from "../../git/watching/watchGroup.js";
2
+ import { stat } from "node:fs/promises";
3
+ import { Worker } from "node:worker_threads";
4
+ //#region ../git-cli/src/exec/statWorkers.ts
5
+ /**
6
+ * Stats each path it's sent, synchronously, and answers them as one message: a thread making a batch's stats back to
7
+ * back spends far less than the round trip each asynchronous stat makes to libuv's pool. Evaluated as a script, so the
8
+ * package ships no file of its own for it. `throwIfNoEntry: false` answers `undefined` for a path that isn't there,
9
+ * as Node also does for one under a file. Reads as {@link statLocal} does
10
+ */
11
+ const statWorkerSource = `
12
+ const { statSync } = require('node:fs');
13
+ const { parentPort } = require('node:worker_threads');
14
+ parentPort.on('message', paths => {
15
+ parentPort.postMessage(
16
+ paths.map(path => {
17
+ try {
18
+ const stat = statSync(path, { throwIfNoEntry: false });
19
+ return stat == null ? 'missing' : { mtime: stat.mtimeMs, size: stat.size };
20
+ } catch (ex) {
21
+ return ex != null && (ex.code === 'ENOENT' || ex.code === 'ENOTDIR') ? 'missing' : 'unreadable';
22
+ }
23
+ }),
24
+ );
25
+ });
26
+ `;
27
+ /** How long a worker beyond the first stays idle before it's stopped */
28
+ const defaultIdleTimeoutMs = 3e4;
29
+ /** What `maxWorkers` reads as when it isn't a number, as `UnwatchedCacheValidatorOptions.maxFsThreads` does */
30
+ const defaultMaxWorkers = 2;
31
+ /** Workers at most, whatever `maxWorkers` asks for: a batch serves as well on the calling thread past it */
32
+ const maxPoolWorkers = 4;
33
+ /**
34
+ * `path`'s modification time (ms since the epoch) and size, read from the local file system; `undefined` when it isn't
35
+ * there, or is under a path that is a file. Rejects when the stat failed otherwise
36
+ */
37
+ async function statLocal(path) {
38
+ try {
39
+ const s = await stat(path);
40
+ return {
41
+ mtime: s.mtimeMs,
42
+ size: s.size
43
+ };
44
+ } catch (ex) {
45
+ if (isNotFound(ex) || ex?.code === "ENOTDIR") return void 0;
46
+ throw ex;
47
+ }
48
+ }
49
+ /**
50
+ * Worker threads that stat many paths as one call (see `UnwatchedCacheValidatorOptions.statMany`). A batch takes an
51
+ * idle running worker. When none is free, the batch is served on the calling thread, one asynchronous stat at a time,
52
+ * and, while fewer than `maxWorkers` run and none is starting, a worker is started in the background for the batches
53
+ * after it, so no read waits for a worker to start. A worker whose batch never returns (a hung mount) stays busy and
54
+ * is never handed another; one that fails or exits rejects its batch and leaves the pool, and one that does so without a
55
+ * batch rejects the next one. A busy worker keeps the process alive, as a pending file-system call does; an idle or
56
+ * starting one doesn't. One idle worker is kept; the others are stopped once idle for `idleTimeoutMs`.
57
+ */
58
+ var StatWorkerPool = class {
59
+ workers = /* @__PURE__ */ new Set();
60
+ maxWorkers;
61
+ idleTimeoutMs;
62
+ /** Why the last worker to fail without a batch failed, until a batch is rejected with it */
63
+ idleFailure;
64
+ disposed = false;
65
+ constructor(options) {
66
+ const maxWorkers = Math.floor(options.maxWorkers);
67
+ this.maxWorkers = Math.min(Number.isNaN(maxWorkers) ? defaultMaxWorkers : Math.max(1, maxWorkers), maxPoolWorkers);
68
+ this.idleTimeoutMs = options.idleTimeoutMs ?? defaultIdleTimeoutMs;
69
+ }
70
+ dispose() {
71
+ this.disposed = true;
72
+ for (const pooled of [...this.workers]) this.drop(pooled, /* @__PURE__ */ new Error("The stat worker pool was disposed"));
73
+ }
74
+ /** One reading per path, in order; rejects when a worker failed the batch, or once disposed. Never throws */
75
+ statMany(paths) {
76
+ if (this.disposed) return Promise.reject(/* @__PURE__ */ new Error("The stat worker pool was disposed"));
77
+ if (this.idleFailure != null) {
78
+ const failure = this.idleFailure;
79
+ this.idleFailure = void 0;
80
+ return Promise.reject(failure);
81
+ }
82
+ let pooled;
83
+ let starting = false;
84
+ for (const candidate of this.workers) if (!candidate.online) starting = true;
85
+ else if (candidate.batch == null) {
86
+ pooled = candidate;
87
+ break;
88
+ }
89
+ if (pooled == null) {
90
+ if (!starting && this.workers.size < this.maxWorkers) try {
91
+ this.spawn();
92
+ } catch (ex) {
93
+ return Promise.reject(ex instanceof Error ? ex : new Error(String(ex)));
94
+ }
95
+ return statOnCallingThread(paths);
96
+ }
97
+ const worker = pooled;
98
+ return new Promise((resolve, reject) => {
99
+ if (worker.idleTimer != null) {
100
+ clearTimeout(worker.idleTimer);
101
+ worker.idleTimer = void 0;
102
+ }
103
+ worker.batch = {
104
+ resolve,
105
+ reject
106
+ };
107
+ worker.worker.ref();
108
+ try {
109
+ worker.worker.postMessage(paths);
110
+ } catch (ex) {
111
+ this.drop(worker, ex instanceof Error ? ex : new Error(String(ex)));
112
+ }
113
+ });
114
+ }
115
+ /** Starts a worker that answers each batch of paths it's sent with one {@link BatchedStat} per path, in order */
116
+ createWorker() {
117
+ return new Worker(statWorkerSource, {
118
+ eval: true,
119
+ execArgv: []
120
+ });
121
+ }
122
+ spawn() {
123
+ const worker = this.createWorker();
124
+ const pooled = {
125
+ worker,
126
+ online: false,
127
+ batch: void 0,
128
+ idleTimer: void 0
129
+ };
130
+ this.workers.add(pooled);
131
+ worker.unref();
132
+ worker.on("online", () => {
133
+ if (!this.workers.has(pooled)) return;
134
+ pooled.online = true;
135
+ this.startIdleTimer(pooled);
136
+ });
137
+ worker.on("message", (readings) => {
138
+ const batch = pooled.batch;
139
+ if (batch == null) return;
140
+ pooled.batch = void 0;
141
+ worker.unref();
142
+ this.startIdleTimer(pooled);
143
+ batch.resolve(readings);
144
+ });
145
+ const fail = (reason) => {
146
+ if (pooled.batch == null && this.workers.has(pooled)) this.idleFailure = reason;
147
+ this.drop(pooled, reason);
148
+ };
149
+ worker.on("messageerror", fail);
150
+ worker.on("error", fail);
151
+ worker.on("exit", (code) => fail(/* @__PURE__ */ new Error(`The stat worker exited with code ${code}`)));
152
+ }
153
+ /** Stops an idle worker once it stayed idle for {@link idleTimeoutMs}, unless it's the only idle one */
154
+ startIdleTimer(pooled) {
155
+ const timer = setTimeout(() => {
156
+ pooled.idleTimer = void 0;
157
+ if (pooled.batch != null) return;
158
+ let idle = 0;
159
+ for (const candidate of this.workers) if (candidate.online && candidate.batch == null) idle++;
160
+ if (idle > 1) this.drop(pooled, /* @__PURE__ */ new Error("The stat worker was idle"));
161
+ }, this.idleTimeoutMs);
162
+ timer.unref();
163
+ pooled.idleTimer = timer;
164
+ }
165
+ /** Takes `pooled` out of the pool and stops it, rejecting its batch in flight with `reason` */
166
+ drop(pooled, reason) {
167
+ if (!this.workers.delete(pooled)) return;
168
+ if (pooled.idleTimer != null) {
169
+ clearTimeout(pooled.idleTimer);
170
+ pooled.idleTimer = void 0;
171
+ }
172
+ const batch = pooled.batch;
173
+ pooled.batch = void 0;
174
+ batch?.reject(reason);
175
+ pooled.worker.terminate().catch(() => {});
176
+ }
177
+ };
178
+ /**
179
+ * Reads each path with {@link statLocal}, one at a time, so the batch holds one of Node's file-system threads at a
180
+ * time, as the gate it went through counts it
181
+ */
182
+ async function statOnCallingThread(paths) {
183
+ const readings = [];
184
+ for (const path of paths) try {
185
+ readings.push(await statLocal(path) ?? "missing");
186
+ } catch {
187
+ readings.push("unreadable");
188
+ }
189
+ return readings;
190
+ }
191
+ //#endregion
192
+ export { StatWorkerPool, statLocal };
193
+
194
+ //# sourceMappingURL=statWorkers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"statWorkers.js","names":[],"sources":["../../../../git-cli/src/exec/statWorkers.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { Worker } from 'node:worker_threads';\nimport type { BatchedStat } from '@gitlens/git/watching/unwatchedCacheValidator.js';\nimport { isNotFound } from '@gitlens/git/watching/watchGroup.js';\n\n/**\n * Stats each path it's sent, synchronously, and answers them as one message: a thread making a batch's stats back to\n * back spends far less than the round trip each asynchronous stat makes to libuv's pool. Evaluated as a script, so the\n * package ships no file of its own for it. `throwIfNoEntry: false` answers `undefined` for a path that isn't there,\n * as Node also does for one under a file. Reads as {@link statLocal} does\n */\nconst statWorkerSource = `\nconst { statSync } = require('node:fs');\nconst { parentPort } = require('node:worker_threads');\nparentPort.on('message', paths => {\n\tparentPort.postMessage(\n\t\tpaths.map(path => {\n\t\t\ttry {\n\t\t\t\tconst stat = statSync(path, { throwIfNoEntry: false });\n\t\t\t\treturn stat == null ? 'missing' : { mtime: stat.mtimeMs, size: stat.size };\n\t\t\t} catch (ex) {\n\t\t\t\treturn ex != null && (ex.code === 'ENOENT' || ex.code === 'ENOTDIR') ? 'missing' : 'unreadable';\n\t\t\t}\n\t\t}),\n\t);\n});\n`;\n\n/** How long a worker beyond the first stays idle before it's stopped */\nconst defaultIdleTimeoutMs = 30_000;\n/** What `maxWorkers` reads as when it isn't a number, as `UnwatchedCacheValidatorOptions.maxFsThreads` does */\nconst defaultMaxWorkers = 2;\n/** Workers at most, whatever `maxWorkers` asks for: a batch serves as well on the calling thread past it */\nconst maxPoolWorkers = 4;\n\n/**\n * `path`'s modification time (ms since the epoch) and size, read from the local file system; `undefined` when it isn't\n * there, or is under a path that is a file. Rejects when the stat failed otherwise\n */\nexport async function statLocal(path: string): Promise<{ mtime: number; size: number } | undefined> {\n\ttry {\n\t\tconst s = await stat(path);\n\t\treturn { mtime: s.mtimeMs, size: s.size };\n\t} catch (ex) {\n\t\tif (isNotFound(ex) || (ex as { code?: unknown } | undefined)?.code === 'ENOTDIR') return undefined;\n\n\t\tthrow ex;\n\t}\n}\n\ninterface PooledWorker {\n\treadonly worker: Worker;\n\t/** Whether it's running (its `online` event fired); only then is it handed a batch */\n\tonline: boolean;\n\t/** What settles the batch in flight; `undefined` while idle */\n\tbatch:\n\t\t| { readonly resolve: (readings: readonly BatchedStat[]) => void; readonly reject: (ex: Error) => void }\n\t\t| undefined;\n\tidleTimer: ReturnType<typeof setTimeout> | undefined;\n}\n\nexport interface StatWorkerPoolOptions {\n\t/**\n\t * Workers at most, each serving one batch at a time, hung and starting ones included; at most 4, and read as\n\t * `UnwatchedCacheValidatorOptions.maxFsThreads` is (2 when it isn't a number, at least 1)\n\t */\n\treadonly maxWorkers: number;\n\t/** How long a worker beyond the first stays idle before it's stopped. Default: 30 seconds */\n\treadonly idleTimeoutMs?: number;\n}\n\n/**\n * Worker threads that stat many paths as one call (see `UnwatchedCacheValidatorOptions.statMany`). A batch takes an\n * idle running worker. When none is free, the batch is served on the calling thread, one asynchronous stat at a time,\n * and, while fewer than `maxWorkers` run and none is starting, a worker is started in the background for the batches\n * after it, so no read waits for a worker to start. A worker whose batch never returns (a hung mount) stays busy and\n * is never handed another; one that fails or exits rejects its batch and leaves the pool, and one that does so without a\n * batch rejects the next one. A busy worker keeps the process alive, as a pending file-system call does; an idle or\n * starting one doesn't. One idle worker is kept; the others are stopped once idle for `idleTimeoutMs`.\n */\nexport class StatWorkerPool {\n\tprivate readonly workers = new Set<PooledWorker>();\n\tprivate readonly maxWorkers: number;\n\tprivate readonly idleTimeoutMs: number;\n\t/** Why the last worker to fail without a batch failed, until a batch is rejected with it */\n\tprivate idleFailure: Error | undefined;\n\tprivate disposed = false;\n\n\tconstructor(options: StatWorkerPoolOptions) {\n\t\tconst maxWorkers = Math.floor(options.maxWorkers);\n\t\tthis.maxWorkers = Math.min(\n\t\t\tNumber.isNaN(maxWorkers) ? defaultMaxWorkers : Math.max(1, maxWorkers),\n\t\t\tmaxPoolWorkers,\n\t\t);\n\t\tthis.idleTimeoutMs = options.idleTimeoutMs ?? defaultIdleTimeoutMs;\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tfor (const pooled of [...this.workers]) {\n\t\t\tthis.drop(pooled, new Error('The stat worker pool was disposed'));\n\t\t}\n\t}\n\n\t/** One reading per path, in order; rejects when a worker failed the batch, or once disposed. Never throws */\n\tstatMany(paths: readonly string[]): Promise<readonly BatchedStat[]> {\n\t\tif (this.disposed) return Promise.reject(new Error('The stat worker pool was disposed'));\n\n\t\t// Rejected rather than served on the calling thread, so a worker that can't run isn't started again for each batch\n\t\tif (this.idleFailure != null) {\n\t\t\tconst failure = this.idleFailure;\n\t\t\tthis.idleFailure = undefined;\n\t\t\treturn Promise.reject(failure);\n\t\t}\n\n\t\tlet pooled: PooledWorker | undefined;\n\t\tlet starting = false;\n\t\tfor (const candidate of this.workers) {\n\t\t\tif (!candidate.online) {\n\t\t\t\tstarting = true;\n\t\t\t} else if (candidate.batch == null) {\n\t\t\t\tpooled = candidate;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (pooled == null) {\n\t\t\tif (!starting && this.workers.size < this.maxWorkers) {\n\t\t\t\ttry {\n\t\t\t\t\tthis.spawn();\n\t\t\t\t} catch (ex) {\n\t\t\t\t\treturn Promise.reject(ex instanceof Error ? ex : new Error(String(ex)));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn statOnCallingThread(paths);\n\t\t}\n\n\t\tconst worker = pooled;\n\t\treturn new Promise<readonly BatchedStat[]>((resolve, reject) => {\n\t\t\tif (worker.idleTimer != null) {\n\t\t\t\tclearTimeout(worker.idleTimer);\n\t\t\t\tworker.idleTimer = undefined;\n\t\t\t}\n\t\t\t// Claimed before anything is awaited, so a call meanwhile takes another worker\n\t\t\tworker.batch = { resolve: resolve, reject: reject };\n\t\t\tworker.worker.ref();\n\t\t\ttry {\n\t\t\t\tworker.worker.postMessage(paths);\n\t\t\t} catch (ex) {\n\t\t\t\tthis.drop(worker, ex instanceof Error ? ex : new Error(String(ex)));\n\t\t\t}\n\t\t});\n\t}\n\n\t/** Starts a worker that answers each batch of paths it's sent with one {@link BatchedStat} per path, in order */\n\tprotected createWorker(): Worker {\n\t\t// No `execArgv` of the host's (a loader, an inspector), which only slows a worker down that needs none of it\n\t\treturn new Worker(statWorkerSource, { eval: true, execArgv: [] });\n\t}\n\n\tprivate spawn(): void {\n\t\tconst worker = this.createWorker();\n\t\tconst pooled: PooledWorker = { worker: worker, online: false, batch: undefined, idleTimer: undefined };\n\t\tthis.workers.add(pooled);\n\t\tworker.unref();\n\n\t\tworker.on('online', () => {\n\t\t\tif (!this.workers.has(pooled)) return;\n\n\t\t\tpooled.online = true;\n\t\t\tthis.startIdleTimer(pooled);\n\t\t});\n\t\tworker.on('message', (readings: readonly BatchedStat[]) => {\n\t\t\tconst batch = pooled.batch;\n\t\t\tif (batch == null) return;\n\n\t\t\tpooled.batch = undefined;\n\t\t\tworker.unref();\n\t\t\tthis.startIdleTimer(pooled);\n\t\t\tbatch.resolve(readings);\n\t\t});\n\t\tconst fail = (reason: Error): void => {\n\t\t\tif (pooled.batch == null && this.workers.has(pooled)) {\n\t\t\t\tthis.idleFailure = reason;\n\t\t\t}\n\t\t\tthis.drop(pooled, reason);\n\t\t};\n\t\tworker.on('messageerror', fail);\n\t\tworker.on('error', fail);\n\t\tworker.on('exit', code => fail(new Error(`The stat worker exited with code ${code}`)));\n\t}\n\n\t/** Stops an idle worker once it stayed idle for {@link idleTimeoutMs}, unless it's the only idle one */\n\tprivate startIdleTimer(pooled: PooledWorker): void {\n\t\tconst timer = setTimeout(() => {\n\t\t\tpooled.idleTimer = undefined;\n\t\t\tif (pooled.batch != null) return;\n\n\t\t\tlet idle = 0;\n\t\t\tfor (const candidate of this.workers) {\n\t\t\t\tif (candidate.online && candidate.batch == null) {\n\t\t\t\t\tidle++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (idle > 1) {\n\t\t\t\tthis.drop(pooled, new Error('The stat worker was idle'));\n\t\t\t}\n\t\t}, this.idleTimeoutMs);\n\t\ttimer.unref();\n\t\tpooled.idleTimer = timer;\n\t}\n\n\t/** Takes `pooled` out of the pool and stops it, rejecting its batch in flight with `reason` */\n\tprivate drop(pooled: PooledWorker, reason: Error): void {\n\t\tif (!this.workers.delete(pooled)) return;\n\n\t\tif (pooled.idleTimer != null) {\n\t\t\tclearTimeout(pooled.idleTimer);\n\t\t\tpooled.idleTimer = undefined;\n\t\t}\n\t\tconst batch = pooled.batch;\n\t\tpooled.batch = undefined;\n\t\tbatch?.reject(reason);\n\t\tvoid pooled.worker.terminate().catch(() => {});\n\t}\n}\n\n/**\n * Reads each path with {@link statLocal}, one at a time, so the batch holds one of Node's file-system threads at a\n * time, as the gate it went through counts it\n */\nasync function statOnCallingThread(paths: readonly string[]): Promise<readonly BatchedStat[]> {\n\tconst readings: BatchedStat[] = [];\n\tfor (const path of paths) {\n\t\ttry {\n\t\t\treadings.push((await statLocal(path)) ?? 'missing');\n\t\t} catch {\n\t\t\treadings.push('unreadable');\n\t\t}\n\t}\n\treturn readings;\n}\n"],"mappings":";;;;;;;;;;AAWA,MAAM,mBAAmB;;;;;;;;;;;;;;;;;AAkBzB,MAAM,uBAAuB;;AAE7B,MAAM,oBAAoB;;AAE1B,MAAM,iBAAiB;;;;;AAMvB,eAAsB,UAAU,MAAoE;CACnG,IAAI;EACH,MAAM,IAAI,MAAM,KAAK,IAAI;EACzB,OAAO;GAAE,OAAO,EAAE;GAAS,MAAM,EAAE;EAAK;CACzC,SAAS,IAAI;EACZ,IAAI,WAAW,EAAE,KAAM,IAAuC,SAAS,WAAW,OAAO,KAAA;EAEzF,MAAM;CACP;AACD;;;;;;;;;;AAgCA,IAAa,iBAAb,MAA4B;CAC3B,0BAA2B,IAAI,IAAkB;CACjD;CACA;;CAEA;CACA,WAAmB;CAEnB,YAAY,SAAgC;EAC3C,MAAM,aAAa,KAAK,MAAM,QAAQ,UAAU;EAChD,KAAK,aAAa,KAAK,IACtB,OAAO,MAAM,UAAU,IAAI,oBAAoB,KAAK,IAAI,GAAG,UAAU,GACrE,cACD;EACA,KAAK,gBAAgB,QAAQ,iBAAiB;CAC/C;CAEA,UAAgB;EACf,KAAK,WAAW;EAChB,KAAK,MAAM,UAAU,CAAC,GAAG,KAAK,OAAO,GACpC,KAAK,KAAK,wBAAQ,IAAI,MAAM,mCAAmC,CAAC;CAElE;;CAGA,SAAS,OAA2D;EACnE,IAAI,KAAK,UAAU,OAAO,QAAQ,uBAAO,IAAI,MAAM,mCAAmC,CAAC;EAGvF,IAAI,KAAK,eAAe,MAAM;GAC7B,MAAM,UAAU,KAAK;GACrB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D,QAAQ;EACP,SAAS,KAAK,YAAY;CAC3B;CAED,OAAO;AACR"}
@@ -56,10 +56,13 @@ export interface CliGitServiceOptions {
56
56
  * submodule, `--separate-git-dir`, `core.worktree`) isn't validated until a read resolves it, its files looked at
57
57
  * again every 30 seconds. What moves in a worktree under an {@link ignoredWorktreeFolders} folder clears nothing. Without a
58
58
  * {@link watchingProvider}, every repository counts as unwatched. A read waits at most `timeoutMs` (default 1000)
59
- * for the stats, then is served from the cache, and the stats run one at a time per repository and two at once
60
- * overall. A stat on a hung mount holds one of Node's file-system threads until it returns; one outstanding past
61
- * `timeoutMs` lets other repositories' stats go on, as long as the stats hold all but two of the threads
62
- * (`UV_THREADPOOL_SIZE`, default 4), which leaves the host two. Off by default.
59
+ * for the stats, then is served from the cache. Its stats, listings and file reads are made straight on the local
60
+ * file system rather than through `context.fs`, and the stats a repository's git dirs need together as one batch
61
+ * on a worker thread (on the calling thread while no worker is free). The calls run one at a time per repository
62
+ * and two at once overall. A call on a hung mount holds its thread (a worker's, or one of Node's file-system
63
+ * threads) until it returns; one outstanding past `timeoutMs` lets other repositories' calls go on, as long as the
64
+ * calls hold no more threads than Node's file-system pool has less two (`UV_THREADPOOL_SIZE`, default 4), which
65
+ * leaves the host two. Off by default.
63
66
  */
64
67
  validateUnwatchedCaches?: boolean | {
65
68
  readonly timeoutMs?: number;
@@ -1,10 +1,13 @@
1
1
  import { fileUri } from "../utils/uri.js";
2
+ import { FileType } from "../git/context.js";
2
3
  import { isNotFound } from "../git/watching/watchGroup.js";
3
4
  import { GitService } from "../git/service.js";
4
5
  import { CliGitProvider } from "./cliGitProvider.js";
5
6
  import { UnwatchedCacheValidator } from "../git/watching/unwatchedCacheValidator.js";
6
7
  import { findGitPath } from "./exec/locator.js";
8
+ import { StatWorkerPool, statLocal } from "./exec/statWorkers.js";
7
9
  import { env } from "node:process";
10
+ import { readFile, readdir } from "node:fs/promises";
8
11
  //#region ../git-cli/src/service.ts
9
12
  /**
10
13
  * Creates a ready-to-use {@link GitService} backed by the CLI git provider.
@@ -41,11 +44,14 @@ import { env } from "node:process";
41
44
  * ```
42
45
  */
43
46
  function createCliGitService(options) {
47
+ const maxFsThreads = getThreadPoolSize() - 2;
48
+ const statWorkers = options.validateUnwatchedCaches ? new StatWorkerPool({ maxWorkers: maxFsThreads }) : void 0;
44
49
  const service = GitService.createSingleton(options.watchingProvider, {
45
50
  watchPolling: options.watchPolling,
46
51
  verifyBaseRemeasure: options.verifyBaseRemeasure,
47
52
  readFile: (path) => options.context.fs.readFile(fileUri(path)),
48
- readDirectory: (path) => options.context.fs.readDirectory(fileUri(path))
53
+ readDirectory: (path) => options.context.fs.readDirectory(fileUri(path)),
54
+ disposables: statWorkers != null ? [statWorkers] : void 0
49
55
  });
50
56
  const locator = options.locator ?? (() => findGitPath(options.gitPath ?? null));
51
57
  const provider = new CliGitProvider({
@@ -57,28 +63,19 @@ function createCliGitService(options) {
57
63
  refreshIndexAfterWrites: options.refreshIndexAfterWrites
58
64
  });
59
65
  service.register(provider, () => true);
60
- if (options.validateUnwatchedCaches) {
61
- const fs = options.context.fs;
66
+ if (statWorkers != null) {
62
67
  const validator = new UnwatchedCacheValidator({
63
68
  cache: provider.cache,
64
69
  timeoutMs: typeof options.validateUnwatchedCaches === "object" ? options.validateUnwatchedCaches.timeoutMs : void 0,
65
- maxFsThreads: getThreadPoolSize() - 2,
66
- stat: async (path) => {
67
- try {
68
- const stat = await fs.stat(fileUri(path));
69
- return stat != null ? {
70
- mtime: stat.mtime,
71
- size: stat.size
72
- } : void 0;
73
- } catch (ex) {
74
- if (isNotFound(ex)) return void 0;
75
- throw ex;
76
- }
70
+ maxFsThreads,
71
+ statMany: (paths) => statWorkers.statMany(paths),
72
+ stat: statLocal,
73
+ readDirectory: async (path) => {
74
+ return (await readdir(path, { withFileTypes: true })).map((e) => [e.name, (e.isDirectory() ? FileType.Directory : FileType.File) | (e.isSymbolicLink() ? FileType.SymbolicLink : 0)]);
77
75
  },
78
- readDirectory: (path) => fs.readDirectory(fileUri(path)),
79
76
  readFile: async (path) => {
80
77
  try {
81
- return await fs.readFile(fileUri(path));
78
+ return await readFile(path);
82
79
  } catch (ex) {
83
80
  if (isNotFound(ex)) return void 0;
84
81
  throw ex;
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","names":[],"sources":["../../../git-cli/src/service.ts"],"sourcesContent":["import { env } from 'node:process';\nimport { GitService } from '@gitlens/git/service.js';\nimport type { FileWatchingProvider } from '@gitlens/git/watching/provider.js';\nimport { UnwatchedCacheValidator } from '@gitlens/git/watching/unwatchedCacheValidator.js';\nimport { isNotFound } from '@gitlens/git/watching/watchGroup.js';\nimport type { WatchPollingOptions } from '@gitlens/git/watching/watchService.js';\nimport type { WorktreeSummaryServiceOptions } from '@gitlens/git/watching/worktreeSummary.js';\nimport { fileUri } from '@gitlens/utils/uri.js';\nimport type { CliGitProviderOptions } from './cliGitProvider.js';\nimport { CliGitProvider } from './cliGitProvider.js';\nimport type { GitLocation } from './exec/locator.js';\nimport { findGitPath } from './exec/locator.js';\n\n/**\n * Options for {@link createCliGitService}.\n */\nexport interface CliGitServiceOptions {\n\t/**\n\t * Path(s) to the git binary.\n\t * Auto-detected if omitted (searches PATH, platform-specific locations).\n\t * Ignored when {@link locator} is provided.\n\t */\n\tgitPath?: string | string[];\n\n\t/**\n\t * Custom git binary resolver. When provided, used instead of the\n\t * default `findGitPath(gitPath)` lookup.\n\t */\n\tlocator?: () => Promise<GitLocation>;\n\n\t/** Host-provided context hooks (cache events, workspace, integrations, telemetry, fs) */\n\tcontext: CliGitProviderOptions['context'];\n\n\t/**\n\t * Git execution options passed through to the underlying Git executor. `gitOptions.isTrusted(repoPath)` is the\n\t * per-repository trust gate: a `false` answer rejects git runs in that path with `WorkspaceUntrustedError` before\n\t * any process starts. It applies only when `context.workspace.isTrusted` is unset; that flag wins when present.\n\t */\n\tgitOptions?: CliGitProviderOptions['gitOptions'];\n\n\t/** Use an existing Cache instance, or one will be created */\n\tcache?: CliGitProviderOptions['cache'];\n\n\t/** Folders, relative to a repository's common git dir, whose worktrees core acts as if didn't exist */\n\tignoredWorktreeFolders?: CliGitProviderOptions['ignoredWorktreeFolders'];\n\n\t/** Refreshes a checkout's index after core's own writes rewrote it (see `CliGitProviderOptions`); off by default */\n\trefreshIndexAfterWrites?: CliGitProviderOptions['refreshIndexAfterWrites'];\n\n\t/**\n\t * Filesystem watching provider. When provided, the {@link GitService}\n\t * will watch repositories for changes (file creates, edits, deletes).\n\t */\n\twatchingProvider?: FileWatchingProvider;\n\n\t/**\n\t * Polls in place of (or beside) the watchers {@link watchingProvider} reports it can't trust. When omitted, no\n\t * watcher is asked.\n\t */\n\twatchPolling?: WatchPollingOptions;\n\n\t/**\n\t * Keeps the caches that never expire (branches, current branch, refs, tags, remotes, worktrees, stashes, gk config,\n\t * paused operation, and what derives from them) fresh for repositories whose `.git` directory nothing watches:\n\t * before such a read, stats the files a watcher would have reported, and lists the ref directories and worktree\n\t * admin entries, applying what moved as a watcher event would. Files git writes by rename are read only once the\n\t * directory they're in moved, so a read of an idle repository costs a stat per git dir, per ref directory, per\n\t * linked worktree and per file git writes in place, at most once per 250ms per repository; a watched one costs\n\t * nothing, unless its watch is suspended, which holds what it hears until it resumes. Never runs git: a repository\n\t * whose git dir nothing resolved yet is read from its own files, and one whose files can't show it (bare, a\n\t * submodule, `--separate-git-dir`, `core.worktree`) isn't validated until a read resolves it, its files looked at\n\t * again every 30 seconds. What moves in a worktree under an {@link ignoredWorktreeFolders} folder clears nothing. Without a\n\t * {@link watchingProvider}, every repository counts as unwatched. A read waits at most `timeoutMs` (default 1000)\n\t * for the stats, then is served from the cache, and the stats run one at a time per repository and two at once\n\t * overall. A stat on a hung mount holds one of Node's file-system threads until it returns; one outstanding past\n\t * `timeoutMs` lets other repositories' stats go on, as long as the stats hold all but two of the threads\n\t * (`UV_THREADPOOL_SIZE`, default 4), which leaves the host two. Off by default.\n\t */\n\tvalidateUnwatchedCaches?: boolean | { readonly timeoutMs?: number };\n\n\t/** For tests only; production never passes it (see `WorktreeSummaryServiceOptions.verifyBaseRemeasure`) */\n\tverifyBaseRemeasure?: WorktreeSummaryServiceOptions['verifyBaseRemeasure'];\n}\n\n/**\n * Creates a ready-to-use {@link GitService} backed by the CLI git provider.\n *\n * This is the primary entry point for standalone (non-VS Code) consumers\n * of the `@gitlens/git-cli` library. It creates a singleton {@link GitService},\n * wires up a {@link CliGitProvider}, and registers it for all repository paths.\n *\n * @example\n * ```typescript\n * const git = createCliGitService({ context: {} });\n *\n * const repo = git.forRepo('/path/to/repo')!;\n * const branches = await repo.branches.getBranches();\n * const status = await repo.status.getStatus();\n * await repo.ops!.fetch({ remote: 'origin' });\n *\n * git.dispose(); // cleans up provider, cache, and module-level state\n * ```\n *\n * The cache shares a repository's data between its checkouts only once each checkout is registered\n * (`cache.registerRepoPath`). A host that registers checkouts in the background can have each one registered before\n * its first read through `forRepo` by setting a registrar once it has the service (see\n * `Cache.setRepoPathRegistrar`; `undefined` declines a path):\n *\n * ```typescript\n * cache.setRepoPathRegistrar(path =>\n * \tisKnownCheckout(path)\n * \t\t? git.forRepo(path)!.config.getGitDir!().then(gitDir => {\n * \t\t\t\tif (gitDir != null) cache.registerRepoPath(fileUri(path), gitDir);\n * \t\t\t})\n * \t\t: undefined,\n * );\n * ```\n */\nexport function createCliGitService(options: CliGitServiceOptions): GitService {\n\tconst service = GitService.createSingleton(options.watchingProvider, {\n\t\twatchPolling: options.watchPolling,\n\t\tverifyBaseRemeasure: options.verifyBaseRemeasure,\n\t\t// The host's file system reads the shared `.git/config` the watch service compares reports of\n\t\treadFile: path => options.context.fs.readFile(fileUri(path)),\n\t\t// And lists the directory the admin entries of its worktrees are in\n\t\treadDirectory: path => options.context.fs.readDirectory(fileUri(path)),\n\t});\n\n\tconst locator = options.locator ?? (() => findGitPath(options.gitPath ?? null));\n\tconst provider = new CliGitProvider({\n\t\tcontext: options.context,\n\t\tlocator: locator,\n\t\tgitOptions: options.gitOptions,\n\t\tcache: options.cache,\n\t\tignoredWorktreeFolders: options.ignoredWorktreeFolders,\n\t\trefreshIndexAfterWrites: options.refreshIndexAfterWrites,\n\t});\n\n\tservice.register(provider, () => true);\n\n\tif (options.validateUnwatchedCaches) {\n\t\tconst fs = options.context.fs;\n\t\tconst validator = new UnwatchedCacheValidator({\n\t\t\tcache: provider.cache,\n\t\t\ttimeoutMs:\n\t\t\t\ttypeof options.validateUnwatchedCaches === 'object'\n\t\t\t\t\t? options.validateUnwatchedCaches.timeoutMs\n\t\t\t\t\t: undefined,\n\t\t\tmaxFsThreads: getThreadPoolSize() - 2,\n\t\t\tstat: async path => {\n\t\t\t\ttry {\n\t\t\t\t\tconst stat = await fs.stat(fileUri(path));\n\t\t\t\t\treturn stat != null ? { mtime: stat.mtime, size: stat.size } : undefined;\n\t\t\t\t} catch (ex) {\n\t\t\t\t\tif (isNotFound(ex)) return undefined;\n\n\t\t\t\t\tthrow ex;\n\t\t\t\t}\n\t\t\t},\n\t\t\treadDirectory: path => fs.readDirectory(fileUri(path)),\n\t\t\treadFile: async path => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await fs.readFile(fileUri(path));\n\t\t\t\t} catch (ex) {\n\t\t\t\t\tif (isNotFound(ex)) return undefined;\n\n\t\t\t\t\tthrow ex;\n\t\t\t\t}\n\t\t\t},\n\t\t\t// Only for a path whose git dir is cached, which it finds the common git dir from without running git\n\t\t\tgetIgnoredWorktreeRoots: repoPath =>\n\t\t\t\tprovider.cache.gitDir.get(repoPath) != null\n\t\t\t\t\t? provider.getIgnoredWorktreeRoots(repoPath)\n\t\t\t\t\t: Promise.resolve([]),\n\t\t\tresolveGitDir: repoPath => provider.config.resolveGitDirWithoutGit(repoPath),\n\t\t\t// The watch service keys repositories as the cache does (`getRepositoryKey` normalizes a file path alike)\n\t\t\tisWatched: repoPath => service.watchService?.isRepoWatched(repoPath) ?? false,\n\t\t});\n\t\tprovider.cache.setReadValidator(\n\t\t\trepoPath => validator.validate(repoPath),\n\t\t\t() => validator.getResourceUsage(),\n\t\t);\n\t\tservice.watchService?.onDidChangeRepoWatched(e => {\n\t\t\tif (e.watched) {\n\t\t\t\tvalidator.onWatched(e.repoPath);\n\t\t\t} else {\n\t\t\t\tvalidator.onUnwatched(e.repoPath);\n\t\t\t}\n\t\t});\n\t}\n\n\t// Advance the provider cache's status generation clock from the watch session's global events — the standalone\n\t// analogue of what the VS Code host wires in `GitProviderService`. Without this, a consumer that passes a\n\t// `watchingProvider` and drives watch sessions gets FS events but a FROZEN clock, so `dedupeByStatusGeneration`\n\t// degrades to the pre-change/post-change stale-join this branch exists to fix. Standalone has no `Repository`\n\t// models, so there are no force-fired `closed`/`lastFetched` bypassing the session for the global repo event to\n\t// miss. Subscriptions are torn down with the service (its `watchService`'s emitters are disposed on dispose).\n\tservice.watchService?.onDidChangeWorkingTree(repoPath => provider.cache.onWorkingTreeChanged(repoPath));\n\t// Announced kinds were evicted when core announced its write; evicting them again would discard what the host\n\t// re-read since\n\tservice.watchService?.onDidChangeRepository(e => {\n\t\tconst changes = e.getUnannouncedChanges();\n\t\tif (changes.length) {\n\t\t\tprovider.cache.onRepositoryChanged(e.repoPath, changes, {\n\t\t\t\tmovedWorktrees: e.movedWorktrees,\n\t\t\t\tobservedAt: e.observedAt,\n\t\t\t});\n\t\t}\n\t});\n\t// FETCH_HEAD maps to no session change, and there's no `Repository` model here to force-fire `lastFetched` (as\n\t// the VS Code host does), so bridge it straight to the cache or the last-fetched time is never re-read.\n\tservice.watchService?.onDidChangeFetchHead(repoPath =>\n\t\tprovider.cache.onRepositoryChanged(repoPath, ['lastFetched']),\n\t);\n\treturn service;\n}\n\n/** The size of libuv's thread pool, which runs Node's file-system calls, as libuv reads it at its first use */\nfunction getThreadPoolSize(): number {\n\tconst size = Number.parseInt(env.UV_THREADPOOL_SIZE ?? '', 10);\n\treturn Number.isNaN(size) ? 4 : Math.min(Math.max(size, 1), 1024);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAQ,KAAK,OACpC,SAAS,wBAAwB,QAAQ,IACzC,QAAQ,QAAQ,CAAC,CAAC;GACtB,gBAAe,aAAY,SAAS,OAAO,wBAAwB,QAAQ;GAE3E,YAAW,aAAY,QAAQ,cAAc,cAAc,QAAQ,KAAK;EACzE,CAAC;EACD,SAAS,MAAM,kBACd,aAAY,UAAU,SAAS,QAAQ,SACjC,UAAU,iBAAiB,CAClC;EACA,QAAQ,cAAc,wBAAuB,MAAK;GACjD,IAAI,EAAE,SACL,UAAU,UAAU,EAAE,QAAQ;QAE9B,UAAU,YAAY,EAAE,QAAQ;EAElC,CAAC;CACF;CAQA,QAAQ,cAAc,wBAAuB,aAAY,SAAS,MAAM,qBAAqB,QAAQ,CAAC;CAGtG,QAAQ,cAAc,uBAAsB,MAAK;EAChD,MAAM,UAAU,EAAE,sBAAsB;EACxC,IAAI,QAAQ,QACX,SAAS,MAAM,oBAAoB,EAAE,UAAU,SAAS;GACvD,gBAAgB,EAAE;GAClB,YAAY,EAAE;EACf,CAAC;CAEH,CAAC;CAGD,QAAQ,cAAc,sBAAqB,aAC1C,SAAS,MAAM,oBAAoB,UAAU,CAAC,aAAa,CAAC,CAC7D;CACA,OAAO;AACR;;AAGA,SAAS,oBAA4B;CACpC,MAAM,OAAO,OAAO,SAAS,IAAI,sBAAsB,IAAI,EAAE;CAC7D,OAAO,OAAO,MAAM,IAAI,IAAI,IAAI,KAAK,IAAI,KAAK,IAAI,MAAM,CAAC,GAAG,IAAI;AACjE"}
1
+ {"version":3,"file":"service.js","names":[],"sources":["../../../git-cli/src/service.ts"],"sourcesContent":["import { readdir, readFile } from 'node:fs/promises';\nimport { env } from 'node:process';\nimport { FileType } from '@gitlens/git/context.js';\nimport { GitService } from '@gitlens/git/service.js';\nimport type { FileWatchingProvider } from '@gitlens/git/watching/provider.js';\nimport { UnwatchedCacheValidator } from '@gitlens/git/watching/unwatchedCacheValidator.js';\nimport { isNotFound } from '@gitlens/git/watching/watchGroup.js';\nimport type { WatchPollingOptions } from '@gitlens/git/watching/watchService.js';\nimport type { WorktreeSummaryServiceOptions } from '@gitlens/git/watching/worktreeSummary.js';\nimport { fileUri } from '@gitlens/utils/uri.js';\nimport type { CliGitProviderOptions } from './cliGitProvider.js';\nimport { CliGitProvider } from './cliGitProvider.js';\nimport type { GitLocation } from './exec/locator.js';\nimport { findGitPath } from './exec/locator.js';\nimport { statLocal, StatWorkerPool } from './exec/statWorkers.js';\n\n/**\n * Options for {@link createCliGitService}.\n */\nexport interface CliGitServiceOptions {\n\t/**\n\t * Path(s) to the git binary.\n\t * Auto-detected if omitted (searches PATH, platform-specific locations).\n\t * Ignored when {@link locator} is provided.\n\t */\n\tgitPath?: string | string[];\n\n\t/**\n\t * Custom git binary resolver. When provided, used instead of the\n\t * default `findGitPath(gitPath)` lookup.\n\t */\n\tlocator?: () => Promise<GitLocation>;\n\n\t/** Host-provided context hooks (cache events, workspace, integrations, telemetry, fs) */\n\tcontext: CliGitProviderOptions['context'];\n\n\t/**\n\t * Git execution options passed through to the underlying Git executor. `gitOptions.isTrusted(repoPath)` is the\n\t * per-repository trust gate: a `false` answer rejects git runs in that path with `WorkspaceUntrustedError` before\n\t * any process starts. It applies only when `context.workspace.isTrusted` is unset; that flag wins when present.\n\t */\n\tgitOptions?: CliGitProviderOptions['gitOptions'];\n\n\t/** Use an existing Cache instance, or one will be created */\n\tcache?: CliGitProviderOptions['cache'];\n\n\t/** Folders, relative to a repository's common git dir, whose worktrees core acts as if didn't exist */\n\tignoredWorktreeFolders?: CliGitProviderOptions['ignoredWorktreeFolders'];\n\n\t/** Refreshes a checkout's index after core's own writes rewrote it (see `CliGitProviderOptions`); off by default */\n\trefreshIndexAfterWrites?: CliGitProviderOptions['refreshIndexAfterWrites'];\n\n\t/**\n\t * Filesystem watching provider. When provided, the {@link GitService}\n\t * will watch repositories for changes (file creates, edits, deletes).\n\t */\n\twatchingProvider?: FileWatchingProvider;\n\n\t/**\n\t * Polls in place of (or beside) the watchers {@link watchingProvider} reports it can't trust. When omitted, no\n\t * watcher is asked.\n\t */\n\twatchPolling?: WatchPollingOptions;\n\n\t/**\n\t * Keeps the caches that never expire (branches, current branch, refs, tags, remotes, worktrees, stashes, gk config,\n\t * paused operation, and what derives from them) fresh for repositories whose `.git` directory nothing watches:\n\t * before such a read, stats the files a watcher would have reported, and lists the ref directories and worktree\n\t * admin entries, applying what moved as a watcher event would. Files git writes by rename are read only once the\n\t * directory they're in moved, so a read of an idle repository costs a stat per git dir, per ref directory, per\n\t * linked worktree and per file git writes in place, at most once per 250ms per repository; a watched one costs\n\t * nothing, unless its watch is suspended, which holds what it hears until it resumes. Never runs git: a repository\n\t * whose git dir nothing resolved yet is read from its own files, and one whose files can't show it (bare, a\n\t * submodule, `--separate-git-dir`, `core.worktree`) isn't validated until a read resolves it, its files looked at\n\t * again every 30 seconds. What moves in a worktree under an {@link ignoredWorktreeFolders} folder clears nothing. Without a\n\t * {@link watchingProvider}, every repository counts as unwatched. A read waits at most `timeoutMs` (default 1000)\n\t * for the stats, then is served from the cache. Its stats, listings and file reads are made straight on the local\n\t * file system rather than through `context.fs`, and the stats a repository's git dirs need together as one batch\n\t * on a worker thread (on the calling thread while no worker is free). The calls run one at a time per repository\n\t * and two at once overall. A call on a hung mount holds its thread (a worker's, or one of Node's file-system\n\t * threads) until it returns; one outstanding past `timeoutMs` lets other repositories' calls go on, as long as the\n\t * calls hold no more threads than Node's file-system pool has less two (`UV_THREADPOOL_SIZE`, default 4), which\n\t * leaves the host two. Off by default.\n\t */\n\tvalidateUnwatchedCaches?: boolean | { readonly timeoutMs?: number };\n\n\t/** For tests only; production never passes it (see `WorktreeSummaryServiceOptions.verifyBaseRemeasure`) */\n\tverifyBaseRemeasure?: WorktreeSummaryServiceOptions['verifyBaseRemeasure'];\n}\n\n/**\n * Creates a ready-to-use {@link GitService} backed by the CLI git provider.\n *\n * This is the primary entry point for standalone (non-VS Code) consumers\n * of the `@gitlens/git-cli` library. It creates a singleton {@link GitService},\n * wires up a {@link CliGitProvider}, and registers it for all repository paths.\n *\n * @example\n * ```typescript\n * const git = createCliGitService({ context: {} });\n *\n * const repo = git.forRepo('/path/to/repo')!;\n * const branches = await repo.branches.getBranches();\n * const status = await repo.status.getStatus();\n * await repo.ops!.fetch({ remote: 'origin' });\n *\n * git.dispose(); // cleans up provider, cache, and module-level state\n * ```\n *\n * The cache shares a repository's data between its checkouts only once each checkout is registered\n * (`cache.registerRepoPath`). A host that registers checkouts in the background can have each one registered before\n * its first read through `forRepo` by setting a registrar once it has the service (see\n * `Cache.setRepoPathRegistrar`; `undefined` declines a path):\n *\n * ```typescript\n * cache.setRepoPathRegistrar(path =>\n * \tisKnownCheckout(path)\n * \t\t? git.forRepo(path)!.config.getGitDir!().then(gitDir => {\n * \t\t\t\tif (gitDir != null) cache.registerRepoPath(fileUri(path), gitDir);\n * \t\t\t})\n * \t\t: undefined,\n * );\n * ```\n */\nexport function createCliGitService(options: CliGitServiceOptions): GitService {\n\tconst maxFsThreads = getThreadPoolSize() - 2;\n\tconst statWorkers = options.validateUnwatchedCaches ? new StatWorkerPool({ maxWorkers: maxFsThreads }) : undefined;\n\tconst service = GitService.createSingleton(options.watchingProvider, {\n\t\twatchPolling: options.watchPolling,\n\t\tverifyBaseRemeasure: options.verifyBaseRemeasure,\n\t\t// The host's file system reads the shared `.git/config` the watch service compares reports of\n\t\treadFile: path => options.context.fs.readFile(fileUri(path)),\n\t\t// And lists the directory the admin entries of its worktrees are in\n\t\treadDirectory: path => options.context.fs.readDirectory(fileUri(path)),\n\t\tdisposables: statWorkers != null ? [statWorkers] : undefined,\n\t});\n\n\tconst locator = options.locator ?? (() => findGitPath(options.gitPath ?? null));\n\tconst provider = new CliGitProvider({\n\t\tcontext: options.context,\n\t\tlocator: locator,\n\t\tgitOptions: options.gitOptions,\n\t\tcache: options.cache,\n\t\tignoredWorktreeFolders: options.ignoredWorktreeFolders,\n\t\trefreshIndexAfterWrites: options.refreshIndexAfterWrites,\n\t});\n\n\tservice.register(provider, () => true);\n\n\tif (statWorkers != null) {\n\t\tconst validator = new UnwatchedCacheValidator({\n\t\t\tcache: provider.cache,\n\t\t\ttimeoutMs:\n\t\t\t\ttypeof options.validateUnwatchedCaches === 'object'\n\t\t\t\t\t? options.validateUnwatchedCaches.timeoutMs\n\t\t\t\t\t: undefined,\n\t\t\tmaxFsThreads: maxFsThreads,\n\t\t\t// Straight from the local file system, as git reads these paths: a worker thread can't call the host's\n\t\t\t// `context.fs`, and a path read one way must read the same the other, or a batch that failed (whose paths\n\t\t\t// are read one at a time) would report as moved what only read differently. Listings and file reads too, so\n\t\t\t// the validator reads one file system\n\t\t\tstatMany: paths => statWorkers.statMany(paths),\n\t\t\tstat: statLocal,\n\t\t\treadDirectory: async path => {\n\t\t\t\tconst entries = await readdir(path, { withFileTypes: true });\n\t\t\t\treturn entries.map(\n\t\t\t\t\te =>\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\te.name,\n\t\t\t\t\t\t\t(e.isDirectory() ? FileType.Directory : FileType.File) |\n\t\t\t\t\t\t\t\t(e.isSymbolicLink() ? FileType.SymbolicLink : 0),\n\t\t\t\t\t\t] as const,\n\t\t\t\t);\n\t\t\t},\n\t\t\treadFile: async path => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await readFile(path);\n\t\t\t\t} catch (ex) {\n\t\t\t\t\tif (isNotFound(ex)) return undefined;\n\n\t\t\t\t\tthrow ex;\n\t\t\t\t}\n\t\t\t},\n\t\t\t// Only for a path whose git dir is cached, which it finds the common git dir from without running git\n\t\t\tgetIgnoredWorktreeRoots: repoPath =>\n\t\t\t\tprovider.cache.gitDir.get(repoPath) != null\n\t\t\t\t\t? provider.getIgnoredWorktreeRoots(repoPath)\n\t\t\t\t\t: Promise.resolve([]),\n\t\t\tresolveGitDir: repoPath => provider.config.resolveGitDirWithoutGit(repoPath),\n\t\t\t// The watch service keys repositories as the cache does (`getRepositoryKey` normalizes a file path alike)\n\t\t\tisWatched: repoPath => service.watchService?.isRepoWatched(repoPath) ?? false,\n\t\t});\n\t\tprovider.cache.setReadValidator(\n\t\t\trepoPath => validator.validate(repoPath),\n\t\t\t() => validator.getResourceUsage(),\n\t\t);\n\t\tservice.watchService?.onDidChangeRepoWatched(e => {\n\t\t\tif (e.watched) {\n\t\t\t\tvalidator.onWatched(e.repoPath);\n\t\t\t} else {\n\t\t\t\tvalidator.onUnwatched(e.repoPath);\n\t\t\t}\n\t\t});\n\t}\n\n\t// Advance the provider cache's status generation clock from the watch session's global events — the standalone\n\t// analogue of what the VS Code host wires in `GitProviderService`. Without this, a consumer that passes a\n\t// `watchingProvider` and drives watch sessions gets FS events but a FROZEN clock, so `dedupeByStatusGeneration`\n\t// degrades to the pre-change/post-change stale-join this branch exists to fix. Standalone has no `Repository`\n\t// models, so there are no force-fired `closed`/`lastFetched` bypassing the session for the global repo event to\n\t// miss. Subscriptions are torn down with the service (its `watchService`'s emitters are disposed on dispose).\n\tservice.watchService?.onDidChangeWorkingTree(repoPath => provider.cache.onWorkingTreeChanged(repoPath));\n\t// Announced kinds were evicted when core announced its write; evicting them again would discard what the host\n\t// re-read since\n\tservice.watchService?.onDidChangeRepository(e => {\n\t\tconst changes = e.getUnannouncedChanges();\n\t\tif (changes.length) {\n\t\t\tprovider.cache.onRepositoryChanged(e.repoPath, changes, {\n\t\t\t\tmovedWorktrees: e.movedWorktrees,\n\t\t\t\tobservedAt: e.observedAt,\n\t\t\t});\n\t\t}\n\t});\n\t// FETCH_HEAD maps to no session change, and there's no `Repository` model here to force-fire `lastFetched` (as\n\t// the VS Code host does), so bridge it straight to the cache or the last-fetched time is never re-read.\n\tservice.watchService?.onDidChangeFetchHead(repoPath =>\n\t\tprovider.cache.onRepositoryChanged(repoPath, ['lastFetched']),\n\t);\n\treturn service;\n}\n\n/** The size of libuv's thread pool, which runs Node's file-system calls, as libuv reads it at its first use */\nfunction getThreadPoolSize(): number {\n\tconst size = Number.parseInt(env.UV_THREADPOOL_SIZE ?? '', 10);\n\treturn Number.isNaN(size) ? 4 :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,SAAS,IAAI;KACZ,IAAI,WAAW,EAAE,GAAG,OAAO,KAAA;KAE3B,MAAM;IACP;GACD;GAEA,0BAAyB,aACxB,SAAS,MAAM,OAAO,IAAI,QAAQ,KAAK,OACpC,SAAS,wBAAwB,QAAQ,IACzC,QAAQ,QAAQ,CAAC,CAAC;GACtB,gBAAe,aAAY,SAAS,OAAO,wBAAwB,QAAQ;GAE3E,YAAW,aAAY,QAAQ,cAAc,cAAc,QAAQ,KAAK;EACzE,CAAC;EACD,SAAS,MAAM,kBACd,aAAY,UAAU,SAAS,QAAQ,SACjC,UAAU,iBAAiB,CAClC;EACA,QAAQ,cAAc,wBAAuB,MAAK;GACjD,IAAI,EAAE,SACL,UAAU,UAAU,EAAE,QAAQ;QAE9B,UAAU,YAAY,EAAE,QAAQ;EAElC,CAAC;CACF;CAQA,QAAQ,cAAc,wBAAuB,aAAY,SAAS,MAAM,qBAAqB,QAAQ,CAAC;CAGtG,QAAQ,cAAc,uBAAsB,MAAK;EAChD,MAAM,UAAU,EAAE,sBAAsB;EACxC,IAAI,QAAQ,QACX,SAAS,MAAM,oBAAoB,EAAE,UAAU,SAAS;GACvD,gBAAgB,EAAE;GAClB,YAAY,EAAE;EACf,CAAC;CAEH,CAAC;CAGD,QAAQ,cAAc,sBAAqB,aAC1C,SAAS,MAAM,oBAAoB,UAAU,CAAC,aAAa,CAAC,CAC7D;CACA,OAAO;AACR;;AAGA,SAAS,oBAA4B;CACpC,MAAM,OAAO,OAAO,SAAS,IAAI,sBAAsB,IAAI,EAAE;CAC7D,OAAO,OAAO,MAAM,IAAI,IAAI,IAAI,KAAK,IAAI,KAAK,IAAI,MAAM,CAAC,GAAG,IAAI;AACjE"}
@@ -146,28 +146,30 @@ function spawnProcess(command, args, options) {
146
146
  }
147
147
  const child = spawn(command, args, spawnOptions);
148
148
  if (isWindows) killTreeOnKill(child);
149
- if (timeout != null && timeout > 0) {
150
- let timeoutId = setTimeout(() => {
151
- if (timeoutId != null) {
152
- try {
153
- child.kill();
154
- } catch (ex) {
155
- child.emit("error", ex);
156
- }
157
- timeoutId = void 0;
158
- }
159
- }, timeout);
160
- const clear = () => {
161
- if (timeoutId != null) {
162
- clearTimeout(timeoutId);
163
- timeoutId = void 0;
164
- }
165
- };
166
- child.once("exit", clear);
167
- child.once("close", clear);
168
- }
149
+ if (timeout != null && timeout > 0) killOnTimeout(child, timeout);
169
150
  return child;
170
151
  }
152
+ /** Node's spawn `timeout`, but also cleared on `'close'`; see {@link spawnProcess} */
153
+ function killOnTimeout(child, timeout) {
154
+ let timeoutId = setTimeout(() => {
155
+ if (timeoutId != null) {
156
+ try {
157
+ child.kill();
158
+ } catch (ex) {
159
+ child.emit("error", ex);
160
+ }
161
+ timeoutId = void 0;
162
+ }
163
+ }, timeout);
164
+ const clear = () => {
165
+ if (timeoutId != null) {
166
+ clearTimeout(timeoutId);
167
+ timeoutId = void 0;
168
+ }
169
+ };
170
+ child.once("exit", clear);
171
+ child.once("close", clear);
172
+ }
171
173
  const taskkillTimeout = 5e3;
172
174
  /**
173
175
  * Makes `kill` end the child's whole tree (Windows only). There `kill` terminates just the child, and a launcher such
@@ -217,9 +219,9 @@ function killTreeOnKill(child) {
217
219
  String(child.pid)
218
220
  ], {
219
221
  stdio: "ignore",
220
- windowsHide: true,
221
- timeout: taskkillTimeout
222
+ windowsHide: true
222
223
  });
224
+ killOnTimeout(taskkill, taskkillTimeout);
223
225
  taskkill.once("error", fail);
224
226
  taskkill.once("exit", (code) => {
225
227
  if (code !== 0) fail();
@@ -1 +1 @@
1
- {"version":3,"file":"exec.js","names":["joinPaths"],"sources":["../../../../../utils/src/env/node/exec.ts"],"sourcesContent":["import type { ChildProcess, ExecFileException, ExecFileOptions } from 'child_process';\nimport { execFile, spawn } from 'child_process';\nimport type { Stats } from 'fs';\nimport { access, constants } from 'fs';\nimport { stat } from 'fs/promises';\nimport { join as joinPaths } from 'path';\nimport * as process from 'process';\nimport type { Readable, Writable } from 'stream';\nimport type { CancellationReason } from '../../cancellation.js';\nimport { getScopedLogger, maybeStartScopedLogger } from '../../logger.scoped.js';\nimport { isWindows } from './platform.js';\n\n// -- Error types --\n\ninterface RunErrorContext {\n\tmessage: string;\n\tcmd?: string | undefined;\n\tkilled?: boolean | undefined;\n\tcode?: string | number | null | undefined;\n\tsignal?: NodeJS.Signals | undefined;\n}\n\nexport class RunError extends Error {\n\treadonly cmd?: string | undefined;\n\treadonly killed?: boolean | undefined;\n\treadonly code?: string | number | undefined;\n\treadonly signal?: NodeJS.Signals | undefined;\n\treadonly stdout: string;\n\treadonly stderr: string;\n\n\tconstructor(context: RunErrorContext, stdout: string, stderr: string) {\n\t\tsuper(context.message);\n\n\t\tthis.cmd = context.cmd;\n\t\tthis.killed = context.killed;\n\t\tthis.code = context.code ?? undefined;\n\t\tthis.signal = context.signal;\n\t\tthis.stdout = stdout?.trim() ?? '';\n\t\tthis.stderr = stderr?.trim() ?? '';\n\n\t\tthis.name = 'RunError';\n\t\tError.captureStackTrace?.(this, new.target);\n\t}\n}\n\nexport class CancelledRunError extends RunError {\n\treadonly reason: CancellationReason;\n\n\tconstructor(\n\t\tcmd: string,\n\t\tkilled: boolean,\n\t\tcode?: number | string | undefined,\n\t\tsignal: NodeJS.Signals = 'SIGTERM',\n\t\treason: CancellationReason = 'unknown',\n\t) {\n\t\tsuper(\n\t\t\t{ message: `Operation cancelled; command=${cmd}`, cmd: cmd, killed: killed, code: code, signal: signal },\n\t\t\t'',\n\t\t\t'',\n\t\t);\n\n\t\tthis.reason = reason;\n\n\t\tthis.name = 'CancelledRunError';\n\t\tError.captureStackTrace?.(this, new.target);\n\t}\n}\n\n// -- Execution utilities --\n\nconst slashesRegex = /[\\\\/]/;\nconst ps1Regex = /\\.ps1$/i;\nconst batOrCmdRegex = /\\.(bat|cmd)$/i;\nconst jsRegex = /\\.(js)$/i;\n\n/**\n * Search PATH to see if a file exists in any of the path folders.\n *\n * @param {string} exe The file to search for\n * @return {string} A fully qualified path, or the original path if nothing\n * is found\n *\n * @private\n */\nasync function runDownPath(exe: string): Promise<string> {\n\t// NB: Windows won't search PATH looking for executables in spawn like\n\t// Posix does\n\n\t// Files with any directory path don't get this applied\n\tif (slashesRegex.test(exe)) return exe;\n\n\tconst target = joinPaths('.', exe);\n\ttry {\n\t\tconst stats = await stat(target);\n\t\tif (stats?.isFile() && isExecutable(stats)) return target;\n\t} catch {}\n\n\tconst path = process.env.PATH;\n\tif (path != null && path.length !== 0) {\n\t\tconst haystack = path.split(isWindows ? ';' : ':');\n\t\tfor (const p of haystack) {\n\t\t\tconst needle = joinPaths(p, exe);\n\t\t\ttry {\n\t\t\t\tconst stats = await stat(needle);\n\t\t\t\tif (stats?.isFile() && isExecutable(stats)) return needle;\n\t\t\t} catch {}\n\t\t}\n\t}\n\n\treturn exe;\n}\n\nfunction isExecutable(stats: Stats) {\n\tif (isWindows) return true;\n\n\tconst isGroup = stats.gid ? stats.gid === process.getgid?.() : true;\n\tconst isUser = stats.uid ? stats.uid === process.getuid?.() : true;\n\n\treturn Boolean(stats.mode & 0o0001 || (stats.mode & 0o0010 && isGroup) || (stats.mode & 0o0100 && isUser));\n}\n\n/**\n * Finds the executable and parameters to run on Windows. This method\n * mimics the POSIX behavior of being able to run scripts as executables by\n * replacing the passed-in executable with the script runner, for PowerShell,\n * CMD, and node scripts.\n *\n * This method also does the work of running down PATH, which spawn on Windows\n * also doesn't do, unlike on POSIX.\n */\nexport async function findExecutable(exe: string, args: string[]): Promise<{ cmd: string; args: string[] }> {\n\t// POSIX can just execute scripts directly, no need for silly goosery\n\tif (!isWindows) return { cmd: await runDownPath(exe), args: args };\n\n\tif (!(await fsExists(exe))) {\n\t\t// NB: When you write something like `surf-client ... -- surf-build` on Windows,\n\t\t// a shell would normally convert that to surf-build.cmd, but since it's passed\n\t\t// in as an argument, it doesn't happen\n\t\tconst possibleExts = ['.exe', '.bat', '.cmd', '.ps1'];\n\t\tfor (const ext of possibleExts) {\n\t\t\tconst possibleFullPath = await runDownPath(`${exe}${ext}`);\n\n\t\t\tif (await fsExists(possibleFullPath)) return findExecutable(possibleFullPath, args);\n\t\t}\n\t}\n\n\tif (ps1Regex.test(exe)) {\n\t\tconst cmd = joinPaths(\n\t\t\tprocess.env.SYSTEMROOT ?? 'C:\\\\WINDOWS',\n\t\t\t'System32',\n\t\t\t'WindowsPowerShell',\n\t\t\t'v1.0',\n\t\t\t'PowerShell.exe',\n\t\t);\n\t\tconst psargs = ['-ExecutionPolicy', 'Unrestricted', '-NoLogo', '-NonInteractive', '-File', exe];\n\n\t\treturn { cmd: cmd, args: [...psargs, ...args] };\n\t}\n\n\tif (batOrCmdRegex.test(exe)) {\n\t\tconst cmd = joinPaths(process.env.SYSTEMROOT ?? 'C:\\\\WINDOWS', 'System32', 'cmd.exe');\n\t\tconst cmdArgs = ['/C', exe, ...args];\n\n\t\treturn { cmd: cmd, args: cmdArgs };\n\t}\n\n\tif (jsRegex.test(exe)) {\n\t\tconst cmd = process.execPath;\n\t\tconst nodeArgs = [exe];\n\n\t\treturn { cmd: cmd, args: [...nodeArgs, ...args] };\n\t}\n\n\treturn { cmd: exe, args: args };\n}\n\n/** What core uses of a spawned process; Node's `ChildProcess` satisfies it */\nexport interface SpawnedProcess {\n\treadonly stdin: Writable | null;\n\treadonly stdout: Readable | null;\n\treadonly stderr: Readable | null;\n\treadonly killed: boolean;\n\treadonly exitCode: number | null;\n\treadonly spawnargs: string[];\n\t/** Used to stop a run that passes its `maxBuffer`; without it the run destroys the output streams instead */\n\tkill?(signal?: NodeJS.Signals): boolean;\n\tonce(event: 'error', listener: (error: Error) => void): this;\n\tonce(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;\n\tremoveAllListeners(): this;\n}\n\nexport interface ProcessSpawnOptions {\n\treadonly cwd?: string;\n\t/** The child's whole environment, not additions to the spawner's own; an `undefined` value leaves the key out */\n\treadonly env?: Record<string, string | undefined>;\n\t/** Milliseconds; absent means none */\n\treadonly timeout?: number;\n\treadonly signal?: AbortSignal;\n\t/** A `null` entry means `'pipe'` */\n\treadonly stdio?: ['pipe' | 'ignore', null, null];\n}\n\n/**\n * Launches a process in place of Node's `spawn`, and must behave as it does:\n * - pipe stdout and stderr, and stdin unless `stdio[0]` is `'ignore'`, which leaves `stdin` null\n * - honour `signal`, including one already aborted: kill with SIGTERM, then emit `'error'` with `name` `AbortError`,\n * unless the process has already exited\n * - honour `timeout`: kill with SIGTERM and set `killed`, without emitting `'error'`\n * - report a killed process's `'close'` with a null code and its signal, not an exit code such as 143\n * - on Windows, end the process's whole tree when killing it (timeout, abort, or `kill`): a launcher such as Git for\n * Windows' `cmd\\git.exe` runs the real git as a child holding the same pipes, so killing only the launcher leaves\n * them open and `'close'` never comes\n * - emit no event before returning, `'error'` at most once, and `'close'` exactly once and last: also after `'error'`\n * (a failed launch, an abort), and only after `stdout` and `stderr` have ended or been destroyed, with `exitCode`\n * and `killed` already set\n * - close the child's stdout when `stdout` is destroyed, which is how a reader that stops early ends the process\n */\nexport type ProcessSpawner = (command: string, args: readonly string[], options: ProcessSpawnOptions) => SpawnedProcess;\n\n/**\n * The default {@link ProcessSpawner}: Node's `spawn`, but with its `timeout` handled here. Node clears its timeout\n * timer only on `'exit'`, which a failed launch (e.g. a missing `cwd`) never emits, so the timer outlives the\n * process and keeps Node alive for the full timeout. This mirrors Node's timeout handling but also clears on\n * `'close'`, as https://github.com/nodejs/node/pull/65506 does; remove it once the minimum supported Node/Electron\n * includes that fix.\n */\nexport function spawnProcess(command: string, args: readonly string[], options: ProcessSpawnOptions): ChildProcess {\n\tconst { timeout, ...spawnOptions } = options;\n\t// Node's own validation, thrown before anything spawns\n\tif (timeout != null && !(Number.isInteger(timeout) && timeout >= 0)) {\n\t\tconst ex = new RangeError(\n\t\t\t`The value of \"timeout\" is out of range. It must be an unsigned integer. Received ${String(timeout)}`,\n\t\t);\n\t\t(ex as RangeError & { code: string }).code = 'ERR_OUT_OF_RANGE';\n\t\tthrow ex;\n\t}\n\n\tconst child = spawn(command, args, spawnOptions);\n\tif (isWindows) {\n\t\tkillTreeOnKill(child);\n\t}\n\n\tif (timeout != null && timeout > 0) {\n\t\tlet timeoutId: ReturnType<typeof setTimeout> | undefined = setTimeout(() => {\n\t\t\tif (timeoutId != null) {\n\t\t\t\ttry {\n\t\t\t\t\tchild.kill();\n\t\t\t\t} catch (ex) {\n\t\t\t\t\tchild.emit('error', ex);\n\t\t\t\t}\n\t\t\t\ttimeoutId = undefined;\n\t\t\t}\n\t\t}, timeout);\n\n\t\tconst clear = () => {\n\t\t\tif (timeoutId != null) {\n\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\ttimeoutId = undefined;\n\t\t\t}\n\t\t};\n\t\t// `'exit'` keeps Node's timing; `'close'` covers a launch that fails and never exits\n\t\tchild.once('exit', clear);\n\t\tchild.once('close', clear);\n\t}\n\n\treturn child;\n}\n\nconst taskkillTimeout = 5000;\n\n/**\n * Makes `kill` end the child's whole tree (Windows only). There `kill` terminates just the child, and a launcher such\n * as Git for Windows' `cmd\\git.exe` runs the real git as its own child on the same stdout and stderr, so the pipes\n * stay open and `'close'` never comes. Node's abort and timeout paths call the instance's `kill`, so this covers them.\n */\nfunction killTreeOnKill(child: ChildProcess): void {\n\tconst kill = child.kill.bind(child);\n\tconst mutable = child as { killed: boolean; exitCode: number | null; signalCode: NodeJS.Signals | null };\n\tlet killing = false;\n\n\tchild.kill = (signal?: NodeJS.Signals | number): boolean => {\n\t\tif (child.pid == null || child.exitCode !== null || child.signalCode !== null || typeof signal === 'number') {\n\t\t\treturn kill(signal);\n\t\t}\n\t\tif (killing) return true;\n\n\t\tkilling = true;\n\t\tconst killSignal = signal ?? 'SIGTERM';\n\t\tmutable.killed = true;\n\n\t\t// Killed from outside, the child exits with taskkill's code 1 and no signal; report it as Node's own kill\n\t\t// would, a null code and the signal, which is what every caller keys on\n\t\tlet exitCode: number | null = child.exitCode;\n\t\tObject.defineProperty(child, 'exitCode', {\n\t\t\tconfigurable: true,\n\t\t\tenumerable: true,\n\t\t\tget: () => exitCode,\n\t\t\tset: (value: number | null) => {\n\t\t\t\tif (value === 1) {\n\t\t\t\t\texitCode = null;\n\t\t\t\t\tmutable.signalCode = killSignal;\n\t\t\t\t} else {\n\t\t\t\t\texitCode = value;\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\n\t\t// Once it's killed, a descendant left alive (taskkill failed, or its parent was already gone) can still hold the\n\t\t// pipes; destroying them lets `'close'` come anyway. A child that exited on its own keeps its output\n\t\tchild.once('exit', (_code, exitSignal) => {\n\t\t\tif (exitSignal == null) return;\n\n\t\t\tchild.stdout?.destroy();\n\t\t\tchild.stderr?.destroy();\n\t\t});\n\n\t\t// taskkill failed: fall back to Node's kill, unless the child already exited on its own\n\t\tlet failed = false;\n\t\tconst fail = () => {\n\t\t\tif (failed || child.exitCode !== null || child.signalCode !== null) return;\n\n\t\t\tfailed = true;\n\t\t\ttry {\n\t\t\t\tkill(killSignal);\n\t\t\t} catch {}\n\t\t};\n\n\t\ttry {\n\t\t\t// By absolute path: Windows searches the current directory before PATH for a bare name. Its own time limit\n\t\t\t// keeps a stalled taskkill from leaving the kill, and so the run, hanging\n\t\t\tconst taskkill = spawn(\n\t\t\t\tjoinPaths(process.env.SystemRoot || 'C:\\\\Windows', 'System32', 'taskkill.exe'),\n\t\t\t\t['/T', '/F', '/PID', String(child.pid)],\n\t\t\t\t{ stdio: 'ignore', windowsHide: true, timeout: taskkillTimeout },\n\t\t\t);\n\t\t\ttaskkill.once('error', fail);\n\t\t\ttaskkill.once('exit', code => {\n\t\t\t\tif (code !== 0) {\n\t\t\t\t\tfail();\n\t\t\t\t}\n\t\t\t});\n\t\t} catch {\n\t\t\tfail();\n\t\t}\n\n\t\treturn true;\n\t};\n}\n\nexport interface RunOptions<TEncoding = BufferEncoding | 'buffer'> {\n\tcwd?: string;\n\treadonly env?: Record<string, string | undefined>;\n\treadonly encoding?: TEncoding;\n\t/**\n\t * Decodes non-UTF-8 output. Called when `encoding` is not utf8/binary/buffer.\n\t * Provided by the host via the `GitOptions.decode` option.\n\t * If absent and a non-UTF-8 encoding is requested, throws at runtime.\n\t */\n\treadonly decode?: (data: Uint8Array, options?: { readonly encoding: string }) => string | Promise<string>;\n\t/**\n\t * The most bytes each of stdout and stderr may produce; past it the process is killed and the run rejects\n\t * with a `RunError` whose `code` is `ERR_CHILD_PROCESS_STDIO_MAXBUFFER`.\n\t *\n\t * If not specified, `run` allows 1000MB per stream and `runSpawn` allows unlimited output.\n\t */\n\treadonly maxBuffer?: number;\n\treadonly cancellation?: AbortSignal;\n\t/**\n\t * An optional string or buffer which will be written to\n\t * the child process stdin stream immediately immediately\n\t * after spawning the process.\n\t */\n\treadonly stdin?: string | Buffer;\n\t/**\n\t * The encoding to use when writing to stdin, if the stdin\n\t * parameter is a string.\n\t */\n\treadonly stdinEncoding?: string;\n\treadonly timeout?: number;\n\t/**\n\t * When true, suppresses the `[EXEC]` stderr warning emitted on debug-enabled scopes.\n\t * Use for commands whose failure is expected (e.g. paired with `errors: 'ignore'`).\n\t */\n\treadonly quiet?: boolean;\n\t/** Launches the process; defaults to {@link spawnProcess}. Only used by `runSpawn` */\n\treadonly spawn?: ProcessSpawner;\n}\n\nconst bufferExceededRegex = /stdout maxBuffer( length)? exceeded/;\n\ntype ExitCodeOnlyRunOptions<TEncoding = BufferEncoding | 'buffer'> = RunOptions<TEncoding> & { exitCodeOnly: true };\n\nexport function run(\n\tcommand: string,\n\targs: readonly string[],\n\tencoding: BufferEncoding | string,\n\toptions: ExitCodeOnlyRunOptions<BufferEncoding>,\n): Promise<number>;\nexport function run(\n\tcommand: string,\n\targs: readonly string[],\n\tencoding: BufferEncoding | string,\n\toptions?: RunOptions<BufferEncoding>,\n): Promise<string>;\nexport function run<T extends number | string>(\n\tcommand: string,\n\targs: readonly string[],\n\tencoding: BufferEncoding | string,\n\toptions?: RunOptions<BufferEncoding> & { exitCodeOnly?: boolean },\n): Promise<T> {\n\tconst scope = getScopedLogger() ?? maybeStartScopedLogger('Exec.run');\n\n\tconst { stdin, stdinEncoding, cancellation, decode, ...opts }: RunOptions<BufferEncoding> & ExecFileOptions = {\n\t\tmaxBuffer: 1000 * 1024 * 1024,\n\t\t...options,\n\t};\n\n\tconst promise = new Promise<T>((resolve, reject) => {\n\t\tconst proc = execFile(\n\t\t\tcommand,\n\t\t\targs,\n\t\t\t{ ...opts, signal: cancellation },\n\t\t\tasync (error: ExecFileException | null, stdout, stderr) => {\n\t\t\t\tif (options?.exitCodeOnly) {\n\t\t\t\t\tresolve((error?.code ?? proc.exitCode) as T);\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (error != null) {\n\t\t\t\t\tif (error.signal === 'SIGTERM') {\n\t\t\t\t\t\treject(\n\t\t\t\t\t\t\tnew CancelledRunError(\n\t\t\t\t\t\t\t\t`${command} ${args.join(' ')}`,\n\t\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\t\terror.code ?? undefined,\n\t\t\t\t\t\t\t\terror.signal,\n\t\t\t\t\t\t\t\tcancellation?.aborted ? 'aborted' : error.killed ? 'timeout' : 'unknown',\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (bufferExceededRegex.test(error.message)) {\n\t\t\t\t\t\terror.message = `Command output exceeded the allocated stdout buffer. Set 'options.maxBuffer' to a larger value than ${opts.maxBuffer} bytes`;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet stdoutDecoded: string;\n\t\t\t\t\tlet stderrDecoded: string;\n\t\t\t\t\tif (encoding === 'utf8' || encoding === 'binary' || encoding === 'buffer') {\n\t\t\t\t\t\t// stdout & stderr can be `Buffer` or `string\n\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unnecessary-type-conversion\n\t\t\t\t\t\tstdoutDecoded = stdout.toString();\n\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unnecessary-type-conversion\n\t\t\t\t\t\tstderrDecoded = stderr.toString();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (decode == null) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Non-UTF-8 encoding '${encoding}' requested but no decode function configured`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstdoutDecoded = await decode(\n\t\t\t\t\t\t\tBuffer.from(stdout, 'binary'),\n\t\t\t\t\t\t\tencoding ? { encoding: encoding } : undefined,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tstderrDecoded = await decode(\n\t\t\t\t\t\t\tBuffer.from(stderr, 'binary'),\n\t\t\t\t\t\t\tencoding ? { encoding: encoding } : undefined,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treject(new RunError(error, stdoutDecoded, stderrDecoded));\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (stderr && !options?.quiet && scope?.enabled('debug')) {\n\t\t\t\t\tscope?.warn(`[EXEC] '${command} ${args.join(' ')}' \\u2022 ${stderr}`);\n\t\t\t\t}\n\n\t\t\t\tif (encoding === 'utf8' || encoding === 'binary' || encoding === 'buffer') {\n\t\t\t\t\tresolve(stdout as T);\n\t\t\t\t} else {\n\t\t\t\t\tif (decode == null) {\n\t\t\t\t\t\tthrow new Error(`Non-UTF-8 encoding '${encoding}' requested but no decode function configured`);\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve(\n\t\t\t\t\t\t(await decode(\n\t\t\t\t\t\t\tBuffer.from(stdout, 'binary'),\n\t\t\t\t\t\t\tencoding ? { encoding: encoding } : undefined,\n\t\t\t\t\t\t)) as T,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\t\tif (stdin != null) {\n\t\t\tendStdin(proc.stdin, stdin, stdinEncoding);\n\t\t}\n\t});\n\n\treturn promise.finally(() => scope?.[Symbol.dispose]());\n}\n\n/**\n * Writes a child's whole input and closes it. A child can exit, or be killed on cancellation, before reading all of\n * it, and the pipe then errors (EPIPE, or EOF on Windows). Unlistened, that error is thrown as an uncaught exception\n * and takes down the whole host process, so it is dropped: the child's exit status and stderr already report the\n * failure, and a child that chose to stop reading answered from what it read.\n */\nexport function endStdin(stream: Writable | null, stdin: string | Buffer, stdinEncoding: string | undefined): void {\n\tif (stream == null) return;\n\n\tstream.on('error', () => {});\n\tif (typeof stdin === 'string') {\n\t\tstream.end(stdin, (stdinEncoding ?? 'utf8') as BufferEncoding);\n\t} else {\n\t\tstream.end(stdin);\n\t}\n}\n\nexport interface RunExitResult {\n\t/**\n\t * The process's exit code. ABSENT when the process never exited normally — killed by a signal, in which\n\t * case {@link signal} is set. Deliberately optional rather than defaulted to `0`: a signalled process\n\t * reported as `exitCode: 0` is indistinguishable from a clean success, so callers would read a partial\n\t * or empty stdout as a complete answer.\n\t */\n\treadonly exitCode?: number;\n\t/** Set when the process was terminated by a signal instead of exiting; {@link exitCode} is then absent. */\n\treadonly signal?: NodeJS.Signals;\n\t/** Whether Node itself killed the process (its spawn `timeout`), as opposed to an external signal. */\n\treadonly killed?: boolean;\n}\n\nexport interface RunResult<T extends string | Buffer> extends RunExitResult {\n\tstdout: T;\n\tstderr: T;\n}\n\nexport function runSpawn(\n\tcommand: string,\n\targs: readonly string[],\n\tencoding: BufferEncoding | 'buffer' | string,\n\toptions: ExitCodeOnlyRunOptions,\n): Promise<RunExitResult>;\nexport function runSpawn<T extends string | Buffer>(\n\tcommand: string,\n\targs: readonly string[],\n\tencoding: BufferEncoding | 'buffer' | string,\n\toptions: RunOptions,\n): Promise<RunResult<T>>;\nexport function runSpawn<T extends string | Buffer>(\n\tcommand: string,\n\targs: readonly string[],\n\tencoding: BufferEncoding | 'buffer' | string,\n\toptions: RunOptions & { exitCodeOnly?: boolean },\n): Promise<RunExitResult | RunResult<T>> {\n\tconst scope = getScopedLogger() ?? maybeStartScopedLogger('Exec.runSpawn');\n\n\tconst { stdin, stdinEncoding, cancellation, decode, spawn: spawner, ...opts }: RunOptions = options;\n\n\tconst promise = new Promise<RunExitResult | RunResult<T>>((resolve, reject) => {\n\t\tconst proc = (spawner ?? spawnProcess)(command, args, {\n\t\t\tcwd: opts.cwd,\n\t\t\tenv: opts.env,\n\t\t\t// 0 disables it, which the spawner contract spells as absent\n\t\t\ttimeout: opts.timeout === 0 ? undefined : opts.timeout,\n\t\t\tsignal: cancellation,\n\t\t\tstdio: [stdin != null ? 'pipe' : 'ignore', null, null],\n\t\t});\n\t\tconst errorEncoding = encoding === 'buffer' ? 'utf8' : encoding;\n\n\t\tconst maxBuffer = opts.maxBuffer != null && opts.maxBuffer > 0 ? opts.maxBuffer : undefined;\n\t\tlet limitHit = false;\n\n\t\tfunction collector(buffers: Buffer[], name: 'stdout' | 'stderr'): (data: Buffer) => void {\n\t\t\tlet size = 0;\n\t\t\treturn (data: Buffer) => {\n\t\t\t\tif (limitHit) return;\n\n\t\t\t\tsize += data.length;\n\t\t\t\tif (maxBuffer != null && size > maxBuffer) {\n\t\t\t\t\texceedLimit(name);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tbuffers.push(data);\n\t\t\t};\n\t\t}\n\n\t\tconst stdoutBuffers: Buffer[] = [];\n\t\tconst collectStdout = collector(stdoutBuffers, 'stdout');\n\t\tproc.stdout?.on('data', collectStdout);\n\n\t\tconst stderrBuffers: Buffer[] = [];\n\t\tconst collectStderr = collector(stderrBuffers, 'stderr');\n\t\tproc.stderr?.on('data', collectStderr);\n\n\t\t// Settles the run as soon as a stream passes the limit. Destroying the streams ends a spawner whose process\n\t\t// has no `kill`, and the late `'close'` or `'error'` is ignored through `limitHit`\n\t\tfunction exceedLimit(name: 'stdout' | 'stderr'): void {\n\t\t\tlimitHit = true;\n\t\t\tstdoutBuffers.length = 0;\n\t\t\tstderrBuffers.length = 0;\n\t\t\tproc.stdout?.off('data', collectStdout);\n\t\t\tproc.stderr?.off('data', collectStderr);\n\n\t\t\ttry {\n\t\t\t\tproc.kill?.();\n\t\t\t} catch {}\n\t\t\tproc.stdout?.destroy();\n\t\t\tproc.stderr?.destroy();\n\n\t\t\treject(\n\t\t\t\tnew RunError(\n\t\t\t\t\t{\n\t\t\t\t\t\tmessage: `Command output exceeded the allocated ${name} buffer. Set 'options.maxBuffer' to a larger value than ${maxBuffer} bytes`,\n\t\t\t\t\t\tcmd: `${command} ${args.join(' ')}`,\n\t\t\t\t\t\tkilled: true,\n\t\t\t\t\t\tcode: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER',\n\t\t\t\t\t},\n\t\t\t\t\t'',\n\t\t\t\t\t'',\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\tfunction getStdio<T>(\n\t\t\tencoding: BufferEncoding | 'buffer' | string,\n\t\t): { stdout: T; stderr: T } | Promise<{ stdout: T; stderr: T }> {\n\t\t\tconst stdout = Buffer.concat(stdoutBuffers);\n\t\t\tconst stderr = Buffer.concat(stderrBuffers);\n\t\t\tif (encoding === 'utf8' || encoding === 'binary') {\n\t\t\t\treturn { stdout: stdout.toString(encoding) as T, stderr: stderr.toString(encoding) as T };\n\t\t\t}\n\t\t\tif (encoding === 'buffer') {\n\t\t\t\treturn { stdout: stdout as T, stderr: stderr as T };\n\t\t\t}\n\n\t\t\tif (decode == null) {\n\t\t\t\tthrow new Error(`Non-UTF-8 encoding '${encoding}' requested but no decode function configured`);\n\t\t\t}\n\n\t\t\treturn Promise.all([\n\t\t\t\tdecode(stdout, encoding ? { encoding: encoding } : undefined),\n\t\t\t\tdecode(stderr, encoding ? { encoding: encoding } : undefined),\n\t\t\t]).then(([decodedStdout, decodedStderr]) => ({\n\t\t\t\tstdout: decodedStdout as T,\n\t\t\t\tstderr: decodedStderr as T,\n\t\t\t}));\n\t\t}\n\n\t\t// An async listener's throw would be an unhandled rejection that leaves the promise pending forever, so\n\t\t// anything it throws (an undecodable output, a failing `decode`) rejects the run instead. It rejects as\n\t\t// thrown: wrapped in a `RunError` with the exit code, a clean exit would read as a run with no output\n\t\tconst rejectThrown = (ex: unknown): void => reject(ex instanceof Error ? ex : new Error(String(ex)));\n\t\tproc.once('error', ex => void onError(ex).catch(rejectThrown));\n\t\tproc.once('close', (code, signal) => void onClose(code, signal).catch(rejectThrown));\n\n\t\tasync function onError(ex: Error): Promise<void> {\n\t\t\tif (limitHit) return;\n\n\t\t\tif (ex?.name === 'AbortError') {\n\t\t\t\treject(new CancelledRunError(`${command} ${args.join(' ')}`, true, undefined, undefined, 'aborted'));\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// The launch failure is what the caller acts on, so output that can't be decoded is left out of it\n\t\t\tlet stdout = '';\n\t\t\tlet stderr = '';\n\t\t\ttry {\n\t\t\t\tconst stdio = getStdio<string>(errorEncoding);\n\t\t\t\t({ stdout, stderr } = stdio instanceof Promise ? await stdio : stdio);\n\t\t\t} catch {}\n\n\t\t\treject(new RunError(ex, stdout, stderr));\n\t\t}\n\n\t\tasync function onClose(code: number | null, signal: NodeJS.Signals | null): Promise<void> {\n\t\t\tif (limitHit) return;\n\n\t\t\tif (options?.exitCodeOnly) {\n\t\t\t\t// Resolves unconditionally, so this is the one path that can hand back a signalled run. `code`\n\t\t\t\t// is null exactly when the process was killed — report the signal rather than coercing to `0`,\n\t\t\t\t// which would claim a clean success for a command that never finished. Note this returns BEFORE\n\t\t\t\t// the SIGTERM-to-cancellation diversion below, so callers have to classify that themselves.\n\t\t\t\tresolve({ exitCode: code ?? undefined, signal: signal ?? undefined, killed: proc.killed });\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (code !== 0 || signal) {\n\t\t\t\tconst stdio = getStdio<string>(errorEncoding);\n\t\t\t\tconst { stdout, stderr } = stdio instanceof Promise ? await stdio : stdio;\n\t\t\t\tif (stderr.length && !options?.quiet && scope?.enabled('debug')) {\n\t\t\t\t\tscope?.warn(`[EXEC] '${command} ${args.join(' ')}' \\u2022 ${stderr}`);\n\t\t\t\t}\n\n\t\t\t\tif (signal === 'SIGTERM') {\n\t\t\t\t\t// Only Node's spawn `timeout` kills it (a caller abort rejected above, from `'error'`); an\n\t\t\t\t\t// external SIGTERM leaves `proc.killed` false\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew CancelledRunError(\n\t\t\t\t\t\t\t`${command} ${args.join(' ')}`,\n\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\tcode ?? undefined,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tproc.killed ? 'timeout' : 'unknown',\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\treject(\n\t\t\t\t\tnew RunError(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmessage: `Command failed with exit code ${code}`,\n\t\t\t\t\t\t\tcode: code,\n\t\t\t\t\t\t\tsignal: signal ?? undefined,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstdout,\n\t\t\t\t\t\tstderr,\n\t\t\t\t\t),\n\t\t\t\t);\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst stdio = getStdio<T>(encoding);\n\t\t\tconst { stdout, stderr } = stdio instanceof Promise ? await stdio : stdio;\n\t\t\tif (stderr.length && !options?.quiet && scope?.enabled('debug')) {\n\t\t\t\tscope?.warn(\n\t\t\t\t\t`[EXEC] '${command} ${args.join(' ')}' \\u2022 ${typeof stderr === 'string' ? stderr : stderr.toString()}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// The guard above already rejected every non-zero and every signalled close, so this is a clean\n\t\t\t// zero exit — `code` cannot be null here. (The optional typing exists for the `exitCodeOnly`\n\t\t\t// branch, which is where a codeless result can genuinely surface.)\n\t\t\tresolve({ exitCode: code ?? undefined, signal: signal ?? undefined, stdout: stdout, stderr: stderr });\n\t\t}\n\n\t\t// Only a host spawner can leave these out; reading no output as empty would pass for a clean answer\n\t\tif (proc.stdout == null || proc.stderr == null) {\n\t\t\treject(new Error(`'${command}' was spawned without stdout and stderr pipes`));\n\t\t}\n\n\t\tif (stdin != null) {\n\t\t\tendStdin(proc.stdin, stdin, stdinEncoding);\n\t\t}\n\t});\n\n\treturn promise.finally(() => scope?.[Symbol.dispose]());\n}\n\nexport async function fsExists(path: string): Promise<boolean> {\n\treturn new Promise<boolean>(resolve => access(path, constants.F_OK, err => resolve(err == null)));\n}\n"],"mappings":";;;;;;;;AAsBA,IAAa,WAAb,cAA8B,MAAM;CACnC;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAA0B,QAAgB,QAAgB;EACrE,MAAM,QAAQ,OAAO;EAErB,KAAK,MAAM,QAAQ;EACnB,KAAK,SAAS,QAAQ;EACtB,KAAK,OAAO,QAAQ,QAAQ,KAAA;EAC5B,KAAK,SAAS,QAAQ;EACtB,KAAK,SAAS,QAAQ,KAAK,KAAK;EAChC,KAAK,SAAS,QAAQ,KAAK,KAAK;EAEhC,KAAK,OAAO;EACZ,MAAM,oBAAoB,MAAM,UAAU;CAC3C;AACD;AAEA,IAAa,oBAAb,cAAuC,SAAS;CAC/C;CAEA,YACC,KACA,QACA,MACA,SAAyB,WACzB,SAA6B,WAC5B;EACD,MACC;GAAE,SAAS,gCAAgC;GAAY;GAAa;GAAc;GAAc;EAAO,GACvG,IACA,EACD;EAEA,KAAK,SAAS;EAEd,KAAK,OAAO;EACZ,MAAM,oBAAoB,MAAM,UAAU;CAC3C;AACD;AAIA,MAAM,eAAe;AACrB,MAAM,WAAW;AACjB,MAAM,gBAAgB;AACtB,MAAM,UAAU;;;;;;;;;;AAWhB,eAAe,YAAY,KAA8B;CAKxD,IAAI,aAAa,KAAK,GAAG,GAAG,OAAO;CAEnC,MAAM,SAASA,KAAU,KAAK,GAAG;CACjC,IAAI;EACH,MAAM,QAAQ,MAAM,KAAK,MAAM;EAC/B,IAAI,OAAO,OAAO,KAAK,aAAa,KAAK,GAAG,OAAO;CACpD,QAAQ,CAAC;CAET,MAAM,OAAO,QAAQ,IAAI;CACzB,IAAI,QAAQ,QAAQ,KAAK,WAAW,GAAG;EACtC,MAAM,WAAW,KAAK,MAAM,YAAY,MAAM,GAAG;EACjD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AAE,WAAW,OAAO,WAAW,WAAW,SAAS,OAAO,SAAS,GACvG;GAMD,QAAQ;IAAE,UAAU,QAAQ,KAAA;IAAW,QAAQ,UAAU,KAAA;IAAmB;IAAgB;GAAO,CAAC;EACrG;EAGA,IAAI,KAAK,UAAU,QAAQ,KAAK,UAAU,MACzC,uBAAO,IAAI,MAAM,IAAI,QAAQ,8CAA8C,CAAC;EAG7E,IAAI,SAAS,MACZ,SAAS,KAAK,OAAO,OAAO,aAAa;CAE3C,CAEa,CAAC,CAAC,cAAc,QAAQ,OAAO,QAAQ,CAAC,CAAC;AACvD;AAEA,eAAsB,SAAS,MAAgC;CAC9D,OAAO,IAAI,SAAiB,YAAW,OAAO,MAAM,UAAU,OAAM,QAAO,QAAQ,OAAO,IAAI,CAAC,CAAC;AACjG"}
1
+ {"version":3,"file":"exec.js","names":["joinPaths"],"sources":["../../../../../utils/src/env/node/exec.ts"],"sourcesContent":["import type { ChildProcess, ExecFileException, ExecFileOptions } from 'child_process';\nimport { execFile, spawn } from 'child_process';\nimport type { Stats } from 'fs';\nimport { access, constants } from 'fs';\nimport { stat } from 'fs/promises';\nimport { join as joinPaths } from 'path';\nimport * as process from 'process';\nimport type { Readable, Writable } from 'stream';\nimport type { CancellationReason } from '../../cancellation.js';\nimport { getScopedLogger, maybeStartScopedLogger } from '../../logger.scoped.js';\nimport { isWindows } from './platform.js';\n\n// -- Error types --\n\ninterface RunErrorContext {\n\tmessage: string;\n\tcmd?: string | undefined;\n\tkilled?: boolean | undefined;\n\tcode?: string | number | null | undefined;\n\tsignal?: NodeJS.Signals | undefined;\n}\n\nexport class RunError extends Error {\n\treadonly cmd?: string | undefined;\n\treadonly killed?: boolean | undefined;\n\treadonly code?: string | number | undefined;\n\treadonly signal?: NodeJS.Signals | undefined;\n\treadonly stdout: string;\n\treadonly stderr: string;\n\n\tconstructor(context: RunErrorContext, stdout: string, stderr: string) {\n\t\tsuper(context.message);\n\n\t\tthis.cmd = context.cmd;\n\t\tthis.killed = context.killed;\n\t\tthis.code = context.code ?? undefined;\n\t\tthis.signal = context.signal;\n\t\tthis.stdout = stdout?.trim() ?? '';\n\t\tthis.stderr = stderr?.trim() ?? '';\n\n\t\tthis.name = 'RunError';\n\t\tError.captureStackTrace?.(this, new.target);\n\t}\n}\n\nexport class CancelledRunError extends RunError {\n\treadonly reason: CancellationReason;\n\n\tconstructor(\n\t\tcmd: string,\n\t\tkilled: boolean,\n\t\tcode?: number | string | undefined,\n\t\tsignal: NodeJS.Signals = 'SIGTERM',\n\t\treason: CancellationReason = 'unknown',\n\t) {\n\t\tsuper(\n\t\t\t{ message: `Operation cancelled; command=${cmd}`, cmd: cmd, killed: killed, code: code, signal: signal },\n\t\t\t'',\n\t\t\t'',\n\t\t);\n\n\t\tthis.reason = reason;\n\n\t\tthis.name = 'CancelledRunError';\n\t\tError.captureStackTrace?.(this, new.target);\n\t}\n}\n\n// -- Execution utilities --\n\nconst slashesRegex = /[\\\\/]/;\nconst ps1Regex = /\\.ps1$/i;\nconst batOrCmdRegex = /\\.(bat|cmd)$/i;\nconst jsRegex = /\\.(js)$/i;\n\n/**\n * Search PATH to see if a file exists in any of the path folders.\n *\n * @param {string} exe The file to search for\n * @return {string} A fully qualified path, or the original path if nothing\n * is found\n *\n * @private\n */\nasync function runDownPath(exe: string): Promise<string> {\n\t// NB: Windows won't search PATH looking for executables in spawn like\n\t// Posix does\n\n\t// Files with any directory path don't get this applied\n\tif (slashesRegex.test(exe)) return exe;\n\n\tconst target = joinPaths('.', exe);\n\ttry {\n\t\tconst stats = await stat(target);\n\t\tif (stats?.isFile() && isExecutable(stats)) return target;\n\t} catch {}\n\n\tconst path = process.env.PATH;\n\tif (path != null && path.length !== 0) {\n\t\tconst haystack = path.split(isWindows ? ';' : ':');\n\t\tfor (const p of haystack) {\n\t\t\tconst needle = joinPaths(p, exe);\n\t\t\ttry {\n\t\t\t\tconst stats = await stat(needle);\n\t\t\t\tif (stats?.isFile() && isExecutable(stats)) return needle;\n\t\t\t} catch {}\n\t\t}\n\t}\n\n\treturn exe;\n}\n\nfunction isExecutable(stats: Stats) {\n\tif (isWindows) return true;\n\n\tconst isGroup = stats.gid ? stats.gid === process.getgid?.() : true;\n\tconst isUser = stats.uid ? stats.uid === process.getuid?.() : true;\n\n\treturn Boolean(stats.mode & 0o0001 || (stats.mode & 0o0010 && isGroup) || (stats.mode & 0o0100 && isUser));\n}\n\n/**\n * Finds the executable and parameters to run on Windows. This method\n * mimics the POSIX behavior of being able to run scripts as executables by\n * replacing the passed-in executable with the script runner, for PowerShell,\n * CMD, and node scripts.\n *\n * This method also does the work of running down PATH, which spawn on Windows\n * also doesn't do, unlike on POSIX.\n */\nexport async function findExecutable(exe: string, args: string[]): Promise<{ cmd: string; args: string[] }> {\n\t// POSIX can just execute scripts directly, no need for silly goosery\n\tif (!isWindows) return { cmd: await runDownPath(exe), args: args };\n\n\tif (!(await fsExists(exe))) {\n\t\t// NB: When you write something like `surf-client ... -- surf-build` on Windows,\n\t\t// a shell would normally convert that to surf-build.cmd, but since it's passed\n\t\t// in as an argument, it doesn't happen\n\t\tconst possibleExts = ['.exe', '.bat', '.cmd', '.ps1'];\n\t\tfor (const ext of possibleExts) {\n\t\t\tconst possibleFullPath = await runDownPath(`${exe}${ext}`);\n\n\t\t\tif (await fsExists(possibleFullPath)) return findExecutable(possibleFullPath, args);\n\t\t}\n\t}\n\n\tif (ps1Regex.test(exe)) {\n\t\tconst cmd = joinPaths(\n\t\t\tprocess.env.SYSTEMROOT ?? 'C:\\\\WINDOWS',\n\t\t\t'System32',\n\t\t\t'WindowsPowerShell',\n\t\t\t'v1.0',\n\t\t\t'PowerShell.exe',\n\t\t);\n\t\tconst psargs = ['-ExecutionPolicy', 'Unrestricted', '-NoLogo', '-NonInteractive', '-File', exe];\n\n\t\treturn { cmd: cmd, args: [...psargs, ...args] };\n\t}\n\n\tif (batOrCmdRegex.test(exe)) {\n\t\tconst cmd = joinPaths(process.env.SYSTEMROOT ?? 'C:\\\\WINDOWS', 'System32', 'cmd.exe');\n\t\tconst cmdArgs = ['/C', exe, ...args];\n\n\t\treturn { cmd: cmd, args: cmdArgs };\n\t}\n\n\tif (jsRegex.test(exe)) {\n\t\tconst cmd = process.execPath;\n\t\tconst nodeArgs = [exe];\n\n\t\treturn { cmd: cmd, args: [...nodeArgs, ...args] };\n\t}\n\n\treturn { cmd: exe, args: args };\n}\n\n/** What core uses of a spawned process; Node's `ChildProcess` satisfies it */\nexport interface SpawnedProcess {\n\treadonly stdin: Writable | null;\n\treadonly stdout: Readable | null;\n\treadonly stderr: Readable | null;\n\treadonly killed: boolean;\n\treadonly exitCode: number | null;\n\treadonly spawnargs: string[];\n\t/** Used to stop a run that passes its `maxBuffer`; without it the run destroys the output streams instead */\n\tkill?(signal?: NodeJS.Signals): boolean;\n\tonce(event: 'error', listener: (error: Error) => void): this;\n\tonce(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;\n\tremoveAllListeners(): this;\n}\n\nexport interface ProcessSpawnOptions {\n\treadonly cwd?: string;\n\t/** The child's whole environment, not additions to the spawner's own; an `undefined` value leaves the key out */\n\treadonly env?: Record<string, string | undefined>;\n\t/** Milliseconds; absent means none */\n\treadonly timeout?: number;\n\treadonly signal?: AbortSignal;\n\t/** A `null` entry means `'pipe'` */\n\treadonly stdio?: ['pipe' | 'ignore', null, null];\n}\n\n/**\n * Launches a process in place of Node's `spawn`, and must behave as it does:\n * - pipe stdout and stderr, and stdin unless `stdio[0]` is `'ignore'`, which leaves `stdin` null\n * - honour `signal`, including one already aborted: kill with SIGTERM, then emit `'error'` with `name` `AbortError`,\n * unless the process has already exited\n * - honour `timeout`: kill with SIGTERM and set `killed`, without emitting `'error'`\n * - report a killed process's `'close'` with a null code and its signal, not an exit code such as 143\n * - on Windows, end the process's whole tree when killing it (timeout, abort, or `kill`): a launcher such as Git for\n * Windows' `cmd\\git.exe` runs the real git as a child holding the same pipes, so killing only the launcher leaves\n * them open and `'close'` never comes\n * - emit no event before returning, `'error'` at most once, and `'close'` exactly once and last: also after `'error'`\n * (a failed launch, an abort), and only after `stdout` and `stderr` have ended or been destroyed, with `exitCode`\n * and `killed` already set\n * - close the child's stdout when `stdout` is destroyed, which is how a reader that stops early ends the process\n */\nexport type ProcessSpawner = (command: string, args: readonly string[], options: ProcessSpawnOptions) => SpawnedProcess;\n\n/**\n * The default {@link ProcessSpawner}: Node's `spawn`, but with its `timeout` handled here. Node clears its timeout\n * timer only on `'exit'`, which a failed launch (e.g. a missing `cwd`) never emits, so the timer outlives the\n * process and keeps Node alive for the full timeout. This mirrors Node's timeout handling but also clears on\n * `'close'`, as https://github.com/nodejs/node/pull/65506 does; remove it once the minimum supported Node/Electron\n * includes that fix.\n */\nexport function spawnProcess(command: string, args: readonly string[], options: ProcessSpawnOptions): ChildProcess {\n\tconst { timeout, ...spawnOptions } = options;\n\t// Node's own validation, thrown before anything spawns\n\tif (timeout != null && !(Number.isInteger(timeout) && timeout >= 0)) {\n\t\tconst ex = new RangeError(\n\t\t\t`The value of \"timeout\" is out of range. It must be an unsigned integer. Received ${String(timeout)}`,\n\t\t);\n\t\t(ex as RangeError & { code: string }).code = 'ERR_OUT_OF_RANGE';\n\t\tthrow ex;\n\t}\n\n\tconst child = spawn(command, args, spawnOptions);\n\tif (isWindows) {\n\t\tkillTreeOnKill(child);\n\t}\n\n\tif (timeout != null && timeout > 0) {\n\t\tkillOnTimeout(child, timeout);\n\t}\n\n\treturn child;\n}\n\n/** Node's spawn `timeout`, but also cleared on `'close'`; see {@link spawnProcess} */\nfunction killOnTimeout(child: ChildProcess, timeout: number): void {\n\tlet timeoutId: ReturnType<typeof setTimeout> | undefined = setTimeout(() => {\n\t\tif (timeoutId != null) {\n\t\t\ttry {\n\t\t\t\tchild.kill();\n\t\t\t} catch (ex) {\n\t\t\t\tchild.emit('error', ex);\n\t\t\t}\n\t\t\ttimeoutId = undefined;\n\t\t}\n\t}, timeout);\n\n\tconst clear = () => {\n\t\tif (timeoutId != null) {\n\t\t\tclearTimeout(timeoutId);\n\t\t\ttimeoutId = undefined;\n\t\t}\n\t};\n\t// `'exit'` keeps Node's timing; `'close'` covers a launch that fails and never exits\n\tchild.once('exit', clear);\n\tchild.once('close', clear);\n}\n\nconst taskkillTimeout = 5000;\n\n/**\n * Makes `kill` end the child's whole tree (Windows only). There `kill` terminates just the child, and a launcher such\n * as Git for Windows' `cmd\\git.exe` runs the real git as its own child on the same stdout and stderr, so the pipes\n * stay open and `'close'` never comes. Node's abort and timeout paths call the instance's `kill`, so this covers them.\n */\nfunction killTreeOnKill(child: ChildProcess): void {\n\tconst kill = child.kill.bind(child);\n\tconst mutable = child as { killed: boolean; exitCode: number | null; signalCode: NodeJS.Signals | null };\n\tlet killing = false;\n\n\tchild.kill = (signal?: NodeJS.Signals | number): boolean => {\n\t\tif (child.pid == null || child.exitCode !== null || child.signalCode !== null || typeof signal === 'number') {\n\t\t\treturn kill(signal);\n\t\t}\n\t\tif (killing) return true;\n\n\t\tkilling = true;\n\t\tconst killSignal = signal ?? 'SIGTERM';\n\t\tmutable.killed = true;\n\n\t\t// Killed from outside, the child exits with taskkill's code 1 and no signal; report it as Node's own kill\n\t\t// would, a null code and the signal, which is what every caller keys on\n\t\tlet exitCode: number | null = child.exitCode;\n\t\tObject.defineProperty(child, 'exitCode', {\n\t\t\tconfigurable: true,\n\t\t\tenumerable: true,\n\t\t\tget: () => exitCode,\n\t\t\tset: (value: number | null) => {\n\t\t\t\tif (value === 1) {\n\t\t\t\t\texitCode = null;\n\t\t\t\t\tmutable.signalCode = killSignal;\n\t\t\t\t} else {\n\t\t\t\t\texitCode = value;\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\n\t\t// Once it's killed, a descendant left alive (taskkill failed, or its parent was already gone) can still hold the\n\t\t// pipes; destroying them lets `'close'` come anyway. A child that exited on its own keeps its output\n\t\tchild.once('exit', (_code, exitSignal) => {\n\t\t\tif (exitSignal == null) return;\n\n\t\t\tchild.stdout?.destroy();\n\t\t\tchild.stderr?.destroy();\n\t\t});\n\n\t\t// taskkill failed: fall back to Node's kill, unless the child already exited on its own\n\t\tlet failed = false;\n\t\tconst fail = () => {\n\t\t\tif (failed || child.exitCode !== null || child.signalCode !== null) return;\n\n\t\t\tfailed = true;\n\t\t\ttry {\n\t\t\t\tkill(killSignal);\n\t\t\t} catch {}\n\t\t};\n\n\t\ttry {\n\t\t\t// By absolute path: Windows searches the current directory before PATH for a bare name. Its own time limit\n\t\t\t// keeps a stalled taskkill from leaving the kill, and so the run, hanging\n\t\t\tconst taskkill = spawn(\n\t\t\t\tjoinPaths(process.env.SystemRoot || 'C:\\\\Windows', 'System32', 'taskkill.exe'),\n\t\t\t\t['/T', '/F', '/PID', String(child.pid)],\n\t\t\t\t{ stdio: 'ignore', windowsHide: true },\n\t\t\t);\n\t\t\tkillOnTimeout(taskkill, taskkillTimeout);\n\t\t\ttaskkill.once('error', fail);\n\t\t\ttaskkill.once('exit', code => {\n\t\t\t\tif (code !== 0) {\n\t\t\t\t\tfail();\n\t\t\t\t}\n\t\t\t});\n\t\t} catch {\n\t\t\tfail();\n\t\t}\n\n\t\treturn true;\n\t};\n}\n\nexport interface RunOptions<TEncoding = BufferEncoding | 'buffer'> {\n\tcwd?: string;\n\treadonly env?: Record<string, string | undefined>;\n\treadonly encoding?: TEncoding;\n\t/**\n\t * Decodes non-UTF-8 output. Called when `encoding` is not utf8/binary/buffer.\n\t * Provided by the host via the `GitOptions.decode` option.\n\t * If absent and a non-UTF-8 encoding is requested, throws at runtime.\n\t */\n\treadonly decode?: (data: Uint8Array, options?: { readonly encoding: string }) => string | Promise<string>;\n\t/**\n\t * The most bytes each of stdout and stderr may produce; past it the process is killed and the run rejects\n\t * with a `RunError` whose `code` is `ERR_CHILD_PROCESS_STDIO_MAXBUFFER`.\n\t *\n\t * If not specified, `run` allows 1000MB per stream and `runSpawn` allows unlimited output.\n\t */\n\treadonly maxBuffer?: number;\n\treadonly cancellation?: AbortSignal;\n\t/**\n\t * An optional string or buffer which will be written to\n\t * the child process stdin stream immediately immediately\n\t * after spawning the process.\n\t */\n\treadonly stdin?: string | Buffer;\n\t/**\n\t * The encoding to use when writing to stdin, if the stdin\n\t * parameter is a string.\n\t */\n\treadonly stdinEncoding?: string;\n\treadonly timeout?: number;\n\t/**\n\t * When true, suppresses the `[EXEC]` stderr warning emitted on debug-enabled scopes.\n\t * Use for commands whose failure is expected (e.g. paired with `errors: 'ignore'`).\n\t */\n\treadonly quiet?: boolean;\n\t/** Launches the process; defaults to {@link spawnProcess}. Only used by `runSpawn` */\n\treadonly spawn?: ProcessSpawner;\n}\n\nconst bufferExceededRegex = /stdout maxBuffer( length)? exceeded/;\n\ntype ExitCodeOnlyRunOptions<TEncoding = BufferEncoding | 'buffer'> = RunOptions<TEncoding> & { exitCodeOnly: true };\n\nexport function run(\n\tcommand: string,\n\targs: readonly string[],\n\tencoding: BufferEncoding | string,\n\toptions: ExitCodeOnlyRunOptions<BufferEncoding>,\n): Promise<number>;\nexport function run(\n\tcommand: string,\n\targs: readonly string[],\n\tencoding: BufferEncoding | string,\n\toptions?: RunOptions<BufferEncoding>,\n): Promise<string>;\nexport function run<T extends number | string>(\n\tcommand: string,\n\targs: readonly string[],\n\tencoding: BufferEncoding | string,\n\toptions?: RunOptions<BufferEncoding> & { exitCodeOnly?: boolean },\n): Promise<T> {\n\tconst scope = getScopedLogger() ?? maybeStartScopedLogger('Exec.run');\n\n\tconst { stdin, stdinEncoding, cancellation, decode, ...opts }: RunOptions<BufferEncoding> & ExecFileOptions = {\n\t\tmaxBuffer: 1000 * 1024 * 1024,\n\t\t...options,\n\t};\n\n\tconst promise = new Promise<T>((resolve, reject) => {\n\t\tconst proc = execFile(\n\t\t\tcommand,\n\t\t\targs,\n\t\t\t{ ...opts, signal: cancellation },\n\t\t\tasync (error: ExecFileException | null, stdout, stderr) => {\n\t\t\t\tif (options?.exitCodeOnly) {\n\t\t\t\t\tresolve((error?.code ?? proc.exitCode) as T);\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (error != null) {\n\t\t\t\t\tif (error.signal === 'SIGTERM') {\n\t\t\t\t\t\treject(\n\t\t\t\t\t\t\tnew CancelledRunError(\n\t\t\t\t\t\t\t\t`${command} ${args.join(' ')}`,\n\t\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\t\terror.code ?? undefined,\n\t\t\t\t\t\t\t\terror.signal,\n\t\t\t\t\t\t\t\tcancellation?.aborted ? 'aborted' : error.killed ? 'timeout' : 'unknown',\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (bufferExceededRegex.test(error.message)) {\n\t\t\t\t\t\terror.message = `Command output exceeded the allocated stdout buffer. Set 'options.maxBuffer' to a larger value than ${opts.maxBuffer} bytes`;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet stdoutDecoded: string;\n\t\t\t\t\tlet stderrDecoded: string;\n\t\t\t\t\tif (encoding === 'utf8' || encoding === 'binary' || encoding === 'buffer') {\n\t\t\t\t\t\t// stdout & stderr can be `Buffer` or `string\n\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unnecessary-type-conversion\n\t\t\t\t\t\tstdoutDecoded = stdout.toString();\n\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unnecessary-type-conversion\n\t\t\t\t\t\tstderrDecoded = stderr.toString();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (decode == null) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Non-UTF-8 encoding '${encoding}' requested but no decode function configured`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstdoutDecoded = await decode(\n\t\t\t\t\t\t\tBuffer.from(stdout, 'binary'),\n\t\t\t\t\t\t\tencoding ? { encoding: encoding } : undefined,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tstderrDecoded = await decode(\n\t\t\t\t\t\t\tBuffer.from(stderr, 'binary'),\n\t\t\t\t\t\t\tencoding ? { encoding: encoding } : undefined,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treject(new RunError(error, stdoutDecoded, stderrDecoded));\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (stderr && !options?.quiet && scope?.enabled('debug')) {\n\t\t\t\t\tscope?.warn(`[EXEC] '${command} ${args.join(' ')}' \\u2022 ${stderr}`);\n\t\t\t\t}\n\n\t\t\t\tif (encoding === 'utf8' || encoding === 'binary' || encoding === 'buffer') {\n\t\t\t\t\tresolve(stdout as T);\n\t\t\t\t} else {\n\t\t\t\t\tif (decode == null) {\n\t\t\t\t\t\tthrow new Error(`Non-UTF-8 encoding '${encoding}' requested but no decode function configured`);\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve(\n\t\t\t\t\t\t(await decode(\n\t\t\t\t\t\t\tBuffer.from(stdout, 'binary'),\n\t\t\t\t\t\t\tencoding ? { encoding: encoding } : undefined,\n\t\t\t\t\t\t)) as T,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\t\tif (stdin != null) {\n\t\t\tendStdin(proc.stdin, stdin, stdinEncoding);\n\t\t}\n\t});\n\n\treturn promise.finally(() => scope?.[Symbol.dispose]());\n}\n\n/**\n * Writes a child's whole input and closes it. A child can exit, or be killed on cancellation, before reading all of\n * it, and the pipe then errors (EPIPE, or EOF on Windows). Unlistened, that error is thrown as an uncaught exception\n * and takes down the whole host process, so it is dropped: the child's exit status and stderr already report the\n * failure, and a child that chose to stop reading answered from what it read.\n */\nexport function endStdin(stream: Writable | null, stdin: string | Buffer, stdinEncoding: string | undefined): void {\n\tif (stream == null) return;\n\n\tstream.on('error', () => {});\n\tif (typeof stdin === 'string') {\n\t\tstream.end(stdin, (stdinEncoding ?? 'utf8') as BufferEncoding);\n\t} else {\n\t\tstream.end(stdin);\n\t}\n}\n\nexport interface RunExitResult {\n\t/**\n\t * The process's exit code. ABSENT when the process never exited normally — killed by a signal, in which\n\t * case {@link signal} is set. Deliberately optional rather than defaulted to `0`: a signalled process\n\t * reported as `exitCode: 0` is indistinguishable from a clean success, so callers would read a partial\n\t * or empty stdout as a complete answer.\n\t */\n\treadonly exitCode?: number;\n\t/** Set when the process was terminated by a signal instead of exiting; {@link exitCode} is then absent. */\n\treadonly signal?: NodeJS.Signals;\n\t/** Whether Node itself killed the process (its spawn `timeout`), as opposed to an external signal. */\n\treadonly killed?: boolean;\n}\n\nexport interface RunResult<T extends string | Buffer> extends RunExitResult {\n\tstdout: T;\n\tstderr: T;\n}\n\nexport function runSpawn(\n\tcommand: string,\n\targs: readonly string[],\n\tencoding: BufferEncoding | 'buffer' | string,\n\toptions: ExitCodeOnlyRunOptions,\n): Promise<RunExitResult>;\nexport function runSpawn<T extends string | Buffer>(\n\tcommand: string,\n\targs: readonly string[],\n\tencoding: BufferEncoding | 'buffer' | string,\n\toptions: RunOptions,\n): Promise<RunResult<T>>;\nexport function runSpawn<T extends string | Buffer>(\n\tcommand: string,\n\targs: readonly string[],\n\tencoding: BufferEncoding | 'buffer' | string,\n\toptions: RunOptions & { exitCodeOnly?: boolean },\n): Promise<RunExitResult | RunResult<T>> {\n\tconst scope = getScopedLogger() ?? maybeStartScopedLogger('Exec.runSpawn');\n\n\tconst { stdin, stdinEncoding, cancellation, decode, spawn: spawner, ...opts }: RunOptions = options;\n\n\tconst promise = new Promise<RunExitResult | RunResult<T>>((resolve, reject) => {\n\t\tconst proc = (spawner ?? spawnProcess)(command, args, {\n\t\t\tcwd: opts.cwd,\n\t\t\tenv: opts.env,\n\t\t\t// 0 disables it, which the spawner contract spells as absent\n\t\t\ttimeout: opts.timeout === 0 ? undefined : opts.timeout,\n\t\t\tsignal: cancellation,\n\t\t\tstdio: [stdin != null ? 'pipe' : 'ignore', null, null],\n\t\t});\n\t\tconst errorEncoding = encoding === 'buffer' ? 'utf8' : encoding;\n\n\t\tconst maxBuffer = opts.maxBuffer != null && opts.maxBuffer > 0 ? opts.maxBuffer : undefined;\n\t\tlet limitHit = false;\n\n\t\tfunction collector(buffers: Buffer[], name: 'stdout' | 'stderr'): (data: Buffer) => void {\n\t\t\tlet size = 0;\n\t\t\treturn (data: Buffer) => {\n\t\t\t\tif (limitHit) return;\n\n\t\t\t\tsize += data.length;\n\t\t\t\tif (maxBuffer != null && size > maxBuffer) {\n\t\t\t\t\texceedLimit(name);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tbuffers.push(data);\n\t\t\t};\n\t\t}\n\n\t\tconst stdoutBuffers: Buffer[] = [];\n\t\tconst collectStdout = collector(stdoutBuffers, 'stdout');\n\t\tproc.stdout?.on('data', collectStdout);\n\n\t\tconst stderrBuffers: Buffer[] = [];\n\t\tconst collectStderr = collector(stderrBuffers, 'stderr');\n\t\tproc.stderr?.on('data', collectStderr);\n\n\t\t// Settles the run as soon as a stream passes the limit. Destroying the streams ends a spawner whose process\n\t\t// has no `kill`, and the late `'close'` or `'error'` is ignored through `limitHit`\n\t\tfunction exceedLimit(name: 'stdout' | 'stderr'): void {\n\t\t\tlimitHit = true;\n\t\t\tstdoutBuffers.length = 0;\n\t\t\tstderrBuffers.length = 0;\n\t\t\tproc.stdout?.off('data', collectStdout);\n\t\t\tproc.stderr?.off('data', collectStderr);\n\n\t\t\ttry {\n\t\t\t\tproc.kill?.();\n\t\t\t} catch {}\n\t\t\tproc.stdout?.destroy();\n\t\t\tproc.stderr?.destroy();\n\n\t\t\treject(\n\t\t\t\tnew RunError(\n\t\t\t\t\t{\n\t\t\t\t\t\tmessage: `Command output exceeded the allocated ${name} buffer. Set 'options.maxBuffer' to a larger value than ${maxBuffer} bytes`,\n\t\t\t\t\t\tcmd: `${command} ${args.join(' ')}`,\n\t\t\t\t\t\tkilled: true,\n\t\t\t\t\t\tcode: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER',\n\t\t\t\t\t},\n\t\t\t\t\t'',\n\t\t\t\t\t'',\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\tfunction getStdio<T>(\n\t\t\tencoding: BufferEncoding | 'buffer' | string,\n\t\t): { stdout: T; stderr: T } | Promise<{ stdout: T; stderr: T }> {\n\t\t\tconst stdout = Buffer.concat(stdoutBuffers);\n\t\t\tconst stderr = Buffer.concat(stderrBuffers);\n\t\t\tif (encoding === 'utf8' || encoding === 'binary') {\n\t\t\t\treturn { stdout: stdout.toString(encoding) as T, stderr: stderr.toString(encoding) as T };\n\t\t\t}\n\t\t\tif (encoding === 'buffer') {\n\t\t\t\treturn { stdout: stdout as T, stderr: stderr as T };\n\t\t\t}\n\n\t\t\tif (decode == null) {\n\t\t\t\tthrow new Error(`Non-UTF-8 encoding '${encoding}' requested but no decode function configured`);\n\t\t\t}\n\n\t\t\treturn Promise.all([\n\t\t\t\tdecode(stdout, encoding ? { encoding: encoding } : undefined),\n\t\t\t\tdecode(stderr, encoding ? { encoding: encoding } : undefined),\n\t\t\t]).then(([decodedStdout, decodedStderr]) => ({\n\t\t\t\tstdout: decodedStdout as T,\n\t\t\t\tstderr: decodedStderr as T,\n\t\t\t}));\n\t\t}\n\n\t\t// An async listener's throw would be an unhandled rejection that leaves the promise pending forever, so\n\t\t// anything it throws (an undecodable output, a failing `decode`) rejects the run instead. It rejects as\n\t\t// thrown: wrapped in a `RunError` with the exit code, a clean exit would read as a run with no output\n\t\tconst rejectThrown = (ex: unknown): void => reject(ex instanceof Error ? ex : new Error(String(ex)));\n\t\tproc.once('error', ex => void onError(ex).catch(rejectThrown));\n\t\tproc.once('close', (code, signal) => void onClose(code, signal).catch(rejectThrown));\n\n\t\tasync function onError(ex: Error): Promise<void> {\n\t\t\tif (limitHit) return;\n\n\t\t\tif (ex?.name === 'AbortError') {\n\t\t\t\treject(new CancelledRunError(`${command} ${args.join(' ')}`, true, undefined, undefined, 'aborted'));\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// The launch failure is what the caller acts on, so output that can't be decoded is left out of it\n\t\t\tlet stdout = '';\n\t\t\tlet stderr = '';\n\t\t\ttry {\n\t\t\t\tconst stdio = getStdio<string>(errorEncoding);\n\t\t\t\t({ stdout, stderr } = stdio instanceof Promise ? await stdio : stdio);\n\t\t\t} catch {}\n\n\t\t\treject(new RunError(ex, stdout, stderr));\n\t\t}\n\n\t\tasync function onClose(code: number | null, signal: NodeJS.Signals | null): Promise<void> {\n\t\t\tif (limitHit) return;\n\n\t\t\tif (options?.exitCodeOnly) {\n\t\t\t\t// Resolves unconditionally, so this is the one path that can hand back a signalled run. `code`\n\t\t\t\t// is null exactly when the process was killed — report the signal rather than coercing to `0`,\n\t\t\t\t// which would claim a clean success for a command that never finished. Note this returns BEFORE\n\t\t\t\t// the SIGTERM-to-cancellation diversion below, so callers have to classify that themselves.\n\t\t\t\tresolve({ exitCode: code ?? undefined, signal: signal ?? undefined, killed: proc.killed });\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (code !== 0 || signal) {\n\t\t\t\tconst stdio = getStdio<string>(errorEncoding);\n\t\t\t\tconst { stdout, stderr } = stdio instanceof Promise ? await stdio : stdio;\n\t\t\t\tif (stderr.length && !options?.quiet && scope?.enabled('debug')) {\n\t\t\t\t\tscope?.warn(`[EXEC] '${command} ${args.join(' ')}' \\u2022 ${stderr}`);\n\t\t\t\t}\n\n\t\t\t\tif (signal === 'SIGTERM') {\n\t\t\t\t\t// Only Node's spawn `timeout` kills it (a caller abort rejected above, from `'error'`); an\n\t\t\t\t\t// external SIGTERM leaves `proc.killed` false\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew CancelledRunError(\n\t\t\t\t\t\t\t`${command} ${args.join(' ')}`,\n\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\tcode ?? undefined,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tproc.killed ? 'timeout' : 'unknown',\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\treject(\n\t\t\t\t\tnew RunError(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmessage: `Command failed with exit code ${code}`,\n\t\t\t\t\t\t\tcode: code,\n\t\t\t\t\t\t\tsignal: signal ?? undefined,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstdout,\n\t\t\t\t\t\tstderr,\n\t\t\t\t\t),\n\t\t\t\t);\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst stdio = getStdio<T>(encoding);\n\t\t\tconst { stdout, stderr } = stdio instanceof Promise ? await stdio : stdio;\n\t\t\tif (stderr.length && !options?.quiet && scope?.enabled('debug')) {\n\t\t\t\tscope?.warn(\n\t\t\t\t\t`[EXEC] '${command} ${args.join(' ')}' \\u2022 ${typeof stderr === 'string' ? stderr : stderr.toString()}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// The guard above already rejected every non-zero and every signalled close, so this is a clean\n\t\t\t// zero exit — `code` cannot be null here. (The optional typing exists for the `exitCodeOnly`\n\t\t\t// branch, which is where a codeless result can genuinely surface.)\n\t\t\tresolve({ exitCode: code ?? undefined, signal: signal ?? undefined, stdout: stdout, stderr: stderr });\n\t\t}\n\n\t\t// Only a host spawner can leave these out; reading no output as empty would pass for a clean answer\n\t\tif (proc.stdout == null || proc.stderr == null) {\n\t\t\treject(new Error(`'${command}' was spawned without stdout and stderr pipes`));\n\t\t}\n\n\t\tif (stdin != null) {\n\t\t\tendStdin(proc.stdin, stdin, stdinEncoding);\n\t\t}\n\t});\n\n\treturn promise.finally(() => scope?.[Symbol.dispose]());\n}\n\nexport async function fsExists(path: string): Promise<boolean> {\n\treturn new Promise<boolean>(resolve => access(path, constants.F_OK, err => resolve(err == null)));\n}\n"],"mappings":";;;;;;;;AAsBA,IAAa,WAAb,cAA8B,MAAM;CACnC;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAA0B,QAAgB,QAAgB;EACrE,MAAM,QAAQ,OAAO;EAErB,KAAK,MAAM,QAAQ;EACnB,KAAK,SAAS,QAAQ;EACtB,KAAK,OAAO,QAAQ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