@buildaharness/app-node 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1059 @@
1
+ import { homedir } from "node:os";
2
+ import { join, resolve, relative, sep, isAbsolute, dirname } from "node:path";
3
+ import { createHash, randomBytes } from "node:crypto";
4
+ import { readFile, rename, stat, realpath, readdir, mkdir, unlink, writeFile, chmod } from "node:fs/promises";
5
+ import { mkdirSync, writeFileSync, readFileSync, existsSync, appendFileSync, statSync, rmSync, renameSync, chmodSync, createReadStream, createWriteStream } from "node:fs";
6
+ import { spawn } from "node:child_process";
7
+ import { createServer, connect } from "node:net";
8
+ import { lookup } from "node:dns/promises";
9
+ import { parseArgs } from "node:util";
10
+ import { createInterface } from "node:readline";
11
+ import { progressText, parseUpdateCache, UPDATE_DOWNLOAD_TIMEOUT_MS, assertHttps } from "@buildaharness/runtime";
12
+ import { Readable } from "node:stream";
13
+ import { pipeline } from "node:stream/promises";
14
+ const BUILDAHARNESS_DIR = ".buildaharness";
15
+ function appPaths(identity, home = homedir()) {
16
+ var _a;
17
+ const dataDir = join(home, BUILDAHARNESS_DIR, ((_a = identity.legacy) == null ? void 0 : _a.dataDirName) ?? identity.id);
18
+ return { dataDir, configFile: join(dataDir, "config.json") };
19
+ }
20
+ function isEnoent$1(err) {
21
+ return (err == null ? void 0 : err.code) === "ENOENT";
22
+ }
23
+ function nodeFsBackend(options = {}) {
24
+ const roots = (options.privateRoots ?? [join(homedir(), BUILDAHARNESS_DIR)]).map((root) => resolve(root));
25
+ const isPrivate = (path) => roots.some((root) => {
26
+ const rel = relative(root, resolve(path));
27
+ return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
28
+ });
29
+ const restrict = (path, mode) => chmod(path, mode).catch(() => {
30
+ });
31
+ return {
32
+ async readTextFile(path) {
33
+ try {
34
+ return await readFile(path, "utf-8");
35
+ } catch (err) {
36
+ if (isEnoent$1(err)) return void 0;
37
+ throw err;
38
+ }
39
+ },
40
+ async writeTextFile(path, contents) {
41
+ if (!isPrivate(path)) return writeFile(path, contents, "utf-8");
42
+ await writeFile(path, contents, { encoding: "utf-8", mode: 384 });
43
+ await restrict(path, 384);
44
+ },
45
+ async removeFile(path) {
46
+ try {
47
+ await unlink(path);
48
+ } catch (err) {
49
+ if (!isEnoent$1(err)) throw err;
50
+ }
51
+ },
52
+ async mkdir(path) {
53
+ if (!isPrivate(path)) {
54
+ await mkdir(path, { recursive: true });
55
+ return;
56
+ }
57
+ await mkdir(path, { recursive: true, mode: 448 });
58
+ await restrict(path, 448);
59
+ },
60
+ async readDir(path) {
61
+ try {
62
+ return await readdir(path);
63
+ } catch (err) {
64
+ if (isEnoent$1(err)) return [];
65
+ throw err;
66
+ }
67
+ },
68
+ async realpath(path) {
69
+ return realpath(path);
70
+ },
71
+ async stat(path) {
72
+ try {
73
+ const info = await stat(path);
74
+ return { isDirectory: info.isDirectory(), size: info.size };
75
+ } catch (err) {
76
+ if (isEnoent$1(err)) return void 0;
77
+ throw err;
78
+ }
79
+ },
80
+ async rename(from, to) {
81
+ await rename(from, to);
82
+ }
83
+ };
84
+ }
85
+ async function nodeFileFingerprint(path) {
86
+ try {
87
+ const bytes = await readFile(path);
88
+ return `${bytes.length}:${createHash("sha256").update(bytes).digest("hex")}`;
89
+ } catch (err) {
90
+ if (isEnoent$1(err)) return void 0;
91
+ throw err;
92
+ }
93
+ }
94
+ async function writeFileAtomic(path, text) {
95
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
96
+ const tempPath = `${path}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`;
97
+ await writeFile(tempPath, text, { encoding: "utf-8", mode: 384 });
98
+ await rename(tempPath, path);
99
+ }
100
+ function isEnoent(err) {
101
+ return (err == null ? void 0 : err.code) === "ENOENT";
102
+ }
103
+ function jsonConfigStore(path, opts = {}) {
104
+ const warn = opts.warn ?? ((message) => console.error(message));
105
+ let queue = Promise.resolve();
106
+ const load = async () => {
107
+ let raw;
108
+ try {
109
+ raw = await readFile(path, "utf-8");
110
+ } catch (err) {
111
+ if (isEnoent(err)) return {};
112
+ throw err;
113
+ }
114
+ try {
115
+ const parsed = JSON.parse(raw);
116
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("not an object");
117
+ return parsed;
118
+ } catch {
119
+ warn(`Warning: ${path} is not valid JSON — ignoring it and falling back to defaults.`);
120
+ return {};
121
+ }
122
+ };
123
+ const writePatch = async (patch) => {
124
+ const existing = await load();
125
+ const merged = { ...existing, ...patch };
126
+ await writeFileAtomic(path, JSON.stringify(merged, null, 2));
127
+ };
128
+ return {
129
+ load,
130
+ save(patch) {
131
+ const task = queue.then(() => writePatch(patch));
132
+ queue = task.catch(() => {
133
+ });
134
+ return task;
135
+ }
136
+ };
137
+ }
138
+ function fileSettingsStore(path, opts = {}) {
139
+ const warn = opts.warn ?? ((message) => console.error(message));
140
+ let queue = Promise.resolve();
141
+ async function load() {
142
+ let raw;
143
+ try {
144
+ raw = await readFile(path, "utf-8");
145
+ } catch (error) {
146
+ if ((error == null ? void 0 : error.code) === "ENOENT") return {};
147
+ throw error;
148
+ }
149
+ try {
150
+ const parsed = JSON.parse(raw);
151
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("not an object");
152
+ return parsed;
153
+ } catch {
154
+ warn(`Warning: ${path} is not valid JSON, so its saved values are ignored.`);
155
+ return {};
156
+ }
157
+ }
158
+ return {
159
+ async getSetting(key) {
160
+ await queue.catch(() => {
161
+ });
162
+ const values = await load();
163
+ return Object.hasOwn(values, key) ? values[key] : void 0;
164
+ },
165
+ setSetting(key, value) {
166
+ const task = queue.then(async () => {
167
+ const values = await load();
168
+ if (value === void 0) delete values[key];
169
+ else values[key] = value;
170
+ await writeFileAtomic(path, JSON.stringify(values, null, 2));
171
+ });
172
+ queue = task.catch(() => {
173
+ });
174
+ return task;
175
+ }
176
+ };
177
+ }
178
+ function fileConsentStore(path) {
179
+ return {
180
+ read: () => {
181
+ try {
182
+ const version = JSON.parse(readFileSync(path, "utf8")).version;
183
+ return typeof version === "string" ? version : void 0;
184
+ } catch {
185
+ return void 0;
186
+ }
187
+ },
188
+ write: (version, acceptedAt) => {
189
+ mkdirSync(dirname(path), { recursive: true });
190
+ writeFileSync(path, JSON.stringify({ version, acceptedAt }));
191
+ }
192
+ };
193
+ }
194
+ const MAX_HEADER_BYTES = 16384;
195
+ function hostAllowed(host, allowlist) {
196
+ const normalized = host.toLowerCase();
197
+ return allowlist.some((entry) => {
198
+ const allowed = entry.toLowerCase();
199
+ return normalized === allowed || normalized.endsWith(`.${allowed}`);
200
+ });
201
+ }
202
+ function parseConnectTarget(requestLine) {
203
+ const match = /^CONNECT\s+([^:\s]+):(\d+)\s+HTTP/i.exec(requestLine);
204
+ return match ? { host: match[1], port: Number(match[2]) } : null;
205
+ }
206
+ function parsePlainHttpTarget(requestLine, headerText) {
207
+ const absoluteUri = /^[A-Z]+\s+https?:\/\/([^/:\s]+)(?::(\d+))?/i.exec(requestLine);
208
+ if (absoluteUri) return { host: absoluteUri[1], port: Number(absoluteUri[2] ?? 80) };
209
+ const hostHeader = /^host:\s*([^\s:]+)(?::(\d+))?/im.exec(headerText);
210
+ return hostHeader ? { host: hostHeader[1], port: Number(hostHeader[2] ?? 80) } : null;
211
+ }
212
+ function handleConnection(clientSocket, allowlist) {
213
+ let buffered = Buffer.alloc(0);
214
+ const onData = (chunk) => {
215
+ buffered = Buffer.concat([buffered, chunk]);
216
+ const headerEnd = buffered.indexOf("\r\n\r\n");
217
+ if (headerEnd === -1) {
218
+ if (buffered.length > MAX_HEADER_BYTES) clientSocket.destroy();
219
+ return;
220
+ }
221
+ clientSocket.removeListener("data", onData);
222
+ clientSocket.pause();
223
+ const headerText = buffered.slice(0, headerEnd).toString("utf-8");
224
+ const requestLine = headerText.split("\r\n")[0] ?? "";
225
+ const isConnect = /^CONNECT\s/i.test(requestLine);
226
+ const target = isConnect ? parseConnectTarget(requestLine) : parsePlainHttpTarget(requestLine, headerText);
227
+ if (!target || !hostAllowed(target.host, allowlist)) {
228
+ clientSocket.end("HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n");
229
+ return;
230
+ }
231
+ const upstream = connect(target.port, target.host, () => {
232
+ if (isConnect) {
233
+ clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
234
+ const tunnelBytes = buffered.slice(headerEnd + 4);
235
+ if (tunnelBytes.length > 0) upstream.write(tunnelBytes);
236
+ } else {
237
+ upstream.write(buffered);
238
+ }
239
+ clientSocket.pipe(upstream);
240
+ upstream.pipe(clientSocket);
241
+ });
242
+ upstream.on("error", () => clientSocket.destroy());
243
+ clientSocket.on("close", () => upstream.destroy());
244
+ };
245
+ clientSocket.on("data", onData);
246
+ clientSocket.on("error", () => clientSocket.destroy());
247
+ }
248
+ function startProxyServer(allowlist) {
249
+ return new Promise((resolveStart, rejectStart) => {
250
+ const server = createServer((socket) => handleConnection(socket, allowlist));
251
+ server.on("error", rejectStart);
252
+ server.listen(0, "127.0.0.1", () => {
253
+ const address = server.address();
254
+ if (address === null || typeof address === "string") {
255
+ rejectStart(new Error("Failed to bind network containment proxy to a loopback port"));
256
+ return;
257
+ }
258
+ resolveStart({
259
+ port: address.port,
260
+ close: () => new Promise((resolveClose) => server.close(() => resolveClose()))
261
+ });
262
+ });
263
+ });
264
+ }
265
+ function startNetworkContainment(allowlist) {
266
+ return startProxyServer([...allowlist]);
267
+ }
268
+ const proxyCache = /* @__PURE__ */ new Map();
269
+ function getNetworkContainmentProxy(allowlist) {
270
+ const key = JSON.stringify([...allowlist].map((host) => host.toLowerCase()).sort());
271
+ let proxy = proxyCache.get(key);
272
+ if (!proxy) {
273
+ proxy = startProxyServer(allowlist);
274
+ proxyCache.set(key, proxy);
275
+ }
276
+ return proxy;
277
+ }
278
+ async function resetNetworkContainmentProxiesForTests() {
279
+ const proxies = [...proxyCache.values()];
280
+ proxyCache.clear();
281
+ for (const proxyPromise of proxies) {
282
+ const proxy = await proxyPromise;
283
+ await proxy.close();
284
+ }
285
+ }
286
+ const DEFAULT_TIMEOUT_MS = 3e4;
287
+ const DEFAULT_MAX_OUTPUT_BYTES = 2e4;
288
+ const ALLOWED_ENV_VARS = ["PATH", "HOME", "LANG"];
289
+ function allowlistedEnv(names) {
290
+ const env = {};
291
+ for (const key of names) {
292
+ const value = process.env[key];
293
+ if (value !== void 0) env[key] = value;
294
+ }
295
+ return env;
296
+ }
297
+ async function networkContainmentEnv(networkAllowlist) {
298
+ const proxy = await getNetworkContainmentProxy(networkAllowlist);
299
+ const proxyUrl = `http://127.0.0.1:${proxy.port}`;
300
+ return {
301
+ HTTP_PROXY: proxyUrl,
302
+ http_proxy: proxyUrl,
303
+ HTTPS_PROXY: proxyUrl,
304
+ https_proxy: proxyUrl
305
+ };
306
+ }
307
+ function truncateOutput(text, maxBytes) {
308
+ const encoded = new TextEncoder().encode(text);
309
+ if (encoded.length <= maxBytes) return text;
310
+ const truncated = new TextDecoder("utf-8", { fatal: false }).decode(encoded.slice(0, maxBytes));
311
+ return `${truncated}
312
+ … (truncated)`;
313
+ }
314
+ async function runShellCommand(command, cwd, options = {}) {
315
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
316
+ const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
317
+ const containmentEnv = await networkContainmentEnv(options.networkAllowlist ?? []);
318
+ return new Promise((resolvePromise, reject) => {
319
+ var _a, _b;
320
+ const proc = spawn(command, {
321
+ shell: true,
322
+ cwd,
323
+ env: { ...allowlistedEnv(options.env ?? ALLOWED_ENV_VARS), ...containmentEnv },
324
+ detached: true,
325
+ stdio: ["ignore", "pipe", "pipe"]
326
+ });
327
+ let output = "";
328
+ let timedOut = false;
329
+ let settled = false;
330
+ const finish = (exitCode) => {
331
+ if (settled) return;
332
+ settled = true;
333
+ clearTimeout(timer);
334
+ resolvePromise({
335
+ output: truncateOutput(output, maxOutputBytes),
336
+ exitCode: timedOut ? null : exitCode,
337
+ timedOut
338
+ });
339
+ };
340
+ const timer = setTimeout(() => {
341
+ var _a2, _b2;
342
+ timedOut = true;
343
+ try {
344
+ if (proc.pid) process.kill(-proc.pid, "SIGKILL");
345
+ else proc.kill("SIGKILL");
346
+ } catch {
347
+ proc.kill("SIGKILL");
348
+ }
349
+ (_b2 = (_a2 = setTimeout(() => {
350
+ var _a3, _b3;
351
+ (_a3 = proc.stdout) == null ? void 0 : _a3.destroy();
352
+ (_b3 = proc.stderr) == null ? void 0 : _b3.destroy();
353
+ finish(null);
354
+ }, 2e3)).unref) == null ? void 0 : _b2.call(_a2);
355
+ }, timeoutMs);
356
+ const append = (chunk) => {
357
+ if (output.length <= maxOutputBytes * 2) output += chunk.toString("utf-8");
358
+ };
359
+ (_a = proc.stdout) == null ? void 0 : _a.on("data", append);
360
+ (_b = proc.stderr) == null ? void 0 : _b.on("data", append);
361
+ proc.on("error", (err) => {
362
+ if (settled) return;
363
+ settled = true;
364
+ clearTimeout(timer);
365
+ reject(err);
366
+ });
367
+ proc.on("close", (exitCode) => finish(exitCode));
368
+ });
369
+ }
370
+ function findGitDir(start) {
371
+ let dir = resolve(start);
372
+ for (; ; ) {
373
+ const dotGit = join(dir, ".git");
374
+ if (existsSync(dotGit)) {
375
+ const stat2 = statSync(dotGit);
376
+ if (stat2.isDirectory()) return dotGit;
377
+ const line = readFileSync(dotGit, "utf8").split("\n").find((l) => l.startsWith("gitdir:"));
378
+ if (!line) return void 0;
379
+ const target = line.slice("gitdir:".length).trim();
380
+ const gitDir = isAbsolute(target) ? target : resolve(dir, target);
381
+ const commonFile = join(gitDir, "commondir");
382
+ if (existsSync(commonFile)) return resolve(gitDir, readFileSync(commonFile, "utf8").trim());
383
+ return gitDir;
384
+ }
385
+ const parent = dirname(dir);
386
+ if (parent === dir) return void 0;
387
+ dir = parent;
388
+ }
389
+ }
390
+ async function excludeFromGit(workspaceRoot, dirs, options = {}) {
391
+ try {
392
+ const gitDir = findGitDir(workspaceRoot);
393
+ if (!gitDir) return [];
394
+ const excludeFile = join(gitDir, "info", "exclude");
395
+ const existing = existsSync(excludeFile) ? readFileSync(excludeFile, "utf8") : "";
396
+ const present = new Set(existing.split("\n").map((l) => l.trim()));
397
+ const missing = dirs.map((d) => `${d}/`).filter((entry) => !present.has(entry) && !present.has(entry.slice(0, -1)));
398
+ if (missing.length === 0) return [];
399
+ mkdirSync(dirname(excludeFile), { recursive: true });
400
+ const prefix = existing === "" || existing.endsWith("\n") ? "" : "\n";
401
+ appendFileSync(excludeFile, `${prefix}# ${options.appName ?? "App"} state (added automatically)
402
+ ${missing.join("\n")}
403
+ `);
404
+ return missing;
405
+ } catch {
406
+ return [];
407
+ }
408
+ }
409
+ function nodeResolver() {
410
+ return async (hostname) => (await lookup(hostname, { all: true })).map((record) => record.address);
411
+ }
412
+ const ESCAPE_SEQUENCE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\u001b\[[0-?]*[ -/]*[@-~]|\u001b[@-Z\\-_]|\u001b/g;
413
+ const UNSAFE_CHARS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g;
414
+ function stripTerminalControls(text) {
415
+ return text.replace(ESCAPE_SEQUENCE, "").replace(UNSAFE_CHARS, "");
416
+ }
417
+ function oneLine(text) {
418
+ return stripTerminalControls(text).replace(/[\n\t\u2028\u2029]+/g, " ");
419
+ }
420
+ function indentBlock(text, prefix = " | ") {
421
+ return stripTerminalControls(text).split(/\n|\u2028|\u2029/).map((line) => `${prefix}${line}`).join("\n");
422
+ }
423
+ function createLineQueue(handle, onError) {
424
+ let tail = Promise.resolve();
425
+ return {
426
+ /** Resolves when this line has been handled. Never rejects: a throw goes to `onError` and later lines still run. */
427
+ enqueue(line) {
428
+ tail = tail.then(() => handle(line)).catch(onError);
429
+ return tail;
430
+ },
431
+ /** Resolves when nothing is queued, including lines queued while waiting. */
432
+ async idle() {
433
+ let seen;
434
+ while (seen !== tail) {
435
+ seen = tail;
436
+ await seen;
437
+ }
438
+ }
439
+ };
440
+ }
441
+ const DEFAULT_DECLINE_NOTICE = "[non-interactive mode: auto-declining]";
442
+ const defaultIsYes = (answer) => ["y", "yes"].includes(answer.trim().toLowerCase());
443
+ function createPrompter(o) {
444
+ const isYes = o.isYes ?? defaultIsYes;
445
+ let closed = false;
446
+ let waiting;
447
+ o.source.on("close", () => {
448
+ closed = true;
449
+ if ((o.pendingAtClose ?? "decline") === "decline") waiting == null ? void 0 : waiting();
450
+ });
451
+ function read(query, failureNotice) {
452
+ return new Promise((resolve2) => {
453
+ const fail = () => {
454
+ waiting = void 0;
455
+ o.say(`
456
+ [could not read a response — ${failureNotice}]`);
457
+ resolve2(void 0);
458
+ };
459
+ if (closed || waiting) {
460
+ o.say(`
461
+ [could not read a response — ${failureNotice}]`);
462
+ return resolve2(void 0);
463
+ }
464
+ waiting = fail;
465
+ try {
466
+ o.source.question(stripTerminalControls(query), (answer) => {
467
+ waiting = void 0;
468
+ resolve2(answer.trim());
469
+ });
470
+ } catch {
471
+ fail();
472
+ }
473
+ });
474
+ }
475
+ const declined = () => {
476
+ if (!o.decline) return false;
477
+ o.say(`
478
+ ${o.declineNotice ?? DEFAULT_DECLINE_NOTICE}`);
479
+ return true;
480
+ };
481
+ function yesNo(question) {
482
+ if (declined()) return Promise.resolve("no");
483
+ return read(question, "treating as declined").then((answer) => answer === void 0 ? "none" : isYes(answer) ? "yes" : "no");
484
+ }
485
+ return {
486
+ yesNo,
487
+ confirm: (question) => yesNo(question).then((answer) => answer === "yes"),
488
+ ask: (question) => read(question, "treating as blank"),
489
+ select(question, options) {
490
+ const last = options[options.length - 1];
491
+ if (!last) throw new Error("select() needs at least one option");
492
+ if (declined()) return Promise.resolve(last.key);
493
+ const lines = options.map((option, i) => ` ${i + 1}) [${option.key}] ${option.label.replace(/\n/g, " ")}`).join("\n");
494
+ return read(`${question}
495
+ ${lines}
496
+ > `, "treating as declined").then((answer) => {
497
+ var _a;
498
+ if (answer === void 0) return last.key;
499
+ const typed = answer.toLowerCase();
500
+ const byKey = options.find((option) => option.key.toLowerCase() === typed);
501
+ const byIndex = /^\d+$/.test(typed) ? options[Number(typed) - 1] : void 0;
502
+ return ((_a = byKey ?? byIndex) == null ? void 0 : _a.key) ?? last.key;
503
+ });
504
+ }
505
+ };
506
+ }
507
+ function resolveNonInteractiveMode(env, variable, warn = (message) => console.error(message)) {
508
+ const raw = env[variable];
509
+ if (raw === void 0) return void 0;
510
+ if (raw === "decline" || raw === "require-tty") return raw;
511
+ warn(`[warning] ${variable}="${raw}" is not "decline" or "require-tty" — ignoring.`);
512
+ return void 0;
513
+ }
514
+ function commandKey(name) {
515
+ return name.split(" ")[0];
516
+ }
517
+ function formatCommandHelp(commands) {
518
+ const width = Math.max(0, ...commands.map((c) => c.usage.length));
519
+ return commands.map((c) => ` ${c.usage.padEnd(width + 2)} ${oneLine(c.description)}`).join("\n");
520
+ }
521
+ const QUIT_WORDS = /* @__PURE__ */ new Set(["exit", "quit", "/exit", "/quit"]);
522
+ function isQuitCommand(message) {
523
+ return QUIT_WORDS.has(message.trim().toLowerCase());
524
+ }
525
+ function parseCommandLine(argv, spec) {
526
+ const commands = spec.commands ?? {};
527
+ const first = argv[0];
528
+ const command = first !== void 0 && Object.hasOwn(commands, first) ? first : void 0;
529
+ const declared = { ...spec.options, ...command ? commands[command].options : {} };
530
+ const options = {
531
+ help: { type: "boolean", short: "h" },
532
+ version: { type: "boolean", short: "v" }
533
+ };
534
+ for (const [name, o] of Object.entries(declared)) options[name] = { type: o.type, ...o.short ? { short: o.short } : {} };
535
+ try {
536
+ const { values, positionals } = parseArgs({ args: argv.slice(command ? 1 : 0), options, allowPositionals: true, strict: true });
537
+ if (values.help) return { kind: "help" };
538
+ if (values.version) return { kind: "version" };
539
+ return { kind: "run", ...command ? { command } : {}, options: { ...values }, words: positionals };
540
+ } catch (e) {
541
+ return { kind: "error", message: e instanceof Error ? e.message : String(e) };
542
+ }
543
+ }
544
+ function commandLineHelp(spec) {
545
+ const rows = (entries) => {
546
+ const width = Math.max(0, ...entries.map(([left]) => left.length));
547
+ return entries.map(([left, help]) => ` ${left.padEnd(width + 2)} ${help}`);
548
+ };
549
+ const optionRows = (options, indent = "") => Object.entries(options).map(([name, o]) => [`${indent}${o.short ? `-${o.short}, ` : ""}--${name}${o.type === "string" ? " <value>" : ""}`, o.help]);
550
+ const commands = Object.entries(spec.commands ?? {}).flatMap(([name, c]) => [[name, c.help], ...optionRows(c.options ?? {}, " ")]);
551
+ return [
552
+ `${spec.name} ${spec.version}${spec.summary ? ` — ${spec.summary}` : ""}`,
553
+ "",
554
+ `Usage: ${spec.name}${commands.length ? " [command]" : ""} [options]`,
555
+ ...commands.length ? ["", "Commands:", ...rows(commands)] : [],
556
+ "",
557
+ "Options:",
558
+ ...rows([...optionRows(spec.options ?? {}), ["-h, --help", "show this help"], ["-v, --version", "print the version"]])
559
+ ].join("\n");
560
+ }
561
+ class StartupError extends Error {
562
+ }
563
+ function createCliHost(o) {
564
+ const input = o.input ?? process.stdin;
565
+ const output = o.output ?? process.stdout;
566
+ const isTty = input.isTTY === true;
567
+ const write = (text) => void output.write(stripTerminalControls(text));
568
+ const print = (text) => write(`${text}
569
+ `);
570
+ const variable = `${o.identity.envPrefix}_NON_INTERACTIVE_APPROVAL`;
571
+ const mode = o.nonInteractive ?? resolveNonInteractiveMode(o.env ?? process.env, variable, print);
572
+ if (mode === "require-tty" && !isTty) {
573
+ throw new StartupError(`${o.identity.name} is set to require a terminal (require-tty), but input is not one. Run it in a terminal, or use ${variable}=decline to refuse every approval.`);
574
+ }
575
+ const own = o.commands ?? [];
576
+ const builtIn = [
577
+ { name: "/help", usage: "/help", description: "Show this list", run: () => print(help()) },
578
+ { name: "/exit", usage: "/exit (/quit, exit, quit)", description: "End the session" }
579
+ ];
580
+ const commands = [...builtIn.filter((b) => !own.some((c) => c.name === b.name)), ...own];
581
+ const help = () => formatCommandHelp(commands);
582
+ const table = /* @__PURE__ */ new Map();
583
+ for (const command of commands) {
584
+ if (!command.run) continue;
585
+ for (const key of [commandKey(command.name), ...command.aliases ?? []]) {
586
+ if (table.has(key)) throw new Error(`Two commands handle "${key}"`);
587
+ table.set(key, command.run);
588
+ }
589
+ }
590
+ let rl;
591
+ let prompter;
592
+ let closed = false;
593
+ let onLine;
594
+ let onClose;
595
+ const backlog = [];
596
+ const interrupts = [];
597
+ function open() {
598
+ if (prompter) return prompter;
599
+ const ended = closed || input.readableEnded === true;
600
+ rl = createInterface({ input, output, prompt: o.prompt ?? "> " });
601
+ rl.on("line", (line) => onLine ? onLine(line) : void backlog.push(line));
602
+ rl.on("close", () => {
603
+ closed = true;
604
+ onClose == null ? void 0 : onClose();
605
+ });
606
+ rl.on("SIGINT", () => {
607
+ const listener = interrupts[interrupts.length - 1];
608
+ if (listener) listener();
609
+ else rl == null ? void 0 : rl.close();
610
+ });
611
+ prompter = createPrompter({
612
+ source: rl,
613
+ say: print,
614
+ decline: mode === "decline",
615
+ declineNotice: `[non-interactive mode: auto-declining — ${variable}=decline]`
616
+ });
617
+ if (ended) rl.close();
618
+ return prompter;
619
+ }
620
+ function close() {
621
+ closed = true;
622
+ rl == null ? void 0 : rl.close();
623
+ }
624
+ async function dispatch(line, handle) {
625
+ const [token = "", ...args] = line.split(/\s+/);
626
+ const run = table.get(token);
627
+ if (run) await run(args);
628
+ else if (handle) await handle(line);
629
+ else print(`Unknown command "${oneLine(token)}". /help lists the commands.`);
630
+ }
631
+ return {
632
+ print,
633
+ write,
634
+ help,
635
+ nonInteractive: mode,
636
+ close,
637
+ yesNo: (question) => open().yesNo(question),
638
+ confirm: (question) => open().confirm(question),
639
+ ask: (question) => mode === "decline" ? Promise.resolve(void 0) : open().ask(question),
640
+ select: (question, options) => open().select(question, options),
641
+ onInterrupt(listener) {
642
+ interrupts.push(listener);
643
+ return () => {
644
+ const at = interrupts.lastIndexOf(listener);
645
+ if (at >= 0) interrupts.splice(at, 1);
646
+ };
647
+ },
648
+ serve(handle) {
649
+ if (onLine) throw new Error("serve() is already running");
650
+ return new Promise((resolve2) => {
651
+ let quitting = false;
652
+ const showPrompt = () => {
653
+ if (isTty && !closed) rl == null ? void 0 : rl.prompt();
654
+ };
655
+ const queue = createLineQueue(
656
+ async (line) => {
657
+ if (quitting) return;
658
+ if (isQuitCommand(line)) {
659
+ quitting = true;
660
+ close();
661
+ return;
662
+ }
663
+ await dispatch(line, handle);
664
+ },
665
+ (error) => print(`[error] ${error instanceof Error ? error.message : String(error)}`)
666
+ );
667
+ const take = (raw) => {
668
+ const line = raw.trim();
669
+ if (!line) return showPrompt();
670
+ void queue.enqueue(line).then(showPrompt);
671
+ };
672
+ let finishing = false;
673
+ const finish = () => {
674
+ if (finishing) return;
675
+ finishing = true;
676
+ void queue.idle().then(() => {
677
+ onLine = onClose = void 0;
678
+ resolve2();
679
+ });
680
+ };
681
+ const alreadyClosed = closed;
682
+ onClose = finish;
683
+ onLine = take;
684
+ open();
685
+ for (const line of backlog.splice(0)) take(line);
686
+ if (alreadyClosed || closed) finish();
687
+ else showPrompt();
688
+ });
689
+ }
690
+ };
691
+ }
692
+ const TONES = { good: "ok", warn: "warning", bad: "failed" };
693
+ const ENDS = { done: "Done.", stopped: "Stopped.", failed: "Failed." };
694
+ function formatJobEvent(event) {
695
+ switch (event.kind) {
696
+ case "count":
697
+ case "stage":
698
+ return ` ${oneLine(progressText(event))}`;
699
+ case "text":
700
+ return stripTerminalControls(event.chunk);
701
+ case "note":
702
+ return ` ${event.tone ? `${TONES[event.tone]}: ` : ""}${oneLine(event.text)}`;
703
+ case "stop":
704
+ return event.how === "soft" ? "Stopping after the current step. Press Ctrl+C again to stop now." : "Stopping now.";
705
+ case "end":
706
+ return ENDS[event.outcome];
707
+ }
708
+ }
709
+ async function runJob(host, job) {
710
+ let midLine = false;
711
+ let asked = false;
712
+ let last = "";
713
+ const unsubscribe = job.subscribe((event) => {
714
+ const text = formatJobEvent(event);
715
+ if (event.kind === "text") {
716
+ host.write(text);
717
+ if (text) midLine = !text.endsWith("\n");
718
+ return;
719
+ }
720
+ if (midLine) host.write("\n");
721
+ midLine = false;
722
+ if (text !== last) host.print(text);
723
+ last = text;
724
+ });
725
+ const release = host.onInterrupt(() => {
726
+ job.stop(asked ? "hard" : "soft");
727
+ asked = true;
728
+ });
729
+ try {
730
+ const outcome = await job.done;
731
+ if (outcome.status === "failed") host.print(indentBlock(outcome.error instanceof Error ? outcome.error.message : String(outcome.error)));
732
+ return outcome;
733
+ } finally {
734
+ release();
735
+ unsubscribe();
736
+ }
737
+ }
738
+ function formatPending(pending) {
739
+ const { shown } = pending;
740
+ return [
741
+ `Needs approval: ${oneLine(shown.summary)}`,
742
+ ...shown.details ? [indentBlock(shown.details)] : [],
743
+ ...(shown.items ?? []).map((item, i) => ` ${i + 1}) ${oneLine(item.label)}`),
744
+ ...(shown.warnings ?? []).map((warning) => ` Warning: ${oneLine(warning)}`),
745
+ ...shown.reversible ? [] : [" This cannot be undone."]
746
+ ].join("\n");
747
+ }
748
+ function formatApproveResult(result) {
749
+ switch (result.status) {
750
+ case "applied":
751
+ return "Done.";
752
+ case "not_applied":
753
+ return `Not done: ${oneLine(result.error)} It is still waiting for approval.`;
754
+ case "outcome_unknown":
755
+ return `This may or may not have been done: ${oneLine(result.error)} Check before trying again.`;
756
+ case "refused": {
757
+ const why = { unknown: "there is no such action", in_progress: "it is already being handled", changed: "it changed since it was shown", invalid: "it cannot be checked" }[result.reason];
758
+ return `Not done: ${why}.${result.error ? ` ${oneLine(result.error)}` : ""}`;
759
+ }
760
+ }
761
+ }
762
+ const MAX_ASKS$1 = 3;
763
+ async function reviewApproval(host, approvals, id) {
764
+ let pending = await approvals.get(id);
765
+ for (let attempt = 1; ; attempt++) {
766
+ const reason = !pending ? "unknown" : pending.claimed ? "claimed" : pending.fingerprint === "" ? "cannot_be_checked" : void 0;
767
+ if (pending) host.print(formatPending(pending));
768
+ if (reason || !pending) {
769
+ host.print({ unknown: "There is no such action.", claimed: "This is being applied, or an earlier attempt did not finish. It is not run again.", cannot_be_checked: "This cannot be checked, so it cannot be approved." }[reason ?? "unknown"]);
770
+ return { decision: "not_asked", reason: reason ?? "unknown" };
771
+ }
772
+ let items;
773
+ const shownItems = pending.shown.items;
774
+ if (shownItems && shownItems.length > 1 && !host.nonInteractive) {
775
+ const typed = await host.ask("Numbers to leave out (comma-separated, Enter for none): ");
776
+ if (typed === void 0) return { decision: "unanswered" };
777
+ const numbers = typed.split(/[\s,]+/).filter(Boolean).map(Number);
778
+ if (numbers.some((n) => !Number.isInteger(n) || n < 1 || n > shownItems.length)) {
779
+ host.print("Not one of the numbers shown; nothing was done.");
780
+ return { decision: "unanswered" };
781
+ }
782
+ items = shownItems.filter((_, i) => !numbers.includes(i + 1)).map((item) => item.id);
783
+ if (items.length === 0) {
784
+ await approvals.reject(id);
785
+ host.print("Everything was left out; nothing was done.");
786
+ return { decision: "declined" };
787
+ }
788
+ }
789
+ const answer = await host.yesNo("Approve? (y/N) ");
790
+ if (answer === "none") return { decision: "unanswered" };
791
+ if (answer === "no") {
792
+ await approvals.reject(id);
793
+ host.print("Declined; nothing was done.");
794
+ return { decision: "declined" };
795
+ }
796
+ const result = await approvals.approve(id, pending.fingerprint, items ? { items } : {});
797
+ host.print(formatApproveResult(result));
798
+ if (result.status === "refused" && result.reason === "changed" && result.current && attempt < MAX_ASKS$1) {
799
+ pending = result.current;
800
+ continue;
801
+ }
802
+ return { decision: "approved", result };
803
+ }
804
+ }
805
+ function formatAppEvent(event) {
806
+ return event.kind === "count" || event.kind === "stage" || event.kind === "note" ? formatJobEvent(event) : void 0;
807
+ }
808
+ function formatDecision(decision) {
809
+ const d = decision;
810
+ return [
811
+ `Needs approval: ${oneLine(d.summary)}`,
812
+ ...d.details ? [indentBlock(d.details)] : [],
813
+ ...(d.items ?? []).map((item, i) => ` ${i + 1}) ${oneLine(item.label)}`),
814
+ ...(d.warnings ?? []).map((w) => ` Warning: ${oneLine(w)}`),
815
+ ...d.reversible ? [] : [" This cannot be undone."]
816
+ ].join("\n");
817
+ }
818
+ async function runAppJob(host, job) {
819
+ const decisions = [];
820
+ let last = "";
821
+ let asked = false;
822
+ const unsubscribe = job.subscribe((event) => {
823
+ if (event.kind === "decision") return void decisions.push(event.request);
824
+ const line = formatAppEvent(event);
825
+ if (line !== void 0 && line !== last) host.print(line);
826
+ last = line ?? last;
827
+ });
828
+ const release = host.onInterrupt(() => {
829
+ job.stop(asked ? "hard" : "soft");
830
+ asked = true;
831
+ });
832
+ try {
833
+ const outcome = await job.done;
834
+ if (outcome.status === "stopped") host.print("Stopped.");
835
+ else if (outcome.status === "failed") host.print(`Failed: ${oneLine(outcome.message)}`);
836
+ return { outcome, decisions };
837
+ } finally {
838
+ release();
839
+ unsubscribe();
840
+ }
841
+ }
842
+ function formatDecisionResult(result, o = {}) {
843
+ const r = result ?? {};
844
+ const files = (n) => `${n} file${n === 1 ? "" : "s"}`;
845
+ if (r.declined) return ["Declined; nothing was done."];
846
+ if (Array.isArray(r.moved)) {
847
+ return [`Moved ${files(r.moved.length)}.${o.undoHint ? ` ${o.undoHint}` : ""}`, ...(r.failed ?? []).map((f) => ` not moved: ${oneLine(f.id)}: ${oneLine(f.reason)}`)];
848
+ }
849
+ if (Array.isArray(r.restored)) {
850
+ return [`Moved back ${files(r.restored.length)}.`, ...(r.conflicts ?? []).map((c) => ` left alone: ${oneLine(c.id)}: ${oneLine(c.reason.replace("_", " "))}`), ...r.refused ? [`Not undone: ${oneLine(r.refused)}`] : []];
851
+ }
852
+ return ["Done."];
853
+ }
854
+ const MAX_ASKS = 3;
855
+ async function reviewDecision(host, session, decision, o = {}) {
856
+ let outcome = { status: "failed", message: "Not answered.", retryable: false, partial: false, unread: [] };
857
+ for (let attempt = 1; attempt <= MAX_ASKS; attempt++) {
858
+ host.print(formatDecision(decision));
859
+ let items;
860
+ let approve = false;
861
+ const shown = decision.items ?? [];
862
+ if (shown.length > 1 && !host.nonInteractive) {
863
+ const typed = await host.ask("Numbers to leave out (comma-separated, Enter for none): ");
864
+ const numbers = (typed ?? "").split(/[\s,]+/).filter(Boolean).map(Number);
865
+ if (typed === void 0 || numbers.some((n) => !Number.isInteger(n) || n < 1 || n > shown.length)) {
866
+ host.print("Nothing was approved.");
867
+ } else {
868
+ items = shown.filter((_, i) => !numbers.includes(i + 1)).map((item) => item.id);
869
+ approve = items.length > 0;
870
+ }
871
+ } else {
872
+ approve = await host.yesNo("Approve? (y/N) ") === "yes";
873
+ }
874
+ let next;
875
+ const answer = session.resolve(decision.id, { choice: approve ? "approve" : "decline", fingerprint: decision.fingerprint, ...items ? { items } : {} });
876
+ answer.subscribe((e) => {
877
+ if (e.kind === "decision") next = e.request;
878
+ });
879
+ outcome = await answer.done;
880
+ if (outcome.status === "done") {
881
+ for (const line of formatDecisionResult(outcome.result, o)) host.print(line);
882
+ return outcome;
883
+ }
884
+ host.print(outcome.status === "failed" ? `Not done: ${oneLine(outcome.message)}` : "Stopped.");
885
+ if (!next) return outcome;
886
+ decision = next;
887
+ }
888
+ return outcome;
889
+ }
890
+ const createNodeProcessRunner = () => ({
891
+ spawn(command, args, options, events) {
892
+ const proc = spawn(command, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] });
893
+ proc.stdout.on("data", (chunk) => events.onStdout(typeof chunk === "string" ? chunk : chunk.toString("utf-8")));
894
+ proc.stderr.on("data", (chunk) => events.onStderr(typeof chunk === "string" ? chunk : chunk.toString("utf-8")));
895
+ proc.on("error", events.onError);
896
+ proc.on("close", events.onClose);
897
+ return { kill: () => {
898
+ proc.kill();
899
+ } };
900
+ }
901
+ });
902
+ const createNodeToolGateHost = () => ({
903
+ listen(handle) {
904
+ return new Promise((resolvePromise, reject) => {
905
+ const server = createServer((socket) => {
906
+ socket.on("error", () => {
907
+ });
908
+ let buffer = "";
909
+ socket.on("data", (chunk) => {
910
+ buffer += chunk.toString("utf-8");
911
+ let newlineIndex;
912
+ while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
913
+ const line = buffer.slice(0, newlineIndex);
914
+ buffer = buffer.slice(newlineIndex + 1);
915
+ if (!line.trim()) continue;
916
+ void handle(line).then((reply) => {
917
+ socket.write(`${reply}
918
+ `);
919
+ });
920
+ }
921
+ });
922
+ });
923
+ server.on("error", reject);
924
+ server.listen(0, "127.0.0.1", () => {
925
+ const address = server.address();
926
+ if (address === null || typeof address === "string") {
927
+ reject(new Error("tool gate server failed to bind to a loopback TCP port"));
928
+ return;
929
+ }
930
+ resolvePromise({ port: address.port, close: () => {
931
+ server.close();
932
+ } });
933
+ });
934
+ });
935
+ }
936
+ });
937
+ function replaceBinary(execPath, newFile, platform = process.platform) {
938
+ if (platform === "win32") {
939
+ const aside = `${execPath}.old`;
940
+ rmSync(aside, { force: true });
941
+ renameSync(execPath, aside);
942
+ try {
943
+ renameSync(newFile, execPath);
944
+ } catch (err) {
945
+ renameSync(aside, execPath);
946
+ throw err;
947
+ }
948
+ return;
949
+ }
950
+ chmodSync(newFile, 493);
951
+ renameSync(newFile, execPath);
952
+ }
953
+ function cleanupStaleUpdateFiles(execPath = process.execPath) {
954
+ for (const stale of [`${execPath}.old`, `${execPath}.update.tmp`]) {
955
+ try {
956
+ if (existsSync(stale)) rmSync(stale, { force: true });
957
+ } catch {
958
+ }
959
+ }
960
+ }
961
+ async function downloadTo(fetchFn, url, dest, allowInsecureHttp = false) {
962
+ const res = await fetchFn(url, { signal: AbortSignal.timeout(UPDATE_DOWNLOAD_TIMEOUT_MS), redirect: "follow" });
963
+ if (!res.ok || !res.body) throw new Error(`Download failed: HTTP ${res.status} for ${url}`);
964
+ if (res.url) assertHttps(res.url, allowInsecureHttp);
965
+ const hash = createHash("sha256");
966
+ rmSync(dest, { force: true });
967
+ await pipeline(
968
+ Readable.fromWeb(res.body),
969
+ async function* (source) {
970
+ for await (const chunk of source) {
971
+ hash.update(chunk);
972
+ yield chunk;
973
+ }
974
+ },
975
+ createWriteStream(dest, { flags: "wx" })
976
+ );
977
+ return hash.digest("hex");
978
+ }
979
+ async function sha256OfFile(path) {
980
+ const hash = createHash("sha256");
981
+ for await (const chunk of createReadStream(path)) hash.update(chunk);
982
+ return hash.digest("hex");
983
+ }
984
+ function createNodeUpdateFiles() {
985
+ return {
986
+ download: downloadTo,
987
+ sha256OfFile,
988
+ remove: (path) => rmSync(path, { force: true }),
989
+ makeDir: (dir) => {
990
+ mkdirSync(dir, { recursive: true });
991
+ },
992
+ replace: replaceBinary,
993
+ dirname
994
+ };
995
+ }
996
+ function createFileUpdateCache(dataDir, fileName = "update-check.json") {
997
+ const path = join(dataDir, fileName);
998
+ return {
999
+ read: () => {
1000
+ try {
1001
+ return parseUpdateCache(readFileSync(path, "utf8"));
1002
+ } catch {
1003
+ return null;
1004
+ }
1005
+ },
1006
+ write: (cache) => {
1007
+ try {
1008
+ mkdirSync(dataDir, { recursive: true });
1009
+ writeFileSync(path, JSON.stringify(cache));
1010
+ } catch {
1011
+ }
1012
+ }
1013
+ };
1014
+ }
1015
+ export {
1016
+ BUILDAHARNESS_DIR,
1017
+ StartupError,
1018
+ appPaths,
1019
+ cleanupStaleUpdateFiles,
1020
+ commandKey,
1021
+ commandLineHelp,
1022
+ createCliHost,
1023
+ createFileUpdateCache,
1024
+ createLineQueue,
1025
+ createNodeProcessRunner,
1026
+ createNodeToolGateHost,
1027
+ createNodeUpdateFiles,
1028
+ createPrompter,
1029
+ excludeFromGit,
1030
+ fileConsentStore,
1031
+ fileSettingsStore,
1032
+ formatAppEvent,
1033
+ formatApproveResult,
1034
+ formatCommandHelp,
1035
+ formatDecision,
1036
+ formatDecisionResult,
1037
+ formatJobEvent,
1038
+ formatPending,
1039
+ getNetworkContainmentProxy,
1040
+ indentBlock,
1041
+ isQuitCommand,
1042
+ jsonConfigStore,
1043
+ nodeFileFingerprint,
1044
+ nodeFsBackend,
1045
+ nodeResolver,
1046
+ oneLine,
1047
+ parseCommandLine,
1048
+ replaceBinary,
1049
+ resetNetworkContainmentProxiesForTests,
1050
+ resolveNonInteractiveMode,
1051
+ reviewApproval,
1052
+ reviewDecision,
1053
+ runAppJob,
1054
+ runJob,
1055
+ runShellCommand,
1056
+ startNetworkContainment,
1057
+ stripTerminalControls
1058
+ };
1059
+ //# sourceMappingURL=index.js.map