@kaynooo/cli-env 0.8.0 → 0.8.1

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.
Files changed (3) hide show
  1. package/dist/ev.js +348 -134
  2. package/dist/redact.js +320 -106
  3. package/package.json +2 -2
package/dist/redact.js CHANGED
@@ -2,10 +2,10 @@
2
2
  // @bun
3
3
 
4
4
  // src/redact.ts
5
- import process7 from "process";
5
+ import process10 from "process";
6
6
 
7
7
  // ../kit/src/args.ts
8
- import process4 from "process";
8
+ import process6 from "process";
9
9
  import { parseArgs } from "util";
10
10
 
11
11
  // ../kit/src/format.ts
@@ -14,7 +14,7 @@ import process3 from "process";
14
14
  // ../kit/src/style.ts
15
15
  import process2 from "process";
16
16
 
17
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
17
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
18
  function x(s) {
19
19
  let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
20
20
  if (!/^[a-f0-9]+$/.test(r))
@@ -234,7 +234,7 @@ class e {
234
234
  }
235
235
  }
236
236
 
237
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
237
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
238
238
  var r = 39;
239
239
  var o = 49;
240
240
  var f2 = "\x1B[";
@@ -358,6 +358,55 @@ function printJson(value) {
358
358
  console.log(JSON.stringify(value, undefined, 2));
359
359
  }
360
360
 
361
+ // ../kit/src/help.ts
362
+ import process4 from "process";
363
+ var OPTIONAL = /\[[^\]]+\]/g;
364
+ var USAGE_PREFIX = /^usage:\s*/i;
365
+ var FULL_STOP = /\.$/;
366
+ function usageLine(usage, colors = paint(process4.stdout)) {
367
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
368
+ }
369
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces } = {}) {
370
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
371
+ `);
372
+ }
373
+ function replacesRows(replaces, colors = paint(process4.stdout)) {
374
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
375
+ }
376
+ function wantsHelpJson(env = process4.env) {
377
+ return env.KIT_HELP === "json";
378
+ }
379
+ function description(usage, { examples = [], replaces } = {}) {
380
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
381
+ `);
382
+ const first = lines[0];
383
+ const colon = first.indexOf(": ");
384
+ const prose = lines[lines.indexOf("") + 1] ?? "";
385
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
386
+ return {
387
+ synopsis: colon === -1 ? first : first.slice(0, colon),
388
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
389
+ ...replaces === undefined ? {} : { replaces },
390
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
391
+ };
392
+ }
393
+ function exampleRows(examples, colors = paint(process4.stdout)) {
394
+ if (examples.length === 0)
395
+ return [];
396
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
397
+ }
398
+ function optionRows(options, colors = paint(process4.stdout)) {
399
+ const rows = Object.entries(options).map(([name, option]) => {
400
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
401
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
402
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
403
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
404
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
405
+ });
406
+ const width = Math.max(0, ...rows.map((row) => row.width));
407
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
408
+ }
409
+
361
410
  // ../kit/src/text.ts
362
411
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
363
412
  function distance(a, b) {
@@ -377,8 +426,22 @@ function closest(name, names) {
377
426
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
378
427
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
379
428
  }
429
+ // ../kit/src/input.ts
430
+ import process5 from "process";
431
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
432
+ if (path === "-") {
433
+ if (process5.stdin.isTTY)
434
+ fail(noStdin);
435
+ return Bun.stdin.text();
436
+ }
437
+ const file = Bun.file(path);
438
+ if (!await file.exists())
439
+ fail(`no file ${path}`);
440
+ return file.text();
441
+ }
380
442
 
381
443
  // ../kit/src/args.ts
444
+ var DASHES = /^-+/;
382
445
  function jsonOption(holds) {
383
446
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
384
447
  }
