sandcovery 0.4.0 → 0.5.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.
@@ -1,1691 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { $ as isString, H as isSuccess, K as getOrUndefined, M as optional, S as fromJsonString, U as try_, V as isFailure, Z as hasProperty, g as Struct, h as String$1, m as Record, n as Boolean, s as Json, x as decodeUnknownSync, y as decodeUnknownOption } from "../Schema-CFI3ZMu8.mjs";
3
- import { n as SANDCOVERY_ORIGIN } from "../origin-BTx2gX8x.mjs";
4
- import { A as isUpper, C as escapeUnprintable, D as consistsOf, E as remoteText, F as usageFailure, I as Canceled, M as CliFailure, N as exitCodeOf, O as isDigit, P as statusOf$1, S as theme, T as remoteLine, _ as clearLine, a as configDirectory, b as plainPrefix, c as flagOf, d as lastValue, f as parseFailure, h as rerunArgv, i as version, j as isWordCharacter, l as isOptionToken, m as readOptionToken, o as writePrivateFile, p as parseLeaf, r as CLI, s as closest, t as BIN, u as isOptionValue, v as ellipsis, w as remoteCell, x as spinnerFrame, y as glyph } from "../spec-B4c-Ug3B.mjs";
5
- import { n as sendTelemetry$1, t as loopbackOrigin } from "../telemetry-BYnuVdoZ.mjs";
6
- import "../posthog-project-CdWw_ofg.mjs";
7
- import http from "node:http";
8
- import fs from "node:fs";
9
- import path from "node:path";
10
- import { buffer } from "node:stream/consumers";
11
- import readline from "node:readline";
12
- // ../cli-core/src/layout.ts
13
- const combining = /\p{M}/u;
14
- const pictographic = /\p{Extended_Pictographic}/u;
15
- const WIDE_RANGES = [
16
- [4352, 4447],
17
- [11904, 12350],
18
- [12353, 13311],
19
- [13312, 19903],
20
- [19968, 40959],
21
- [40960, 42191],
22
- [44032, 55203],
23
- [63744, 64255],
24
- [65072, 65103],
25
- [65280, 65376],
26
- [65504, 65510]
27
- ];
28
- const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
29
- const graphemeWidth = (grapheme) => {
30
- const point = grapheme.codePointAt(0) ?? 0;
31
- const first = String.fromCodePoint(point);
32
- if (grapheme === "" || combining.test(first)) return 0;
33
- return WIDE_RANGES.some(([low, high]) => point >= low && point <= high) || pictographic.test(first) ? 2 : 1;
34
- };
35
- const displayWidth = (text) => {
36
- let total = 0;
37
- for (const { segment } of segmenter.segment(text)) total += graphemeWidth(segment);
38
- return total;
39
- };
40
- const padEnd = (text, width) => `${text}${" ".repeat(Math.max(0, width - displayWidth(text)))}`;
41
- const truncate = ({ ellipsis, text, width }) => {
42
- if (displayWidth(text) <= width) return text;
43
- const room = Math.max(0, width - displayWidth(ellipsis));
44
- let kept = "";
45
- for (const { segment } of segmenter.segment(text)) {
46
- if (displayWidth(`${kept}${segment}`) > room) break;
47
- kept += segment;
48
- }
49
- return `${kept}${ellipsis}`;
50
- };
51
- const wrap = ({ text, width }) => {
52
- const lines = [];
53
- for (const paragraph of text.split("\n")) {
54
- let line = "";
55
- for (const word of paragraph.split(" ")) if (line === "") line = word;
56
- else if (displayWidth(`${line} ${word}`) <= width) line = `${line} ${word}`;
57
- else {
58
- lines.push(line);
59
- line = word;
60
- }
61
- lines.push(line);
62
- }
63
- return lines;
64
- };
65
- const indent = (lines, spaces) => lines.map((line) => line === "" ? "" : `${" ".repeat(spaces)}${line}`);
66
- const twoColumn = ({ decorate = (text) => text, entries, indentBy, width }) => {
67
- const column = indentBy + Math.max(0, ...entries.map((entry) => displayWidth(entry.syntax))) + 2;
68
- const descriptionWidth = width - column;
69
- const sideBySide = descriptionWidth >= 24;
70
- return entries.flatMap(({ description, syntax }) => {
71
- const lead = `${" ".repeat(indentBy)}${decorate(syntax)}`;
72
- if (description === "") return [lead];
73
- if (!sideBySide) return [lead, ...indent(wrap({
74
- text: description,
75
- width: Math.max(20, width - indentBy - 4)
76
- }), indentBy + 4)];
77
- const [first = "", ...rest] = wrap({
78
- text: description,
79
- width: descriptionWidth
80
- });
81
- return [`${lead}${" ".repeat(column - indentBy - displayWidth(syntax))}${first}`, ...indent(rest, column)];
82
- });
83
- };
84
- // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/function/noop.mjs
85
- /**
86
- * A no-operation function that does nothing.
87
- * This can be used as a placeholder or default function.
88
- *
89
- * @example
90
- * noop(); // Does nothing
91
- *
92
- * @returns This function does not return anything.
93
- */
94
- function noop() {}
95
- // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/math/sum.mjs
96
- /**
97
- * Calculates the sum of an array of numbers.
98
- *
99
- * This function takes an array of numbers and returns the sum of all the elements in the array.
100
- *
101
- * @param nums - An array of numbers to be summed.
102
- * @returns The sum of all the numbers in the array.
103
- *
104
- * @example
105
- * const numbers = [1, 2, 3, 4, 5];
106
- * const result = sum(numbers);
107
- * // result will be 15
108
- */
109
- function sum(nums) {
110
- let result = 0;
111
- for (let i = 0; i < nums.length; i++) result += nums[i];
112
- return result;
113
- }
114
- // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/object/omitBy.mjs
115
- /**
116
- * Creates a new object composed of the properties that do not satisfy the predicate function.
117
- *
118
- * This function takes an object and a predicate function, and returns a new object that
119
- * includes only the properties for which the predicate function returns false.
120
- *
121
- * @template T - The type of object.
122
- * @param obj - The object to omit properties from.
123
- * @param shouldOmit - A predicate function that determines
124
- * whether a property should be omitted. It takes the property's key and value as arguments and returns `true`
125
- * if the property should be omitted, and `false` otherwise. Numeric keys are passed as strings.
126
- * @returns A new object with the properties that do not satisfy the predicate function.
127
- *
128
- * @example
129
- * const obj = { a: 1, b: 'omit', c: 3 };
130
- * const shouldOmit = (value) => typeof value === 'string';
131
- * const result = omitBy(obj, shouldOmit);
132
- * // result will be { a: 1, c: 3 }
133
- */
134
- function omitBy(obj, shouldOmit) {
135
- const result = {};
136
- const keys = Object.keys(obj);
137
- for (let i = 0; i < keys.length; i++) {
138
- const key = keys[i];
139
- const objectKey = key;
140
- const value = obj[objectKey];
141
- if (!shouldOmit(value, key)) result[objectKey] = value;
142
- }
143
- return result;
144
- }
145
- // ../cli-core/src/output.ts
146
- const decodeJsonRecord = decodeUnknownSync(fromJsonString(Record(String$1, Json)));
147
- const jsonRecord = ({ value }) => decodeJsonRecord(JSON.stringify(value));
148
- const SHELL_SAFE_PUNCTUATION = /* @__PURE__ */ new Set([
149
- "%",
150
- "+",
151
- ",",
152
- "-",
153
- ".",
154
- "/",
155
- ":",
156
- "=",
157
- "@"
158
- ]);
159
- const DOUBLE_QUOTE_SPECIALS = [
160
- "!",
161
- "\"",
162
- "$",
163
- "\\",
164
- "`"
165
- ];
166
- const isShellSafe = (word) => consistsOf(word, (character) => isWordCharacter(character) || SHELL_SAFE_PUNCTUATION.has(character));
167
- const isPlaceholder = (word) => {
168
- const bare = word.endsWith("...") ? word.slice(0, -3) : word;
169
- const name = bare.slice(1, -1);
170
- return bare.startsWith("<") && bare.endsWith(">") && isUpper(name.charAt(0)) && consistsOf(name, (character) => isUpper(character) || isDigit(character) || character === "_");
171
- };
172
- const shellWord = (word) => {
173
- if (isShellSafe(word) || isPlaceholder(word)) return word;
174
- if (DOUBLE_QUOTE_SPECIALS.some((special) => word.includes(special))) return `'${word.replaceAll("'", () => `'"'"'`)}'`;
175
- return `"${word}"`;
176
- };
177
- const shellCommand = (argv) => argv.map(shellWord).join(" ");
178
- const definedOnly = (value) => omitBy(value, (field) => field === void 0);
179
- const nextEntry = ({ bin, next: { argv, when } }) => {
180
- const entry = {
181
- argv: [bin, ...argv],
182
- command: shellCommand([bin, ...argv])
183
- };
184
- if (when !== void 0) entry.when = when;
185
- return entry;
186
- };
187
- const nextEntries = ({ bin, steps }) => {
188
- const entries = steps.flatMap((step) => "argv" in step ? [nextEntry({
189
- bin,
190
- next: step
191
- })] : []);
192
- return entries.length === 0 ? void 0 : entries;
193
- };
194
- const hasPlaceholder = (argv) => argv.some((word) => word.includes("<"));
195
- const cellText = (cell) => isString(cell) ? cell : cell.text;
196
- const cellPlain = (cell) => isString(cell) ? cell : cell.plain;
197
- const COLUMN_GAP = 3;
198
- const TABLE_INDENT = 2;
199
- const MIN_OPTIONAL_WIDTH = 8;
200
- const LIST_LIMIT = 5;
201
- const MIN_WRAP$1 = 20;
202
- const styledCommand = ({ argv, style }) => hasPlaceholder(argv) ? shellCommand(argv) : theme.command(style, shellCommand(argv));
203
- const rowLines = (rows, style) => rows.flatMap(({ label, prose, value }) => {
204
- const text = prose === true ? remoteText(value).replaceAll("\r", "") : remoteLine(value);
205
- const lead = ` ${padEnd(label, 16)}`;
206
- const room = style.width - 18;
207
- if (prose === true && room >= MIN_WRAP$1) {
208
- const [first = "", ...rest] = wrap({
209
- text,
210
- width: room
211
- });
212
- return [`${lead}${first}`, ...indent(rest, 18)];
213
- }
214
- if (displayWidth(label) >= 16 || displayWidth(text) > room) return [` ${label}`, ` ${text}`];
215
- return [`${lead}${text}`];
216
- });
217
- const plainRowLines = (rows) => rows.map(({ label, value }) => `${label}\t${remoteCell({
218
- separated: true,
219
- text: value
220
- })}`);
221
- const listLines = (items) => {
222
- const shown = items.slice(0, LIST_LIMIT).map((item) => ` ${remoteLine(item)}`);
223
- const rest = items.length - LIST_LIMIT;
224
- return rest <= 0 ? shown : [...shown, ` and ${String(rest)} more`];
225
- };
226
- const tableWidth = (widths) => TABLE_INDENT + sum(widths) + COLUMN_GAP * (widths.length - 1);
227
- const fittedWidths = ({ natural, table, width }) => {
228
- const fixed = sum(table.columns.map((column, index) => column.optional === true ? 0 : natural[index] ?? 0));
229
- const optional = table.columns.filter((column) => column.optional === true).length;
230
- const room = width - TABLE_INDENT - fixed - COLUMN_GAP * (table.columns.length - 1);
231
- const share = optional === 0 ? 0 : Math.floor(room / optional);
232
- return table.columns.map((column, index) => column.optional === true ? Math.min(natural[index] ?? 0, Math.max(share, MIN_OPTIONAL_WIDTH, displayWidth(column.header))) : natural[index] ?? 0);
233
- };
234
- const recoveryLines = ({ bin, recovery, style }) => recovery.flatMap(({ instruction, next, url }, index) => {
235
- const lowered = `${instruction.charAt(0).toLowerCase()}${instruction.slice(1)}`;
236
- const label = index === 0 ? instruction : `Or ${lowered}`;
237
- if (next !== void 0) return [` ${label}:`, ` ${styledCommand({
238
- argv: [bin, ...next.argv],
239
- style
240
- })}`];
241
- if (url !== void 0) return [` ${label}:`, ` ${url}`];
242
- return [` ${label}`];
243
- });
244
- const headlineLines = ({ lead, style, text }) => {
245
- const [first = "", ...rest] = wrap({
246
- text: remoteLine(text),
247
- width: Math.max(MIN_WRAP$1, style.width - 2)
248
- });
249
- return [`${lead} ${first}`, ...indent(rest, 2)];
250
- };
251
- const stepLines = ({ bin, steps, style }) => steps.flatMap((step) => [` ${step.benefit}:`, ` ${"argv" in step ? styledCommand({
252
- argv: [bin, ...step.argv],
253
- style
254
- }) : step.url}`]);
255
- const errorDocument = ({ bin, failure, warnings }) => {
256
- const next = (failure.recovery ?? []).flatMap((recovery) => recovery.next === void 0 ? [] : [nextEntry({
257
- bin,
258
- next: recovery.next
259
- })]);
260
- const issues = failure.issues ?? [];
261
- const data = definedOnly({
262
- ...failure.data,
263
- issues: issues.length === 0 ? void 0 : issues.map(({ field, message }) => ({
264
- field,
265
- message,
266
- reason: failure.reason
267
- })),
268
- remoteMessage: failure.remoteMessage === void 0 ? void 0 : remoteText(failure.remoteMessage)
269
- });
270
- const document = {
271
- message: failure.message,
272
- reason: failure.reason,
273
- status: statusOf$1(failure)
274
- };
275
- if (Object.keys(data).length > 0) document.data = data;
276
- if (next.length > 0) document.next = next;
277
- if (failure.requestId !== void 0) document.requestId = failure.requestId;
278
- if (failure.retryAfter !== void 0) document.retryAfter = failure.retryAfter;
279
- if (failure.retryable !== void 0) document.retryable = failure.retryable;
280
- if (failure.userActionRequired === true) document.userActionRequired = true;
281
- if (warnings.length > 0) document.warnings = warnings;
282
- return document;
283
- };
284
- var Output = class {
285
- warnings = [];
286
- bin;
287
- err;
288
- guidance;
289
- mode;
290
- out;
291
- spinner = null;
292
- stderrUsed = false;
293
- constructor({ bin, err, guidance, mode, out }) {
294
- this.bin = bin;
295
- this.err = err;
296
- this.guidance = guidance;
297
- this.mode = mode;
298
- this.out = out;
299
- }
300
- get human() {
301
- return this.mode.format === "human";
302
- }
303
- get errStyle() {
304
- return this.mode.stderr;
305
- }
306
- get stdoutTerminal() {
307
- return this.mode.stdout.tty;
308
- }
309
- writeErr(lines) {
310
- this.stopSpinner();
311
- for (const line of lines) this.err.write(`${line}\n`);
312
- this.stderrUsed = true;
313
- }
314
- writeOut(lines) {
315
- this.stopSpinner();
316
- for (const line of lines) this.out.write(`${line}\n`);
317
- }
318
- block(lines) {
319
- if (!this.human || lines.length === 0) return;
320
- this.writeErr(this.stderrUsed ? ["", ...lines] : lines);
321
- }
322
- context(rows) {
323
- this.block(rowLines(rows, this.errStyle));
324
- }
325
- note(lines) {
326
- const width = Math.max(MIN_WRAP$1, this.errStyle.width - 2);
327
- this.block(lines.flatMap((line) => indent(wrap({
328
- text: remoteLine(line),
329
- width
330
- }), 2)));
331
- }
332
- receipt({ outcome, rows = [], target }) {
333
- const style = this.errStyle;
334
- const shown = remoteLine(target);
335
- const label = theme.outcome(style, padEnd(outcome, 16));
336
- const headline = style.rich ? `${glyph(style, "success")} ${label}${shown}` : `${outcome} ${shown}`;
337
- this.block([headline, ...rowLines(rows, style)]);
338
- }
339
- warn(reason, message) {
340
- if (this.warnings.some((warning) => warning.message === message)) return;
341
- this.warnings.push({
342
- message,
343
- reason
344
- });
345
- if (!this.human) return;
346
- const style = this.errStyle;
347
- const lead = style.rich ? glyph(style, "warning") : plainPrefix(style, "warning");
348
- this.writeErr(headlineLines({
349
- lead,
350
- style,
351
- text: message
352
- }));
353
- }
354
- next(steps) {
355
- const style = this.errStyle;
356
- const shown = steps.filter((step) => step.optional !== true || this.guidance);
357
- const lines = stepLines({
358
- bin: this.bin,
359
- steps: shown,
360
- style
361
- });
362
- this.block(shown.length > 1 ? [" Next steps:", ...lines] : lines);
363
- }
364
- progress(phase) {
365
- if (!this.human) return { done: noop };
366
- if (!this.errStyle.rich || !this.mode.interactive) {
367
- this.writeErr([` ${phase}`]);
368
- return { done: noop };
369
- }
370
- this.stopSpinner();
371
- const spinner = {
372
- phase,
373
- tick: 0,
374
- timer: setInterval(() => {
375
- this.renderSpinner(spinner);
376
- }, 80)
377
- };
378
- this.spinner = spinner;
379
- this.renderSpinner(spinner);
380
- this.stderrUsed = true;
381
- return { done: () => {
382
- if (this.spinner === spinner) this.stopSpinner();
383
- } };
384
- }
385
- renderSpinner(spinner) {
386
- this.err.write(`${clearLine}${spinnerFrame(spinner.tick)} ${spinner.phase}`);
387
- spinner.tick += 1;
388
- }
389
- stopSpinner() {
390
- if (this.spinner === null) return;
391
- clearInterval(this.spinner.timer);
392
- this.spinner = null;
393
- this.err.write(clearLine);
394
- }
395
- details(rows) {
396
- if (this.human) this.writeOut(this.stdoutTerminal ? rowLines(rows, this.mode.stdout) : plainRowLines(rows));
397
- }
398
- table({ empty, table }) {
399
- if (!this.human) return;
400
- const header = table.columns.map((column) => column.header);
401
- if (table.rows.length === 0) {
402
- if (!this.stdoutTerminal) this.writeOut([header.join(" ")]);
403
- this.block([` ${empty}`]);
404
- return;
405
- }
406
- if (!this.stdoutTerminal) {
407
- this.writeOut([header.join(" "), ...table.rows.map((row) => row.map((cell) => remoteCell({
408
- separated: true,
409
- text: cellPlain(cell)
410
- })).join(" "))]);
411
- return;
412
- }
413
- this.writeOut(this.alignedTable(table));
414
- }
415
- alignedTable(table) {
416
- const style = this.mode.stdout;
417
- const cells = table.rows.map((row) => row.map((cell) => remoteCell({
418
- separated: false,
419
- text: cellText(cell)
420
- })));
421
- const natural = table.columns.map((column, index) => Math.max(displayWidth(column.header), ...cells.map((row) => displayWidth(row[index] ?? ""))));
422
- const widths = tableWidth(natural) > style.width ? fittedWidths({
423
- natural,
424
- table,
425
- width: style.width
426
- }) : natural;
427
- if (tableWidth(widths) > style.width) return cells.flatMap((row, index) => [...index === 0 ? [] : [""], ...rowLines(table.columns.map((column, position) => ({
428
- label: column.header,
429
- value: row[position] ?? ""
430
- })), style)]);
431
- const line = (row) => {
432
- const shown = row.map((cell, index) => {
433
- const width = widths[index] ?? 0;
434
- const cut = truncate({
435
- ellipsis: ellipsis(style),
436
- text: cell,
437
- width
438
- });
439
- return index === row.length - 1 ? cut : padEnd(cut, width);
440
- });
441
- return `${" ".repeat(TABLE_INDENT)}${shown.join(" ".repeat(COLUMN_GAP))}`.trimEnd();
442
- };
443
- return [line(table.columns.map((column) => column.header)), ...cells.map(line)];
444
- }
445
- identifier(id) {
446
- if (this.human && !(this.mode.interactive && this.stdoutTerminal)) this.writeOut([id]);
447
- }
448
- mask(secret) {
449
- if (this.mode.githubActions) {
450
- this.stopSpinner();
451
- this.err.write(`::add-mask::${secret}\n`);
452
- }
453
- }
454
- secret(secret) {
455
- if (this.human) this.writeOut([secret]);
456
- }
457
- bytes(text) {
458
- if (this.human) {
459
- this.stopSpinner();
460
- this.out.write(this.stdoutTerminal ? escapeUnprintable(text) : text);
461
- }
462
- }
463
- values(lines) {
464
- if (this.human) this.writeOut(lines.map((line) => remoteLine(line)));
465
- }
466
- document(document) {
467
- this.stopSpinner();
468
- const full = this.warnings.length === 0 ? document : {
469
- ...document,
470
- warnings: this.warnings
471
- };
472
- const text = this.stdoutTerminal ? JSON.stringify(full, null, 2) : JSON.stringify(full);
473
- this.out.write(`${text}\n`);
474
- }
475
- failure(failure) {
476
- this.stopSpinner();
477
- if (!this.human) {
478
- this.err.write(`${JSON.stringify(errorDocument({
479
- bin: this.bin,
480
- failure,
481
- warnings: this.warnings
482
- }))}\n`);
483
- return;
484
- }
485
- const style = this.errStyle;
486
- const lead = style.rich ? glyph(style, "error") : plainPrefix(style, "error");
487
- const issues = failure.issues ?? [];
488
- const width = Math.max(MIN_WRAP$1, style.width - 2);
489
- const recovery = recoveryLines({
490
- bin: this.bin,
491
- recovery: failure.recovery ?? [],
492
- style
493
- });
494
- this.block([
495
- ...headlineLines({
496
- lead,
497
- style,
498
- text: failure.message
499
- }),
500
- ...(failure.notes ?? []).flatMap((note) => indent(wrap({
501
- text: remoteLine(note),
502
- width
503
- }), 2)),
504
- ...issues.length > 1 ? listLines(issues.map(({ message }) => message)) : [],
505
- ...rowLines(failure.detail ?? [], style),
506
- ...rowLines(failure.context ?? [], style),
507
- ...rowLines(failure.ids ?? [], style),
508
- ...recovery.length === 0 ? [] : ["", ...recovery]
509
- ]);
510
- }
511
- canceled({ lines, next = [], remote }) {
512
- this.stopSpinner();
513
- if (this.human) {
514
- this.block(lines);
515
- this.next(next);
516
- return;
517
- }
518
- const document = {
519
- data: { remote },
520
- message: lines[0] ?? "Canceled.",
521
- reason: "canceled",
522
- status: "error"
523
- };
524
- document.next = nextEntries({
525
- bin: this.bin,
526
- steps: next
527
- });
528
- if (this.warnings.length > 0) document.warnings = this.warnings;
529
- this.err.write(`${JSON.stringify(document)}\n`);
530
- }
531
- };
532
- // ../cli-core/src/route.ts
533
- const HELP = "help";
534
- const WORDS = "words";
535
- const optionsFor = (options, surface) => options.filter((option) => option.surfaces === void 0 || option.surfaces.includes(surface));
536
- const childrenOf = (node, surface) => node.children.filter((child) => child.surfaces === void 0 || child.surfaces.includes(surface));
537
- const matches = (node, token) => node.name === token || (node.shortcuts ?? []).includes(token);
538
- const subtreeOptions = (node) => node.kind === "leaf" ? node.options : [...node.options ?? [], ...node.children.flatMap(subtreeOptions)];
539
- const knownOptions = ({ cli, node, surface }) => [...optionsFor(cli.globals, surface), ...subtreeOptions(node)];
540
- const isHelpCommand = (path) => path.length === 1 && path[0] === HELP;
541
- const takeOption = (walk, argv, token) => {
542
- const read = readOptionToken({
543
- options: knownOptions(walk),
544
- token
545
- });
546
- walk.tokens.push(token);
547
- walk.index += 1;
548
- if (read.option === void 0) {
549
- walk.unknownOption ??= token;
550
- return;
551
- }
552
- const next = argv[walk.index];
553
- if (read.option.kind === "value" && read.explicit === null && next !== void 0 && isOptionValue(next)) {
554
- walk.tokens.push(next);
555
- walk.index += 1;
556
- }
557
- };
558
- const takeWord = (walk, token) => {
559
- const { node } = walk;
560
- walk.index += 1;
561
- if (node.kind === "leaf" || walk.words) {
562
- walk.tokens.push(token);
563
- return;
564
- }
565
- const children = childrenOf(node, walk.surface);
566
- const child = children.find((candidate) => matches(candidate, token));
567
- if (child !== void 0) {
568
- walk.node = child;
569
- walk.path = [...walk.path, child.name];
570
- return;
571
- }
572
- if (isHelpCommand(walk.path)) {
573
- walk.words = true;
574
- walk.tokens.push(token);
575
- return;
576
- }
577
- walk.unknownCommand ??= {
578
- kind: "command",
579
- path: walk.path,
580
- segment: token,
581
- suggestion: closest({
582
- candidates: children.map((candidate) => candidate.name),
583
- token
584
- })
585
- };
586
- };
587
- const optionFailure = (walk) => {
588
- if (walk.unknownOption === null) return null;
589
- const read = readOptionToken({
590
- options: knownOptions(walk),
591
- token: walk.unknownOption
592
- });
593
- return {
594
- kind: "option",
595
- path: walk.path,
596
- segment: read.spelled,
597
- suggestion: read.suggestion
598
- };
599
- };
600
- const route = ({ argv, cli, surface }) => {
601
- const walk = {
602
- cli,
603
- index: 0,
604
- node: cli.root,
605
- path: [],
606
- surface,
607
- tokens: [],
608
- unknownCommand: null,
609
- unknownOption: null,
610
- words: false
611
- };
612
- while (walk.index < argv.length) {
613
- const token = argv[walk.index] ?? "";
614
- const passthrough = walk.node.kind === "leaf" && walk.node.passthrough === true;
615
- if (passthrough || token === "--") {
616
- walk.tokens.push(...passthrough ? ["--"] : [], ...argv.slice(walk.index));
617
- break;
618
- }
619
- if (isOptionToken(token)) takeOption(walk, argv, token);
620
- else takeWord(walk, token);
621
- }
622
- return {
623
- node: walk.node,
624
- path: walk.path,
625
- tokens: walk.tokens,
626
- unknownCommand: walk.unknownCommand,
627
- unknownOption: optionFailure(walk)
628
- };
629
- };
630
- const routeFailure = ({ bin, failure }) => {
631
- const suggestion = failure.suggestion === void 0 ? "" : ` Did you mean ${failure.suggestion}?`;
632
- const message = `Unknown ${failure.kind} ${failure.segment} for ${[bin, ...failure.path].join(" ")}.${suggestion}`;
633
- const issues = [{
634
- field: failure.segment,
635
- message
636
- }];
637
- return failure.kind === "command" ? new CliFailure({
638
- issues,
639
- message,
640
- reason: "unknown_command",
641
- recovery: [{
642
- instruction: "See all commands",
643
- next: { argv: [...failure.path, "--help"] }
644
- }]
645
- }) : usageFailure({
646
- help: failure.path,
647
- issues,
648
- message,
649
- reason: "unknown_option"
650
- });
651
- };
652
- const helpTarget = ({ cli, surface, words }) => {
653
- const { node, path, unknownCommand } = route({
654
- argv: words,
655
- cli,
656
- surface
657
- });
658
- return unknownCommand === null ? {
659
- node,
660
- path
661
- } : routeFailure({
662
- bin: cli.bin,
663
- failure: unknownCommand
664
- });
665
- };
666
- const refusalOf = ({ help, unknownCommand, unknownOption }) => {
667
- if (unknownCommand !== null) return unknownOption ?? unknownCommand;
668
- return help ? null : unknownOption;
669
- };
670
- const readCommandLine = ({ argv, cli, surface }) => {
671
- const routed = route({
672
- argv,
673
- cli,
674
- surface
675
- });
676
- const { node, tokens } = routed;
677
- const { input, issues } = parseLeaf({
678
- arguments: [{
679
- name: WORDS,
680
- optional: true,
681
- variadic: true
682
- }],
683
- command: [cli.bin, ...routed.path].join(" "),
684
- options: knownOptions({
685
- cli,
686
- node: cli.root,
687
- surface
688
- }),
689
- tokens
690
- });
691
- const line = {
692
- options: input.options,
693
- path: routed.path,
694
- unknownCommand: routed.unknownCommand !== null,
695
- used: input.used
696
- };
697
- const help = flagOf(input.options, "help") === true;
698
- const refused = refusalOf({
699
- ...routed,
700
- help
701
- });
702
- if (refused !== null) return {
703
- ...line,
704
- failure: routeFailure({
705
- bin: cli.bin,
706
- failure: refused
707
- }),
708
- kind: "refused"
709
- };
710
- if (isHelpCommand(routed.path)) return issues.length === 0 ? {
711
- ...line,
712
- kind: "helpCommand",
713
- words: input.arguments[WORDS] ?? []
714
- } : {
715
- ...line,
716
- failure: parseFailure({
717
- bin: cli.bin,
718
- issues,
719
- path: routed.path
720
- }),
721
- kind: "refused"
722
- };
723
- if (help) return {
724
- ...line,
725
- kind: "help",
726
- node
727
- };
728
- if (flagOf(input.options, "version") === true) return {
729
- ...line,
730
- kind: "version"
731
- };
732
- if (node.kind === "leaf") return {
733
- ...line,
734
- kind: "leaf",
735
- leaf: node,
736
- tokens
737
- };
738
- const child = childrenOf(node, surface).find((candidate) => candidate.name === node.defaultChild);
739
- return child?.kind === "leaf" ? {
740
- ...line,
741
- kind: "leaf",
742
- leaf: child,
743
- path: [...routed.path, child.name],
744
- tokens
745
- } : {
746
- ...line,
747
- kind: "help",
748
- node
749
- };
750
- };
751
- // ../cli-core/src/help.ts
752
- const COMMANDS = "Commands";
753
- const MIN_WRAP = 20;
754
- const SEARCH_LIMIT = 10;
755
- const PATH_WEIGHT = 3;
756
- const SUMMARY_WEIGHT = 2;
757
- const isNameCharacter = (character) => isWordCharacter(character) || character === "-";
758
- const optionNameEnd = (syntax) => {
759
- const start = syntax.startsWith("-") && isWordCharacter(syntax.charAt(1)) && syntax.startsWith(", ", 2) ? 4 : 0;
760
- if (!syntax.startsWith("--", start)) return 0;
761
- const rest = syntax.slice(start + 2).split("");
762
- const stop = rest.findIndex((character) => !isNameCharacter(character));
763
- const length = stop === -1 ? rest.length : stop;
764
- return length === 0 ? 0 : start + 2 + length;
765
- };
766
- const decorateOptionName = (style, syntax) => {
767
- const end = optionNameEnd(syntax);
768
- return end === 0 ? syntax : `${theme.name(style, syntax.slice(0, end))}${syntax.slice(end)}`;
769
- };
770
- const argumentSyntax = (argument) => {
771
- const name = argument.optional === true ? `[${argument.name}]` : `<${argument.name}>`;
772
- return argument.variadic === true ? `${name}...` : name;
773
- };
774
- const optionSyntax = (option) => {
775
- const hint = option.hint === void 0 ? "" : ` ${option.hint}`;
776
- const long = `--${option.name}${hint}`;
777
- return option.short === void 0 ? long : `-${option.short}, ${long}`;
778
- };
779
- const optionDescription = (option) => {
780
- const parts = [option.summary];
781
- if (option.values !== void 0) parts.push(`(one of: ${option.values.join(", ")})`);
782
- if (option.defaultText !== void 0) parts.push(`(default: ${option.defaultText})`);
783
- return parts.join(" ");
784
- };
785
- const usageText = ({ bin, node, path }) => {
786
- const head = [bin, ...path].join(" ");
787
- if (node.kind === "group") return `${head} <command> [options]`;
788
- return [
789
- head,
790
- ...node.options.flatMap((option) => option.required === true ? [`--${option.name} ${option.hint ?? "<VALUE>"}`] : []),
791
- ...node.arguments.map(argumentSyntax),
792
- "[options]"
793
- ].join(" ");
794
- };
795
- const section = (style, title, lines) => lines.length === 0 ? [] : [
796
- "",
797
- theme.heading(style, `${title}:`),
798
- ...lines
799
- ];
800
- const optionLines = ({ options, style, surface }) => twoColumn({
801
- decorate: (syntax) => decorateOptionName(style, syntax),
802
- entries: optionsFor(options, surface).toSorted((left, right) => left.name.localeCompare(right.name)).map((option) => ({
803
- description: optionDescription(option),
804
- syntax: optionSyntax(option)
805
- })),
806
- indentBy: 2,
807
- width: style.width
808
- });
809
- const commandLines = ({ entries, style }) => twoColumn({
810
- decorate: (syntax) => theme.name(style, syntax),
811
- entries,
812
- indentBy: 2,
813
- width: style.width
814
- });
815
- const taskSections = ({ cli, style, surface }) => cli.tasks.flatMap(({ paths, title }) => section(style, title, commandLines({
816
- entries: paths.flatMap((path) => {
817
- const found = helpTarget({
818
- cli,
819
- surface,
820
- words: path
821
- });
822
- return found instanceof CliFailure ? [] : [{
823
- description: found.node.summary,
824
- syntax: path.join(" ")
825
- }];
826
- }),
827
- style
828
- })));
829
- const childSections = ({ node, style, surface }) => [...section(style, COMMANDS, commandLines({
830
- entries: childrenOf(node, surface).map((child) => ({
831
- description: node.defaultChild === child.name ? `${child.summary} (default)` : child.summary,
832
- syntax: [child.name, ...child.shortcuts ?? []].join(", ")
833
- })),
834
- style
835
- })), ...section(style, "Options", optionLines({
836
- options: node.options ?? [],
837
- style,
838
- surface
839
- }))];
840
- const groupSections = ({ cli, isRoot, node, style, surface }) => isRoot ? taskSections({
841
- cli,
842
- style,
843
- surface
844
- }) : childSections({
845
- node,
846
- style,
847
- surface
848
- });
849
- const leafSections = ({ node, style, surface }) => [...section(style, "Arguments", twoColumn({
850
- entries: node.arguments.map((argument) => ({
851
- description: argument.summary,
852
- syntax: argumentSyntax(argument)
853
- })),
854
- indentBy: 2,
855
- width: style.width
856
- })), ...section(style, "Options", optionLines({
857
- options: node.options,
858
- style,
859
- surface
860
- }))];
861
- const exampleLines = ({ bin, node, style }) => node.kind === "leaf" ? section(style, "Examples", node.examples.flatMap(({ argv, summary }, index) => [
862
- ...index === 0 ? [] : [""],
863
- ` ${summary}`,
864
- ` ${styledCommand({
865
- argv: [bin, ...argv],
866
- style
867
- })}`
868
- ])) : [];
869
- const renderHelp = ({ cli, node, path, style, surface }) => {
870
- const isRoot = path.length === 0;
871
- const head = [cli.bin, ...path].join(" ");
872
- const usage = usageText({
873
- bin: cli.bin,
874
- node,
875
- path
876
- });
877
- const width = Math.max(MIN_WRAP, style.width - 2);
878
- return `${[
879
- `${theme.name(style, head)}${usage.slice(head.length)}`,
880
- theme.optional(style, node.summary),
881
- ...node.kind === "leaf" ? leafSections({
882
- node,
883
- style,
884
- surface
885
- }) : groupSections({
886
- cli,
887
- isRoot,
888
- node,
889
- style,
890
- surface
891
- }),
892
- ...isRoot ? section(style, "Global Options", optionLines({
893
- options: cli.globals,
894
- style,
895
- surface
896
- })) : ["", `${theme.heading(style, "Global Options:")} See \`${cli.bin} --help\``],
897
- ...exampleLines({
898
- bin: cli.bin,
899
- node,
900
- style
901
- }),
902
- ...section(style, "Notes", (node.notes ?? []).flatMap((note) => indent(wrap({
903
- text: note,
904
- width
905
- }), 2))),
906
- ...cli.learnMore === void 0 ? [] : ["", `Learn more: ${cli.learnMore}`]
907
- ].join("\n")}\n`;
908
- };
909
- const optionDocument = (option) => ({
910
- default: option.defaultText ?? null,
911
- name: option.name,
912
- repeatable: option.repeat === "append",
913
- short: option.short ?? null,
914
- type: option.kind === "flag" ? "boolean" : "string",
915
- values: option.values ?? null,
916
- valueHint: option.hint ?? null
917
- });
918
- const argumentDocument = (argument) => ({
919
- name: argument.name,
920
- required: argument.optional !== true,
921
- summary: argument.summary
922
- });
923
- const exampleDocuments = ({ bin, node }) => node.kind === "leaf" ? node.examples.map(({ argv, summary }) => ({
924
- argv: [bin, ...argv],
925
- command: shellCommand([bin, ...argv]),
926
- summary
927
- })) : [];
928
- const subcommandDocument = ({ child, group }) => ({
929
- default: group.defaultChild === child.name,
930
- summary: child.summary
931
- });
932
- const allCommands = ({ path = [], root, surface }) => childrenOf(root, surface).flatMap((child) => {
933
- const childPath = [...path, child.name];
934
- return child.kind === "group" ? [{
935
- node: child,
936
- path: childPath
937
- }, ...allCommands({
938
- path: childPath,
939
- root: child,
940
- surface
941
- })] : [{
942
- node: child,
943
- path: childPath
944
- }];
945
- });
946
- const scoreOf = ({ node, path, words }) => {
947
- const named = path.join(" ");
948
- const summary = node.summary.toLowerCase();
949
- const examples = node.kind === "leaf" ? node.examples.flatMap((example) => [example.summary, example.argv.join(" ")]).join(" ").toLowerCase() : "";
950
- return words.reduce((score, word) => score + (named.includes(word) ? PATH_WEIGHT : 0) + (summary.includes(word) ? SUMMARY_WEIGHT : 0) + (examples.includes(word) ? 1 : 0), 0);
951
- };
952
- const searchCommands = ({ query, root, surface }) => {
953
- const words = query.toLowerCase().split("").map((character) => character === "," || character.trim() === "" ? " " : character).join("").split(" ").filter((word) => word !== "");
954
- return allCommands({
955
- root,
956
- surface
957
- }).flatMap((entry) => {
958
- const score = scoreOf({
959
- ...entry,
960
- words
961
- });
962
- return score > 0 ? [{
963
- entry,
964
- score
965
- }] : [];
966
- }).toSorted((left, right) => right.score - left.score || left.entry.path.join(" ").localeCompare(right.entry.path.join(" "))).slice(0, SEARCH_LIMIT).map(({ entry }) => entry);
967
- };
968
- const listCommands = ({ bin, empty, found, io }) => {
969
- io.table({
970
- empty,
971
- table: {
972
- columns: [{ header: "Command" }, { header: "Summary" }],
973
- rows: found.map(({ node, path }) => [[bin, ...path].join(" "), node.summary])
974
- }
975
- });
976
- if (found.length === 0) io.next([{
977
- argv: ["--help"],
978
- benefit: "See all commands"
979
- }]);
980
- };
981
- // ../cli-core/src/mode.ts
982
- const DEFAULT_WIDTH = 80;
983
- const terminalOf = (stream) => ({
984
- columns: stream.columns,
985
- tty: stream.isTTY === true
986
- });
987
- const falsy = /* @__PURE__ */ new Set([
988
- "",
989
- "0",
990
- "false"
991
- ]);
992
- const enabledVariable = (value) => value !== void 0 && !falsy.has(value.trim().toLowerCase());
993
- const nonempty = (value) => value !== void 0 && value !== "";
994
- const colorPreference = ({ env, noColor }) => {
995
- if (noColor || nonempty(env.NO_COLOR)) return false;
996
- const forced = env.FORCE_COLOR;
997
- if (forced === void 0) return;
998
- return forced !== "0" && forced.toLowerCase() !== "false";
999
- };
1000
- const streamStyle = ({ accessible, color, env, terminal }) => {
1001
- const rich = terminal.tty && env.TERM !== "dumb" && !accessible;
1002
- return {
1003
- color: color ?? rich,
1004
- rich,
1005
- tty: terminal.tty,
1006
- width: terminal.columns !== void 0 && terminal.columns > 0 ? terminal.columns : DEFAULT_WIDTH
1007
- };
1008
- };
1009
- const interactionAllowed = (input, ci) => {
1010
- if (!(input.stdin.tty && input.stderr.tty && !input.payloadStdin) || input.json || ci || input.nonInteractive === true) return false;
1011
- return input.agent === void 0 || input.nonInteractive === false;
1012
- };
1013
- const resolveMode = (input) => {
1014
- const { accessible } = input;
1015
- const ci = enabledVariable(input.env.CI);
1016
- const color = colorPreference(input);
1017
- return {
1018
- accessible,
1019
- agent: input.agent,
1020
- ci,
1021
- format: input.json ? "json" : "human",
1022
- githubActions: input.env.GITHUB_ACTIONS === "true",
1023
- interactive: interactionAllowed(input, ci),
1024
- stderr: streamStyle({
1025
- accessible,
1026
- color,
1027
- env: input.env,
1028
- terminal: input.stderr
1029
- }),
1030
- stdout: streamStyle({
1031
- accessible,
1032
- color,
1033
- env: input.env,
1034
- terminal: input.stdout
1035
- })
1036
- };
1037
- };
1038
- const AGENT_VARIABLES = [
1039
- "AGENT",
1040
- "AI_AGENT",
1041
- "AUGMENT_AGENT",
1042
- "CLAUDECODE",
1043
- "CLAUDE_CODE",
1044
- "CODEX_SANDBOX",
1045
- "CURSOR_AGENT",
1046
- "GEMINI_CLI",
1047
- "OPENCODE"
1048
- ];
1049
- const productVariable = ({ bin, name }) => `${bin.toUpperCase()}_${name}`;
1050
- const guidanceOn = ({ bin, env = process.env }) => !enabledVariable(env[productVariable({
1051
- bin,
1052
- name: "GUIDANCE_DISABLED"
1053
- })]);
1054
- const accessibleOn = ({ bin, env = process.env }) => enabledVariable(env[productVariable({
1055
- bin,
1056
- name: "ACCESSIBLE"
1057
- })]);
1058
- const modeOf = ({ bin, env = process.env, io, json, noColor, nonInteractive, payloadStdin }) => resolveMode({
1059
- accessible: accessibleOn({
1060
- bin,
1061
- env
1062
- }),
1063
- agent: AGENT_VARIABLES.find((name) => enabledVariable(env[name])),
1064
- env,
1065
- json,
1066
- noColor,
1067
- nonInteractive: nonInteractive ?? null,
1068
- payloadStdin,
1069
- stderr: terminalOf(io.stderr),
1070
- stdin: terminalOf(io.stdin),
1071
- stdout: terminalOf(io.stdout)
1072
- });
1073
- // ../cli-core/src/prompt.ts
1074
- const ask = async (question) => {
1075
- const { promise, reject, resolve } = Promise.withResolvers();
1076
- const prompt = readline.createInterface({
1077
- input: process.stdin,
1078
- output: process.stderr,
1079
- terminal: true
1080
- });
1081
- let answered = false;
1082
- prompt.on("SIGINT", () => {
1083
- prompt.close();
1084
- });
1085
- prompt.on("close", () => {
1086
- if (!answered) {
1087
- process.stderr.write("\n");
1088
- reject(new Canceled({
1089
- remote: "none",
1090
- signal: "SIGINT"
1091
- }));
1092
- }
1093
- });
1094
- prompt.question(`? ${question} `, (answer) => {
1095
- answered = true;
1096
- prompt.close();
1097
- resolve(answer);
1098
- });
1099
- return await promise;
1100
- };
1101
- const terminalPrompter = {
1102
- confirm: async (question) => {
1103
- const answer = await ask(`${question} (y/N)`);
1104
- return ["y", "yes"].includes(answer.trim().toLowerCase());
1105
- },
1106
- text: async (question) => await ask(question)
1107
- };
1108
- // ../cli-core/src/telemetry-settings.ts
1109
- const telemetrySettingsSchema = Struct({
1110
- disclosed: optional(Boolean),
1111
- enabled: optional(Boolean)
1112
- });
1113
- const settingsSchema = Struct({ telemetry: optional(telemetrySettingsSchema) });
1114
- const decodeSettings = decodeUnknownOption(fromJsonString(settingsSchema));
1115
- const readSettings = (file) => {
1116
- const read = try_(() => fs.readFileSync(file, "utf-8"));
1117
- if (isSuccess(read)) return getOrUndefined(decodeSettings(read.success));
1118
- return hasProperty(read.failure, "code") && read.failure.code === "ENOENT" ? {} : void 0;
1119
- };
1120
- const disabledVariable = (bin) => productVariable({
1121
- bin,
1122
- name: "TELEMETRY_DISABLED"
1123
- });
1124
- const telemetryStatus = ({ bin, env = process.env, file }) => {
1125
- const settings = readSettings(file);
1126
- const disclosed = settings?.telemetry?.disclosed === true;
1127
- if (enabledVariable(env[disabledVariable(bin)])) return {
1128
- disclosed,
1129
- enabled: false,
1130
- readable: settings !== void 0,
1131
- source: "environment"
1132
- };
1133
- if (settings === void 0) return {
1134
- disclosed,
1135
- enabled: false,
1136
- readable: false,
1137
- source: "settings"
1138
- };
1139
- const enabled = settings.telemetry?.enabled;
1140
- return enabled === void 0 ? {
1141
- disclosed,
1142
- enabled: true,
1143
- readable: true,
1144
- source: "default"
1145
- } : {
1146
- disclosed,
1147
- enabled,
1148
- readable: true,
1149
- source: "settings"
1150
- };
1151
- };
1152
- const writeTelemetry = ({ file, telemetry }) => {
1153
- const settings = readSettings(file) ?? {};
1154
- writePrivateFile({
1155
- file,
1156
- text: `${JSON.stringify({
1157
- ...settings,
1158
- telemetry: {
1159
- ...settings.telemetry,
1160
- ...telemetry
1161
- }
1162
- }, null, 2)}\n`
1163
- });
1164
- };
1165
- const statusText = ({ bin, file, status }) => {
1166
- if (status.source === "environment") return `Off, since ${disabledVariable(bin)} is set.`;
1167
- if (!status.readable) return `Off, since ${file} can't be read.`;
1168
- return status.enabled ? "On." : "Off.";
1169
- };
1170
- const telemetryCommand = ({ action, bin, env = process.env, file, io }) => {
1171
- const report = (status, outcome) => {
1172
- io.receipt({
1173
- outcome: "Telemetry",
1174
- target: statusText({
1175
- bin,
1176
- file,
1177
- status
1178
- })
1179
- });
1180
- return {
1181
- outcome,
1182
- telemetry: {
1183
- enabled: status.enabled,
1184
- source: status.source
1185
- }
1186
- };
1187
- };
1188
- const before = telemetryStatus({
1189
- bin,
1190
- env,
1191
- file
1192
- });
1193
- if (action === "status") return report(before);
1194
- if (!before.readable) return new CliFailure({
1195
- message: `${file}: the CLI settings can't be read.`,
1196
- notes: ["Fix the file or move it away, then run the command again."],
1197
- reason: "invalid_config"
1198
- });
1199
- const enabled = action === "enable";
1200
- if (before.source === "settings" && before.enabled === enabled) return report(before, "unchanged");
1201
- writeTelemetry({
1202
- file,
1203
- telemetry: {
1204
- disclosed: true,
1205
- enabled
1206
- }
1207
- });
1208
- return report(telemetryStatus({
1209
- bin,
1210
- env,
1211
- file
1212
- }), enabled ? "enabled" : "disabled");
1213
- };
1214
- // src/cli/local.ts
1215
- const helpSearch = (context) => {
1216
- const query = (context.arguments.query ?? []).join(" ");
1217
- const found = searchCommands({
1218
- query,
1219
- root: CLI.root,
1220
- surface: "cli"
1221
- });
1222
- listCommands({
1223
- bin: CLI.bin,
1224
- empty: `No commands match "${query}".`,
1225
- found,
1226
- io: context.io
1227
- });
1228
- return { document: { commands: found.map(({ node, path }) => ({
1229
- argv: [CLI.bin, ...path],
1230
- path: path.join(" "),
1231
- summary: node.summary
1232
- })) } };
1233
- };
1234
- const telemetry = (action) => ({ io, settingsFile }) => {
1235
- const document = telemetryCommand({
1236
- action,
1237
- bin: CLI.bin,
1238
- file: settingsFile,
1239
- io
1240
- });
1241
- if (document instanceof CliFailure) throw document;
1242
- return { document };
1243
- };
1244
- const LOCAL_COMMANDS = /* @__PURE__ */ new Map([
1245
- ["cli telemetry disable", telemetry("disable")],
1246
- ["cli telemetry enable", telemetry("enable")],
1247
- ["cli telemetry status", telemetry("status")],
1248
- ["help search", helpSearch]
1249
- ]);
1250
- // src/cli/settings.ts
1251
- const settingsFileOf = (directory) => path.join(configDirectory({
1252
- bin: BIN,
1253
- override: directory
1254
- }), "settings.json");
1255
- // src/cli/telemetry.ts
1256
- const DISCLOSURE = "The Sandcovery CLI sends anonymous usage data: command paths, option names, failure reasons, and exit codes, never values or remote data.";
1257
- const DISCLOSURE_STEP = {
1258
- argv: [
1259
- "cli",
1260
- "telemetry",
1261
- "disable"
1262
- ],
1263
- benefit: "Turn it off"
1264
- };
1265
- const telemetryHost = (origin) => loopbackOrigin(process.env.__SANDCOVERY_POSTHOG_HOST) ?? (origin === "https://www.sandcovery.com" ? "https://us.i.posthog.com" : void 0);
1266
- const sendTelemetry = ({ event, host }) => {
1267
- sendTelemetry$1({
1268
- bin: BIN,
1269
- event: {
1270
- ...event,
1271
- version
1272
- },
1273
- host
1274
- });
1275
- };
1276
- // src/cli/main.ts
1277
- const CANCELED_EXIT = 130;
1278
- const SUCCESS = { exitCode: 0 };
1279
- const UNREADABLE = /* @__PURE__ */ new Map([
1280
- ["EACCES", "isn't readable"],
1281
- ["EISDIR", "is a directory"],
1282
- ["ENOENT", "doesn't exist"]
1283
- ]);
1284
- const globalsOf = (options) => ({
1285
- debug: flagOf(options, "debug") === true,
1286
- globalConfig: lastValue(options, "global-config"),
1287
- json: flagOf(options, "json") === true,
1288
- noColor: flagOf(options, "no-color") === true,
1289
- nonInteractive: flagOf(options, "non-interactive"),
1290
- token: lastValue(options, "token")
1291
- });
1292
- const commandOf = ({ leaf, path: commandPath, tokens }) => {
1293
- const { input, issues } = parseLeaf({
1294
- arguments: leaf.arguments,
1295
- command: [CLI.bin, ...commandPath].join(" "),
1296
- options: [...CLI.globals, ...leaf.options],
1297
- tokens
1298
- });
1299
- if (issues.length > 0) return {
1300
- failure: parseFailure({
1301
- bin: CLI.bin,
1302
- issues,
1303
- path: commandPath
1304
- }),
1305
- kind: "failure"
1306
- };
1307
- const empty = Object.entries(input.options).find(([, value]) => value.kind === "value" && value.values.some((text) => text.trim() === ""));
1308
- if (empty !== void 0) {
1309
- const field = `--${empty[0]}`;
1310
- const message = `Can't use an empty ${field}.`;
1311
- return {
1312
- failure: usageFailure({
1313
- help: commandPath,
1314
- issues: [{
1315
- field,
1316
- message
1317
- }],
1318
- message
1319
- }),
1320
- kind: "failure"
1321
- };
1322
- }
1323
- return {
1324
- input,
1325
- kind: "command",
1326
- path: commandPath
1327
- };
1328
- };
1329
- const invocationOf = (line) => {
1330
- switch (line.kind) {
1331
- case "refused": return {
1332
- failure: line.failure,
1333
- kind: "failure"
1334
- };
1335
- case "helpCommand": return {
1336
- all: flagOf(line.options, "all") === true,
1337
- kind: "help",
1338
- path: line.words
1339
- };
1340
- case "help": return {
1341
- all: false,
1342
- kind: "help",
1343
- path: line.path
1344
- };
1345
- case "version": return { kind: "version" };
1346
- case "leaf": return commandOf(line);
1347
- default: return commandOf(line);
1348
- }
1349
- };
1350
- const failed = ({ failure, session }) => {
1351
- session.out.failure(failure);
1352
- return {
1353
- exitCode: exitCodeOf(failure.reason),
1354
- reason: failure.reason
1355
- };
1356
- };
1357
- const succeeded = ({ finished, session }) => {
1358
- if (session.mode.format === "json") session.out.document(jsonRecord({ value: finished.document }));
1359
- else if (finished.next !== void 0 && finished.next.length > 0) session.out.next(finished.next);
1360
- return { exitCode: finished.exitCode ?? 0 };
1361
- };
1362
- const canceled = ({ progress, session }) => {
1363
- const unknown = progress.sent && progress.mutation;
1364
- const lines = unknown ? ["Stopped waiting. Can't confirm whether the request finished."] : [progress.sent ? "Canceled." : "Canceled. Nothing was changed."];
1365
- session.out.canceled({
1366
- lines,
1367
- next: unknown && progress.inspect !== null ? [{
1368
- argv: progress.inspect,
1369
- benefit: "Check what happened"
1370
- }] : [],
1371
- remote: unknown ? "unknown" : "none"
1372
- });
1373
- return {
1374
- exitCode: Number.isInteger(session.signal.reason) ? Number(session.signal.reason) : CANCELED_EXIT,
1375
- reason: "canceled"
1376
- };
1377
- };
1378
- const internalFailure = (commandPath) => new CliFailure({
1379
- message: `Unexpected error in sandcovery ${commandPath.join(" ")}. This is a bug in the Sandcovery CLI.`,
1380
- reason: "internal_error",
1381
- recovery: [{
1382
- instruction: "See the details",
1383
- next: { argv: [...commandPath, "--debug"] }
1384
- }, {
1385
- instruction: "Report it to the Sandcovery team",
1386
- url: "mailto:team@sandcovery.com"
1387
- }]
1388
- });
1389
- const debugLine = (session) => (line) => {
1390
- if (session.globals.debug) session.io.stderr.write(`debug: ${line}\n`);
1391
- };
1392
- const readSource = async (source) => {
1393
- if (source === "-") return new Uint8Array(await buffer(process.stdin));
1394
- const read = try_(() => fs.readFileSync(path.resolve(source)));
1395
- if (isSuccess(read)) return new Uint8Array(read.success);
1396
- const { failure } = read;
1397
- const reason = UNREADABLE.get(hasProperty(failure, "code") && isString(failure.code) ? failure.code : "");
1398
- if (reason === void 0) throw failure;
1399
- throw new CliFailure({
1400
- message: `Can't read ${source}. The file ${reason}.`,
1401
- reason: "invalid_arguments"
1402
- });
1403
- };
1404
- const runCommand = async ({ invocation, session }) => {
1405
- const progress = {
1406
- inspect: null,
1407
- mutation: false,
1408
- sent: false
1409
- };
1410
- const { input } = invocation;
1411
- const context = {
1412
- arguments: input.arguments,
1413
- debug: debugLine(session),
1414
- io: session.out,
1415
- mode: session.mode,
1416
- now: /* @__PURE__ */ new Date(),
1417
- options: input.options,
1418
- path: invocation.path,
1419
- progress,
1420
- prompter: session.mode.interactive ? terminalPrompter : void 0,
1421
- read: readSource,
1422
- rerun: rerunArgv({
1423
- arguments: input.arguments,
1424
- options: input.options,
1425
- path: invocation.path
1426
- }),
1427
- settingsFile: session.settingsFile,
1428
- signal: session.signal,
1429
- streams: {
1430
- stderr: session.io.stderr,
1431
- stdout: session.io.stdout
1432
- },
1433
- token: session.globals.token
1434
- };
1435
- const key = invocation.path.join(" ");
1436
- const settle = async () => {
1437
- try {
1438
- const local = LOCAL_COMMANDS.get(key);
1439
- if (local !== void 0) return local(context);
1440
- const { HANDLERS } = await import("../handlers-BS1KuMqq.mjs");
1441
- const handler = HANDLERS.get(key);
1442
- if (handler === void 0) throw internalFailure(invocation.path);
1443
- return await handler(context);
1444
- } catch (error) {
1445
- if (error instanceof Canceled || error instanceof CliFailure || session.signal.aborted) throw error;
1446
- context.debug(error instanceof Error ? error.stack ?? error.message : String(error));
1447
- throw internalFailure(invocation.path);
1448
- }
1449
- };
1450
- try {
1451
- return succeeded({
1452
- finished: await settle(),
1453
- session
1454
- });
1455
- } catch (error) {
1456
- if (error instanceof Canceled || session.signal.aborted) return canceled({
1457
- progress,
1458
- session
1459
- });
1460
- if (error instanceof CliFailure) return failed({
1461
- failure: error,
1462
- session
1463
- });
1464
- throw error;
1465
- }
1466
- };
1467
- const optionDocumentOf = (option) => ({
1468
- ...optionDocument(option),
1469
- deprecated: null,
1470
- summary: option.summary
1471
- });
1472
- const commandDocument = ({ node, path: nodePath }) => ({
1473
- arguments: node.kind === "group" ? [] : node.arguments.map(argumentDocument),
1474
- examples: exampleDocuments({
1475
- bin: CLI.bin,
1476
- node
1477
- }),
1478
- lifecycle: null,
1479
- options: node.kind === "group" ? [] : node.options.map(optionDocumentOf),
1480
- path: nodePath.join(" "),
1481
- resultSchema: node.kind === "group" || node.result.length === 0 ? null : { fields: node.result.map(({ name, secret, type }) => ({
1482
- name,
1483
- secret: secret ?? false,
1484
- type
1485
- })) },
1486
- subcommands: node.kind === "group" ? node.children.map((child) => ({
1487
- ...subcommandDocument({
1488
- child,
1489
- group: node
1490
- }),
1491
- path: [...nodePath, child.name].join(" ")
1492
- })) : [],
1493
- summary: node.summary
1494
- });
1495
- const showHelp = ({ all, path: words, session }) => {
1496
- const json = session.mode.format === "json";
1497
- if (all) {
1498
- const commands = allCommands({
1499
- root: CLI.root,
1500
- surface: "cli"
1501
- });
1502
- if (json) session.out.document(jsonRecord({ value: { commands: [{
1503
- node: CLI.root,
1504
- path: []
1505
- }, ...commands].map(commandDocument) } }));
1506
- else listCommands({
1507
- bin: CLI.bin,
1508
- empty: "",
1509
- found: commands,
1510
- io: session.out
1511
- });
1512
- return SUCCESS;
1513
- }
1514
- const target = helpTarget({
1515
- cli: CLI,
1516
- surface: "cli",
1517
- words
1518
- });
1519
- if (target instanceof CliFailure) return failed({
1520
- failure: target,
1521
- session
1522
- });
1523
- if (json) session.out.document(jsonRecord({ value: target.path.length === 0 ? {
1524
- ...commandDocument(target),
1525
- globalOptions: CLI.globals.map(optionDocumentOf)
1526
- } : commandDocument(target) }));
1527
- else session.io.stdout.write(renderHelp({
1528
- cli: CLI,
1529
- ...target,
1530
- style: session.mode.stdout,
1531
- surface: "cli"
1532
- }));
1533
- return SUCCESS;
1534
- };
1535
- const dispatch = async (session) => {
1536
- const { invocation } = session;
1537
- switch (invocation.kind) {
1538
- case "failure": return failed({
1539
- failure: invocation.failure,
1540
- session
1541
- });
1542
- case "help": return showHelp({
1543
- all: invocation.all,
1544
- path: invocation.path,
1545
- session
1546
- });
1547
- case "version":
1548
- if (session.mode.format === "json") session.out.document({ version });
1549
- else session.io.stdout.write(`${version}\n`);
1550
- return SUCCESS;
1551
- case "command": return await runCommand({
1552
- invocation,
1553
- session
1554
- });
1555
- default: return await runCommand({
1556
- invocation,
1557
- session
1558
- });
1559
- }
1560
- };
1561
- const discloses = (session) => session.mode.format !== "json" && session.invocation.kind !== "help" && session.invocation.kind !== "version" && !session.telemetryPath.startsWith("cli telemetry");
1562
- const disclose = (session) => {
1563
- if (session.mode.interactive) {
1564
- session.out.note([DISCLOSURE]);
1565
- session.out.next([DISCLOSURE_STEP]);
1566
- } else session.io.stderr.write(`${DISCLOSURE} Turn it off with ${shellCommand([CLI.bin, ...DISCLOSURE_STEP.argv])} or SANDCOVERY_TELEMETRY_DISABLED=1.\n`);
1567
- const saved = try_(() => {
1568
- writeTelemetry({
1569
- file: session.settingsFile,
1570
- telemetry: { disclosed: true }
1571
- });
1572
- });
1573
- if (isFailure(saved)) session.out.note([`Couldn't save to ${session.settingsFile} that telemetry was disclosed.`]);
1574
- };
1575
- const statusOf = (session) => telemetryStatus({
1576
- bin: CLI.bin,
1577
- file: session.settingsFile
1578
- });
1579
- const telemetryAllowed = ({ host, session }) => {
1580
- if (host === void 0) return false;
1581
- const status = statusOf(session);
1582
- if (!status.enabled) return false;
1583
- if (status.disclosed) return true;
1584
- if (!discloses(session)) return false;
1585
- disclose(session);
1586
- return true;
1587
- };
1588
- const originFor = (options) => {
1589
- const chosen = [lastValue(options, "base-url"), process.env.SANDCOVERY_BASE_URL].find((value) => value !== void 0 && value.trim() !== "");
1590
- return chosen === void 0 ? SANDCOVERY_ORIGIN : URL.parse(chosen.trim())?.origin ?? chosen;
1591
- };
1592
- const run = async ({ argv, io, signal }) => {
1593
- const line = readCommandLine({
1594
- argv,
1595
- cli: CLI,
1596
- surface: "cli"
1597
- });
1598
- const globals = globalsOf(line.options);
1599
- const invocation = invocationOf(line);
1600
- const options = invocation.kind === "command" ? invocation.input.options : line.options;
1601
- const mode = modeOf({
1602
- bin: CLI.bin,
1603
- io,
1604
- json: globals.json,
1605
- noColor: globals.noColor,
1606
- nonInteractive: globals.nonInteractive,
1607
- payloadStdin: lastValue(options, "from") === "-"
1608
- });
1609
- const session = {
1610
- globals,
1611
- invocation,
1612
- io,
1613
- mode,
1614
- out: new Output({
1615
- bin: CLI.bin,
1616
- err: io.stderr,
1617
- guidance: guidanceOn({ bin: CLI.bin }),
1618
- mode,
1619
- out: io.stdout
1620
- }),
1621
- settingsFile: settingsFileOf(globals.globalConfig),
1622
- signal,
1623
- telemetryPath: [...line.path, ...line.unknownCommand ? ["<path>"] : []].join(" ")
1624
- };
1625
- if (globals.debug) io.stderr.write(`debug: sandcovery ${version}, node ${process.version}, ${process.platform}, interactive ${String(mode.interactive)}, agent ${String(mode.agent !== void 0)}, ci ${String(mode.ci)}\n`);
1626
- const host = telemetryHost(originFor(options));
1627
- const send = telemetryAllowed({
1628
- host,
1629
- session
1630
- });
1631
- const outcome = await dispatch(session);
1632
- if (send && host !== void 0 && statusOf(session).enabled) sendTelemetry({
1633
- event: {
1634
- command: session.telemetryPath,
1635
- exitCode: outcome.exitCode,
1636
- options: line.used,
1637
- reason: outcome.reason
1638
- },
1639
- host
1640
- });
1641
- return outcome.exitCode;
1642
- };
2
+ import { t as start } from "../start-B8ruSPVb.mjs";
1643
3
  // src/cli/index.ts
