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