@@ -413,61 +476,20 @@ class HelpShown extends Exit {
413
476
 
414
477
  class Completing {
415
478
  options;
416
- constructor(options) {
479
+ positionals;
480
+ candidates;
481
+ constructor(options, positionals = [], candidates = {}) {
417
482
  this.options = options;
483
+ this.positionals = positionals;
484
+ this.candidates = candidates;
418
485
  }
419
486
  }
420
487
  var completion = { active: false };
421
- var OPTIONAL = /\[[^\]]+\]/g;
422
- var USAGE_PREFIX = /^usage:\s*/i;
423
- var FULL_STOP = /\.$/;
424
- var DASHES = /^-+/;
425
- function usageLine(usage, colors = paint(process4.stdout)) {
426
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
427
- }
428
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces } = {}) {
429
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
430
- `);
431
- }
432
- function replacesRows(replaces, colors = paint(process4.stdout)) {
433
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
434
- }
435
- function wantsHelpJson(env = process4.env) {
436
- return env.KIT_HELP === "json";
437
- }
438
- function description(usage, { examples = [], replaces } = {}) {
439
- const lines = usage.replace(USAGE_PREFIX, "").split(`
440
- `);
441
- const first = lines[0];
442
- const colon = first.indexOf(": ");
443
- const prose = lines[lines.indexOf("") + 1] ?? "";
444
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
445
- return {
446
- synopsis: colon === -1 ? first : first.slice(0, colon),
447
- summary: colon === -1 ? fallback : first.slice(colon + 2),
448
- ...replaces === undefined ? {} : { replaces },
449
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
450
- };
451
- }
452
- function exampleRows(examples, colors = paint(process4.stdout)) {
453
- if (examples.length === 0)
454
- return [];
455
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
456
- }
457
- function optionRows(options, colors = paint(process4.stdout)) {
458
- const rows = Object.entries(options).map(([name, option]) => {
459
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
460
- const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
461
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
462
- });
463
- const width = Math.max(0, ...rows.map((row) => row.width));
464
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
465
- }
466
488
  var OUTPUT_OPTIONS = {
467
489
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
468
490
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
469
491
  };
470
- function applyOutput(color, plain, env = process4.env) {
492
+ function applyOutput(color, plain, env = process6.env) {
471
493
  const when = plain === true ? "never" : color ?? "auto";
472
494
  if (when === "auto")
473
495
  return;
@@ -484,14 +506,13 @@ function applyOutput(color, plain, env = process4.env) {
484
506
  function parse(args, usage, options, settings = {}) {
485
507
  const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
486
508
  const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
509
+ const listing = listed(all, settings.allowNegative === true);
487
510
  if (completion.active)
488
- throw new Completing(all);
489
- const separator = settings.rest === true ? args.indexOf("--") : -1;
490
- const own = separator === -1 ? args : args.slice(0, separator);
491
- const rest = separator === -1 ? undefined : args.slice(separator + 1);
511
+ throw new Completing(listing, settings.positionals, settings.candidates);
512
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
492
513
  let parsed;
493
514
  try {
494
- parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
515
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
495
516
  } catch (error) {
496
517
  const message = parseError(error);
497
518
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -499,12 +520,84 @@ function parse(args, usage, options, settings = {}) {
499
520
  const values = parsed.values;
500
521
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
501
522
  if (values.help === true) {
502
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
523
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
503
524
  throw new HelpShown;
504
525
  }
526
+ checkChoices(parsed.values, all);
527
+ checkConflicts(parsed.values, all);
505
528
  if (settings.positionals !== undefined)
506
529
  checkPositionals(parsed.positionals, settings.positionals);
507
- return { ...parsed, positionals: parsed.positionals, rest };
530
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
531
+ }
532
+ function splitRest(args, passes) {
533
+ const separator = passes ? args.indexOf("--") : -1;
534
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
535
+ }
536
+ function splitTrailing(args, options, count) {
537
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
538
+ let seen = 0;
539
+ if (count === 0)
540
+ return { own: args, rest: undefined };
541
+ for (let at = 0;at < args.length; at++) {
542
+ const word = args[at];
543
+ if (word === "--")
544
+ break;
545
+ if (word.startsWith("-")) {
546
+ if (takesValue(word))
547
+ at++;
548
+ continue;
549
+ }
550
+ seen++;
551
+ if (seen === count)
552
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
553
+ }
554
+ return { own: args, rest: undefined };
555
+ }
556
+ function listed(options, allowNegative) {
557
+ if (!allowNegative)
558
+ return options;
559
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
560
+ if (option.type !== "boolean" || option.negative === undefined)
561
+ return [[name, option]];
562
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
563
+ }));
564
+ }
565
+ function withBare(args, options) {
566
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
567
+ if (bare.size === 0)
568
+ return args;
569
+ const separator = args.indexOf("--");
570
+ const own = separator === -1 ? args : args.slice(0, separator);
571
+ return [...own.flatMap((arg, index) => {
572
+ const optional = bare.get(arg);
573
+ const next = own[index + 1];
574
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
575
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
576
+ }), ...separator === -1 ? [] : args.slice(separator)];
577
+ }
578
+ function checkConflicts(values, options) {
579
+ const given = (name) => values[name] !== undefined && values[name] !== false;
580
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
581
+ const other = given(name) ? conflicts.find(given) : undefined;
582
+ if (other !== undefined)
583
+ badUsage(`--${name} cannot be used with --${other}`);
584
+ }
585
+ }
586
+ function checkChoices(values, options) {
587
+ for (const [name, option] of Object.entries(options)) {
588
+ if (option.choices === undefined)
589
+ continue;
590
+ const given = values[name];
591
+ for (const value of Array.isArray(given) ? given : [given]) {
592
+ if (typeof value === "string")
593
+ oneOf(value, name, option.choices);
594
+ }
595
+ }
596
+ }
597
+ function oneOf(value, name, choices) {
598
+ if (!choices.includes(value))
599
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
600
+ return value;
508
601
  }
509
602
  function checkPositionals(given, names) {
510
603
  const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
@@ -553,31 +646,73 @@ function nearestOption(message, options, allowNegative) {
553
646
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
554
647
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
555
648
  }
556
- async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
557
- if (path === "-") {
558
- if (process4.stdin.isTTY)
559
- fail(noStdin);
560
- return Bun.stdin.text();
561
- }
562
- const file = Bun.file(path);
563
- if (!await file.exists())
564
- fail(`no file ${path}`);
565
- return file.text();
566
- }
567
649
  // ../kit/src/progress.ts
568
650
  var ESC = String.fromCharCode(27);
569
651
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
570
652
  var RESET_STYLE = `${ESC}[0m`;
571
653
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
572
654
  // ../kit/src/cli.ts
573
- import process5 from "process";
655
+ import process8 from "process";
656
+
657
+ // ../kit/src/usage.ts
658
+ import { appendFileSync, mkdirSync } from "fs";
659
+ import { homedir } from "os";
660
+ import { dirname, isAbsolute, join } from "path";
661
+ import process7 from "process";
662
+
663
+ // ../kit/src/logs.ts
664
+ var DAY_MS = 24 * 60 * 60 * 1000;
665
+ var CLI_FOLDER = "kaynooo-cli";
666
+
667
+ // ../kit/src/usage.ts
668
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
669
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
670
+ var LONGEST_NAME = 40;
671
+ var usageError;
672
+ function noteUsageError(message) {
673
+ usageError = message;
674
+ }
675
+ function stateHome(env = process7.env) {
676
+ const dir = env.XDG_STATE_HOME;
677
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
678
+ }
679
+ function usagePath(env = process7.env) {
680
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
681
+ }
682
+ function usageRecorded(env = process7.env) {
683
+ const off = env.KAYNOOO_CLI_NO_USAGE;
684
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
685
+ }
686
+ function flagNames(argv) {
687
+ const end = argv.indexOf("--");
688
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
689
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
690
+ }
691
+ function usageEntry(bin, command, argv, code, now = new Date) {
692
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
693
+ usageError = undefined;
694
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
695
+ }
696
+ function recordUsage(entry, env = process7.env) {
697
+ if (!usageRecorded(env))
698
+ return;
699
+ try {
700
+ const path = usagePath(env);
701
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
702
+ appendFileSync(path, `${JSON.stringify(entry)}
703
+ `, { mode: 384 });
704
+ } catch {}
705
+ }
706
+
707
+ // ../kit/src/cli.ts
574
708
  var LEVEL_OPTIONS = {
575
709
  ...OUTPUT_OPTIONS,
576
710
  help: { type: "boolean", short: "h", description: "show this help" }
577
711
  };
578
712
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
579
- async function commandRows(commands, colors) {
580
- const width = Math.max(...Object.keys(commands).map((name) => name.length));
713
+ async function commandRows(all, colors) {
714
+ const commands = shown(all);
715
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
581
716
  const groups = new Map([["Commands:", []]]);
582
717
  const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
583
718
  for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
@@ -588,6 +723,9 @@ async function commandRows(commands, colors) {
588
723
  }
589
724
  return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
590
725
  }
726
+ function shown(commands) {
727
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
728
+ }
591
729
  function takeOutputFlags(argv) {
592
730
  let index = 0;
593
731
  for (;index < argv.length; index++) {
@@ -619,7 +757,7 @@ async function expand(scope, words) {
619
757
  }
620
758
  return { ...scope, commands, lazy: [] };
621
759
  }
622
- async function help({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
760
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
623
761
  const colors = paint(stream);
624
762
  const prefix = path.join(" ");
625
763
  const summary = await resolveSummary(lazySummary);
@@ -646,8 +784,8 @@ async function help({ path, header, summary: lazySummary, commands, defaultComma
646
784
  `);
647
785
  }