1644
- const SIGNAL_EXITS = [
1645
- ["SIGHUP", 129],
1646
- ["SIGINT", 130],
1647
- ["SIGTERM", 143]
1648
- ];
1649
- const quietOnBrokenPipe = (stream) => {
1650
- stream.on("error", (error) => {
1651
- if (error.code === "EPIPE") process.exit(process.exitCode ?? 0);
1652
- throw error;
1653
- });
1654
- };
1655
- const applyProxyFromEnv = () => {
1656
- if ([
1657
- process.env.HTTPS_PROXY,
1658
- process.env.https_proxy,
1659
- process.env.HTTP_PROXY,
1660
- process.env.http_proxy
1661
- ].some((value) => value !== void 0 && value !== "") && Object.hasOwn(http, "setGlobalProxyFromEnv")) http.setGlobalProxyFromEnv();
1662
- };
1663
- const event = process.env.__SANDCOVERY_TELEMETRY_EVENT;
1664
- applyProxyFromEnv();
1665
- if (event === void 0) {
1666
- quietOnBrokenPipe(process.stdout);
1667
- quietOnBrokenPipe(process.stderr);
1668
- const controller = new AbortController();
1669
- for (const [signal, code] of SIGNAL_EXITS) process.on(signal, () => {
1670
- if (controller.signal.aborted) process.exit(code);
1671
- controller.abort(code);
1672
- });
1673
- process.exitCode = await run({
1674
- argv: process.argv.slice(2),
1675
- io: {
1676
- stderr: process.stderr,
1677
- stdin: process.stdin,
1678
- stdout: process.stdout
1679
- },
1680
- signal: controller.signal
1681
- });
1682
- } else {
1683
- const [{ deliverTelemetry }, project] = await Promise.all([import("../telemetry-delivery-Yd6CeynR.mjs"), import("../posthog-project-BpOd2VxW.mjs")]);
1684
- await deliverTelemetry({
1685
- host: process.env.__SANDCOVERY_POSTHOG_HOST,
1686
- productionHost: project.POSTHOG_INGEST_HOST,
1687
- text: event,
1688
- token: project.POSTHOG_PROJECT_TOKEN
1689
- });
1690
- }
4
+ await start({ argv: process.argv.slice(2) });
1691
5
  export {};