648
786
  function printError(prefix, message, hint, cause) {
649
- const colors = paint(process5.stderr);
650
- const styled = takesControlCodes(process5.stderr);
787
+ const colors = paint(process8.stderr);
788
+ const styled = takesControlCodes(process8.stderr);
651
789
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
652
790
  const under = (label, text, tint) => text === undefined ? "" : `
653
791
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -666,6 +804,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
666
804
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
667
805
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
668
806
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
807
+ if (error instanceof UsageError)
808
+ noteUsageError(error.message);
669
809
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
670
810
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
671
811
  return error instanceof Exit ? error.code : 1;
@@ -679,12 +819,20 @@ async function dispatch(level, typed, { version, redact }) {
679
819
  return reportThrown(prefix, error);
680
820
  }
681
821
  const [name, ...args] = argv;
822
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
823
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
824
+ try {
825
+ return await fallback.run([]);
826
+ } catch (error) {
827
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
828
+ }
829
+ }
682
830
  if (name === undefined && level.path.length > 1) {
683
- console.error(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stderr));
831
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
684
832
  return 2;
685
833
  }
686
834
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
687
- console.log(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stdout));
835
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
688
836
  return 0;
689
837
  }
690
838
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -693,6 +841,7 @@ async function dispatch(level, typed, { version, redact }) {
693
841
  }
694
842
  let command = level.commands[level.aliases?.[name] ?? name];
695
843
  let rest = args;
844
+ let ran = name;
696
845
  if (command === undefined && level.lazy.length > 0) {
697
846
  level = await expand(level, [...level.path.slice(1), ...argv]);
698
847
  command = level.commands[level.aliases?.[name] ?? name];
@@ -700,40 +849,77 @@ async function dispatch(level, typed, { version, redact }) {
700
849
  if (command === undefined && level.defaultCommand !== undefined) {
701
850
  command = level.commands[level.defaultCommand];
702
851
  rest = argv;
852
+ ran = level.defaultCommand;
703
853
  }
704
854
  if (command === undefined) {
705
- const meant = closest(name, Object.keys(level.commands));
855
+ const meant = closest(name, Object.keys(shown(level.commands)));
706
856
  printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
707
857
  return 2;
708
858
  }
709
859
  if ("commands" in command) {
710
860
  const { summary } = command;
711
- return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, examples: command.examples, replaces: undefined }, rest, { version, redact });
861
+ return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
712
862
  }
713
863
  try {
714
864
  return await command.run(rest);
715
865
  } catch (error) {
716
- return reportThrown(`${prefix} ${name}`, error, redact, wantsJson(rest));
866
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
717
867
  }
718
868
  }
719
869
  var COMPLETE = "__complete";
720
870
  var FILES = "__files__";
721
- async function optionsOf(run) {
871
+ async function completingOf(run) {
722
872
  completion.active = true;
723
873
  try {
724
874
  await run([]);
725
875
  } catch (error) {
726
876
  if (error instanceof Completing)
727
- return error.options;
877
+ return error;
728
878
  } finally {
729
879
  completion.active = false;
730
880
  }
731
- return {};
881
+ return new Completing({});
882
+ }
883
+ async function optionsOf(run) {
884
+ return (await completingOf(run)).options;
885
+ }
886
+ function candidateLine(candidate) {
887
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
888
+ }
889
+ function positionalBeingTyped(before, { options, positionals }) {
890
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
891
+ let index = 0;
892
+ let at = 0;
893
+ while (at < before.length) {
894
+ const word = before[at];
895
+ if (word === "--") {
896
+ index += before.length - at - 1;
897
+ break;
898
+ }
899
+ if (!word.startsWith("-"))
900
+ index++;
901
+ else if (takesValue(word))
902
+ at++;
903
+ at++;
904
+ }
905
+ const last = positionals.at(-1);
906
+ if (index < positionals.length)
907
+ return positionals[index];
908
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
732
909
  }
733
910
  async function leafCandidates(run, words) {
734
- if (!(words.at(-1) ?? "").startsWith("-"))
735
- return [FILES];
736
- return Object.entries(await optionsOf(run)).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
911
+ const completing = await completingOf(run);
912
+ if ((words.at(-1) ?? "").startsWith("-"))
913
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
914
+ const flag = words.at(-2);
915
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
916
+ if (option?.type === "string") {
917
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
918
+ return values === undefined ? [FILES] : values.map(candidateLine);
919
+ }
920
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
921
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
922
+ return values === undefined ? [FILES] : values.map(candidateLine);
737
923
  }
738
924
  async function candidates(scope, defaultCommand, words, before = []) {
739
925
  const [word = "", ...rest] = words;
@@ -744,8 +930,13 @@ async function candidates(scope, defaultCommand, words, before = []) {
744
930
  ({ commands, aliases } = await expand(scope, [...before, ...words]));
745
931
  command = commands[aliases?.[word] ?? word];
746
932
  }
747
- if (listing)
748
- return Promise.all(Object.entries(commands).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
933
+ if (listing) {
934
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
935
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
936
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
937
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
938
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
939
+ }
749
940
  if (command === undefined) {
750
941
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
751
942
  return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
@@ -757,26 +948,49 @@ async function printCandidates(found) {
757
948
  console.log(line);
758
949
  return 0;
759
950
  }
760
- async function runCli(cli, argv = process5.argv.slice(2)) {
951
+ async function runCli(cli, argv = process8.argv.slice(2)) {
761
952
  if (argv[0] === COMPLETE)
762
953
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
763
- return dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, examples: cli.examples, replaces: cli.replaces }, argv, { version: cli.version, redact: cli.redact });
954
+ const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version: cli.version, redact: cli.redact });
955
+ if (cli.usage !== false) {
956
+ try {
957
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
958
+ } catch {}
959
+ }
960
+ return code;
961
+ }
962
+ function commandPath(scope, argv) {
963
+ const path = [];
964
+ let level = scope;
965
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
966
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
967
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
968
+ if (command === undefined)
969
+ break;
970
+ path.push(word);
971
+ if (!("commands" in command))
972
+ break;
973
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
974
+ }
975
+ return path.length === 0 ? undefined : path.join(" ");
764
976
  }
765
- async function runMain({ name, version, run, redact }, argv = process5.argv.slice(2)) {
977
+ async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
766
978
  if (argv[0] === COMPLETE)
767
979
  return printCandidates(leafCandidates(run, argv.slice(1)));
768
980
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
769
981
  console.log(version);
770
982
  return 0;
771
983
  }
984
+ let code;
772
985
  try {
773
- return await run(argv);
986
+ code = await run(argv);
774
987
  } catch (error) {
775
- return reportThrown(name, error, redact, wantsJson(argv));
988
+ code = reportThrown(name, error, redact, wantsJson(argv));
776
989
  }
990
+ if (usage !== false)
991
+ recordUsage(usageEntry(name, undefined, argv, code));
992
+ return code;
777
993
  }
778
- // ../kit/src/logs.ts
779
- var DAY_MS = 24 * 60 * 60 * 1000;
780
994
  // ../kit/src/secrets.ts
781
995
  var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
782
996
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
@@ -789,11 +1003,11 @@ var {Glob } = globalThis.Bun;
789
1003
  var SESSION_FILES = new Glob("*.json");
790
1004
  var ACCOUNT_DIRS = new Glob("*/sessions");
791
1005
  // package.json
792
- var version = "0.8.0";
1006
+ var version = "0.8.1";
793
1007
 
794
1008
  // src/files.ts
795
1009
  import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
796
- import { basename, dirname, join } from "path";
1010
+ import { basename, dirname as dirname2, join as join2 } from "path";
797
1011
 
798
1012
  // src/dotenv.ts
799
1013
  var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
@@ -1099,7 +1313,7 @@ async function envFiles(folder = process.cwd()) {
1099
1313
  const found = await readdir(folder, { withFileTypes: true });
1100
1314
  const names = [];
1101
1315
  for (const entry of found) {
1102
- if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join(folder, entry.name)))
1316
+ if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join2(folder, entry.name)))
1103
1317
  names.push(entry.name);
1104
1318
  }
1105
1319
  return names.sort();
@@ -1123,7 +1337,7 @@ async function writeAtomic(path, text) {
1123
1337
  if (error.code !== "ENOENT")
1124
1338
  throw error;
1125
1339
  }
1126
- const temp = join(dirname(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1340
+ const temp = join2(dirname2(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1127
1341
  try {
1128
1342
  await writeFile(temp, text, { mode: 384, flag: "wx" });
1129
1343
  if (owner !== undefined)
@@ -1161,7 +1375,7 @@ async function acquire(path) {
1161
1375
  try {
1162
1376
  real = await realpath(path);
1163
1377
  } catch {}
1164
- const lock = join(dirname(real), `.${basename(real)}.lock`);
1378
+ const lock = join2(dirname2(real), `.${basename(real)}.lock`);
1165
1379
  const deadline = Date.now() + LOCK_WAIT_MS;
1166
1380
  while (true) {
1167
1381
  try {
@@ -1199,7 +1413,7 @@ async function envFilesBelow(folder, depth = 0) {
1199
1413
  return found;
1200
1414
  }
1201
1415
  for (const entry of children) {
1202
- const path = join(folder, entry.name);
1416
+ const path = join2(folder, entry.name);
1203
1417
  if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
1204
1418
  found.push(...await envFilesBelow(path, depth + 1));
1205
1419
  else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
@@ -1333,7 +1547,7 @@ function check(text, known) {
1333
1547
  }
1334
1548
 
1335
1549
  // src/redact.ts
1336
- var usage = `redact [--check]
1550
+ var usage2 = `redact [--check]
1337
1551
 
1338
1552
  Copies stdin to stdout line by line with secrets masked: known token formats (GitHub, GitLab, Slack, AWS, npm, Stripe, Google and SendGrid keys, sk-, JWTs, Authorization headers, password= and secret= pairs), private key blocks, the password and the tokens of any URL and the values of secret-looking keys in this folder's .env* files.
1339
1553
  --check prints nothing of the input and lists the file and line of each secret found, exiting 1 when there is any: \`git diff --cached | redact --check\`.
@@ -1344,7 +1558,7 @@ var options = {
1344
1558
  "no-env": { type: "boolean", description: "do not search for the values of the .env* files" }
1345
1559
  };
1346
1560
  async function run(args) {
1347
- const parsed = parse(args, usage, options, { replaces: "printing a command's secrets into a log or a transcript", examples: [["docker compose config | redact", "the resolved compose file, secrets masked"], ["git diff --cached | redact --check", "refuse a commit carrying a secret"]] });
1561
+ const parsed = parse(args, usage2, options, { replaces: "printing a command's secrets into a log or a transcript", examples: [["docker compose config | redact", "the resolved compose file, secrets masked"], ["git diff --cached | redact --check", "refuse a commit carrying a secret"]] });
1348
1562
  const known = parsed.values["no-env"] === true ? undefined : await loadKnown();
1349
1563
  if (parsed.values.check === true) {
1350
1564
  const findings = check(await readInput("-"), known);
@@ -1355,8 +1569,8 @@ async function run(args) {
1355
1569
  const redactor = new Redactor(known);
1356
1570
  const decoder = new TextDecoder;
1357
1571
  for await (const chunk of Bun.stdin.stream())
1358
- process7.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1359
- process7.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1572
+ process10.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1573
+ process10.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1360
1574
  return 0;
1361
1575
  }
1362
- process7.exitCode = await runMain({ name: "redact", version, run });
1576
+ process10.exitCode = await runMain({ name: "redact", version, run });