@kaynooo/cli-env 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/redact.js CHANGED
@@ -2,10 +2,9 @@
2
2
  // @bun
3
3
 
4
4
  // src/redact.ts
5
- import process7 from "process";
6
-
5
+ import process10 from "process";
7
6
  // ../kit/src/args.ts
8
- import process4 from "process";
7
+ import process6 from "process";
9
8
  import { parseArgs } from "util";
10
9
 
11
10
  // ../kit/src/format.ts
@@ -14,7 +13,7 @@ import process3 from "process";
14
13
  // ../kit/src/style.ts
15
14
  import process2 from "process";
16
15
 
17
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
16
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
17
  function x(s) {
19
18
  let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
20
19
  if (!/^[a-f0-9]+$/.test(r))
@@ -234,7 +233,7 @@ class e {
234
233
  }
235
234
  }
236
235
 
237
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
236
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
238
237
  var r = 39;
239
238
  var o = 49;
240
239
  var f2 = "\x1B[";
@@ -358,6 +357,63 @@ function printJson(value) {
358
357
  console.log(JSON.stringify(value, undefined, 2));
359
358
  }
360
359
 
360
+ // ../kit/src/help.ts
361
+ import process4 from "process";
362
+ var OPTIONAL = /\[[^\]]+\]/g;
363
+ var USAGE_PREFIX = /^usage:\s*/i;
364
+ var FULL_STOP = /\.$/;
365
+ function usageLine(usage, colors = paint(process4.stdout)) {
366
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
367
+ }
368
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
369
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
370
+ `);
371
+ }
372
+ function exitRows(exits, colors = paint(process4.stdout)) {
373
+ if (exits.length === 0)
374
+ return [];
375
+ const width = Math.max(...exits.map(([code]) => String(code).length));
376
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
377
+ }
378
+ function replacesRows(replaces, colors = paint(process4.stdout)) {
379
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
380
+ }
381
+ function wantsHelpJson(env = process4.env) {
382
+ return env.KIT_HELP === "json";
383
+ }
384
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
385
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
386
+ `);
387
+ const first = lines[0];
388
+ const colon = first.indexOf(": ");
389
+ const prose = lines[lines.indexOf("") + 1] ?? "";
390
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
391
+ return {
392
+ synopsis: colon === -1 ? first : first.slice(0, colon),
393
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
394
+ ...replaces === undefined ? {} : { replaces },
395
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
396
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
397
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
398
+ };
399
+ }
400
+ function exampleRows(examples, colors = paint(process4.stdout)) {
401
+ if (examples.length === 0)
402
+ return [];
403
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
404
+ }
405
+ function optionRows(options, colors = paint(process4.stdout)) {
406
+ const rows = Object.entries(options).map(([name, option]) => {
407
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
408
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
409
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
410
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
411
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
412
+ });
413
+ const width = Math.max(0, ...rows.map((row) => row.width));
414
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
415
+ }
416
+
361
417
  // ../kit/src/text.ts
362
418
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
363
419
  function distance(a, b) {
@@ -377,8 +433,22 @@ function closest(name, names) {
377
433
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
378
434
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
379
435
  }
436
+ // ../kit/src/input.ts
437
+ import process5 from "process";
438
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
439
+ if (path === "-") {
440
+ if (process5.stdin.isTTY)
441
+ fail(noStdin);
442
+ return Bun.stdin.text();
443
+ }
444
+ const file = Bun.file(path);
445
+ if (!await file.exists())
446
+ fail(`no file ${path}`);
447
+ return file.text();
448
+ }
380
449
 
381
450
  // ../kit/src/args.ts
451
+ var DASHES = /^-+/;
382
452
  function jsonOption(holds) {
383
453
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
384
454
  }
@@ -413,61 +483,20 @@ class HelpShown extends Exit {
413
483
 
414
484
  class Completing {
415
485
  options;
416
- constructor(options) {
486
+ positionals;
487
+ candidates;
488
+ constructor(options, positionals = [], candidates = {}) {
417
489
  this.options = options;
490
+ this.positionals = positionals;
491
+ this.candidates = candidates;
418
492
  }
419
493
  }
420
494
  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
495
  var OUTPUT_OPTIONS = {
467
496
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
468
497
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
469
498
  };
470
- function applyOutput(color, plain, env = process4.env) {
499
+ function applyOutput(color, plain, env = process6.env) {
471
500
  const when = plain === true ? "never" : color ?? "auto";
472
501
  if (when === "auto")
473
502
  return;
@@ -484,14 +513,13 @@ function applyOutput(color, plain, env = process4.env) {
484
513
  function parse(args, usage, options, settings = {}) {
485
514
  const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
486
515
  const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
516
+ const listing = listed(all, settings.allowNegative === true);
487
517
  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);
518
+ throw new Completing(listing, settings.positionals, settings.candidates);
519
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
492
520
  let parsed;
493
521
  try {
494
- parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
522
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
495
523
  } catch (error) {
496
524
  const message = parseError(error);
497
525
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -499,12 +527,96 @@ function parse(args, usage, options, settings = {}) {
499
527
  const values = parsed.values;
500
528
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
501
529
  if (values.help === true) {
502
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
530
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
503
531
  throw new HelpShown;
504
532
  }
533
+ checkChoices(parsed.values, all);
534
+ checkConflicts(parsed.values, all);
505
535
  if (settings.positionals !== undefined)
506
536
  checkPositionals(parsed.positionals, settings.positionals);
507
- return { ...parsed, positionals: parsed.positionals, rest };
537
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
538
+ }
539
+ function splitRest(args, passes) {
540
+ const separator = passes ? args.indexOf("--") : -1;
541
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
542
+ }
543
+ function splitTrailing(args, options, count) {
544
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
545
+ let seen = 0;
546
+ if (count === 0)
547
+ return { own: args, rest: undefined };
548
+ for (let at = 0;at < args.length; at++) {
549
+ const word = args[at];
550
+ if (word === "--")
551
+ break;
552
+ if (word.startsWith("-")) {
553
+ if (takesValue(word))
554
+ at++;
555
+ continue;
556
+ }
557
+ seen++;
558
+ if (seen === count)
559
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
560
+ }
561
+ return { own: args, rest: undefined };
562
+ }
563
+ function listed(options, allowNegative) {
564
+ if (!allowNegative)
565
+ return options;
566
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
567
+ if (option.type !== "boolean" || option.negative === undefined)
568
+ return [[name, option]];
569
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
570
+ }));
571
+ }
572
+ function withAliases(args, options) {
573
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
574
+ if (named.size === 0)
575
+ return args;
576
+ const separator = args.indexOf("--");
577
+ const own = separator === -1 ? args : args.slice(0, separator);
578
+ return [...own.map((arg) => {
579
+ const at = arg.indexOf("=");
580
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
581
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
582
+ }), ...separator === -1 ? [] : args.slice(separator)];
583
+ }
584
+ function withBare(args, options) {
585
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
586
+ if (bare.size === 0)
587
+ return args;
588
+ const separator = args.indexOf("--");
589
+ const own = separator === -1 ? args : args.slice(0, separator);
590
+ return [...own.flatMap((arg, index) => {
591
+ const optional = bare.get(arg);
592
+ const next = own[index + 1];
593
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
594
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
595
+ }), ...separator === -1 ? [] : args.slice(separator)];
596
+ }
597
+ function checkConflicts(values, options) {
598
+ const given = (name) => values[name] !== undefined && values[name] !== false;
599
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
600
+ const other = given(name) ? conflicts.find(given) : undefined;
601
+ if (other !== undefined)
602
+ badUsage(`--${name} cannot be used with --${other}`);
603
+ }
604
+ }
605
+ function checkChoices(values, options) {
606
+ for (const [name, option] of Object.entries(options)) {
607
+ if (option.choices === undefined)
608
+ continue;
609
+ const given = values[name];
610
+ for (const value of Array.isArray(given) ? given : [given]) {
611
+ if (typeof value === "string")
612
+ oneOf(value, name, option.choices);
613
+ }
614
+ }
615
+ }
616
+ function oneOf(value, name, choices) {
617
+ if (!choices.includes(value))
618
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
619
+ return value;
508
620
  }
509
621
  function checkPositionals(given, names) {
510
622
  const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
@@ -553,31 +665,75 @@ function nearestOption(message, options, allowNegative) {
553
665
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
554
666
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
555
667
  }
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
668
  // ../kit/src/progress.ts
568
669
  var ESC = String.fromCharCode(27);
569
670
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
570
671
  var RESET_STYLE = `${ESC}[0m`;
571
672
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
572
673
  // ../kit/src/cli.ts
573
- import process5 from "process";
674
+ import { readFileSync, realpathSync } from "fs";
675
+ import { dirname as dirname2, join as join2 } from "path";
676
+ import process8 from "process";
677
+
678
+ // ../kit/src/usage.ts
679
+ import { appendFileSync, mkdirSync } from "fs";
680
+ import { homedir } from "os";
681
+ import { dirname, isAbsolute, join } from "path";
682
+ import process7 from "process";
683
+
684
+ // ../kit/src/logs.ts
685
+ var DAY_MS = 24 * 60 * 60 * 1000;
686
+ var CLI_FOLDER = "kaynooo-cli";
687
+
688
+ // ../kit/src/usage.ts
689
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
690
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
691
+ var LONGEST_NAME = 40;
692
+ var usageError;
693
+ function noteUsageError(message) {
694
+ usageError = message;
695
+ }
696
+ function stateHome(env = process7.env) {
697
+ const dir = env.XDG_STATE_HOME;
698
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
699
+ }
700
+ function usagePath(env = process7.env) {
701
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
702
+ }
703
+ function usageRecorded(env = process7.env) {
704
+ const off = env.KAYNOOO_CLI_NO_USAGE;
705
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
706
+ }
707
+ function flagNames(argv) {
708
+ const end = argv.indexOf("--");
709
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
710
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
711
+ }
712
+ function usageEntry(bin, command, argv, code, now = new Date) {
713
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
714
+ usageError = undefined;
715
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
716
+ }
717
+ function recordUsage(entry, env = process7.env) {
718
+ if (!usageRecorded(env))
719
+ return;
720
+ try {
721
+ const path = usagePath(env);
722
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
723
+ appendFileSync(path, `${JSON.stringify(entry)}
724
+ `, { mode: 384 });
725
+ } catch {}
726
+ }
727
+
728
+ // ../kit/src/cli.ts
574
729
  var LEVEL_OPTIONS = {
575
730
  ...OUTPUT_OPTIONS,
576
731
  help: { type: "boolean", short: "h", description: "show this help" }
577
732
  };
578
733
  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));
734
+ async function commandRows(all, colors) {
735
+ const commands = shown(all);
736
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
581
737
  const groups = new Map([["Commands:", []]]);
582
738
  const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
583
739
  for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
@@ -588,6 +744,9 @@ async function commandRows(commands, colors) {
588
744
  }
589
745
  return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
590
746
  }
747
+ function shown(commands) {
748
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
749
+ }
591
750
  function takeOutputFlags(argv) {
592
751
  let index = 0;
593
752
  for (;index < argv.length; index++) {
@@ -619,7 +778,7 @@ async function expand(scope, words) {
619
778
  }
620
779
  return { ...scope, commands, lazy: [] };
621
780
  }
622
- async function help({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
781
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
623
782
  const colors = paint(stream);
624
783
  const prefix = path.join(" ");
625
784
  const summary = await resolveSummary(lazySummary);
@@ -646,8 +805,8 @@ async function help({ path, header, summary: lazySummary, commands, defaultComma
646
805
  `);
647
806
  }
648
807
  function printError(prefix, message, hint, cause) {
649
- const colors = paint(process5.stderr);
650
- const styled = takesControlCodes(process5.stderr);
808
+ const colors = paint(process8.stderr);
809
+ const styled = takesControlCodes(process8.stderr);
651
810
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
652
811
  const under = (label, text, tint) => text === undefined ? "" : `
653
812
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -666,6 +825,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
666
825
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
667
826
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
668
827
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
828
+ if (error instanceof UsageError)
829
+ noteUsageError(error.message);
669
830
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
670
831
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
671
832
  return error instanceof Exit ? error.code : 1;
@@ -679,12 +840,20 @@ async function dispatch(level, typed, { version, redact }) {
679
840
  return reportThrown(prefix, error);
680
841
  }
681
842
  const [name, ...args] = argv;
843
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
844
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
845
+ try {
846
+ return await fallback.run([]);
847
+ } catch (error) {
848
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
849
+ }
850
+ }
682
851
  if (name === undefined && level.path.length > 1) {
683
- console.error(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stderr));
852
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
684
853
  return 2;
685
854
  }
686
855
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
687
- console.log(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stdout));
856
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
688
857
  return 0;
689
858
  }
690
859
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -693,6 +862,7 @@ async function dispatch(level, typed, { version, redact }) {
693
862
  }
694
863
  let command = level.commands[level.aliases?.[name] ?? name];
695
864
  let rest = args;
865
+ let ran = name;
696
866
  if (command === undefined && level.lazy.length > 0) {
697
867
  level = await expand(level, [...level.path.slice(1), ...argv]);
698
868
  command = level.commands[level.aliases?.[name] ?? name];
@@ -700,40 +870,77 @@ async function dispatch(level, typed, { version, redact }) {
700
870
  if (command === undefined && level.defaultCommand !== undefined) {
701
871
  command = level.commands[level.defaultCommand];
702
872
  rest = argv;
873
+ ran = level.defaultCommand;
703
874
  }
704
875
  if (command === undefined) {
705
- const meant = closest(name, Object.keys(level.commands));
876
+ const meant = closest(name, Object.keys(shown(level.commands)));
706
877
  printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
707
878
  return 2;
708
879
  }
709
880
  if ("commands" in command) {
710
881
  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 });
882
+ 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
883
  }
713
884
  try {
714
885
  return await command.run(rest);
715
886
  } catch (error) {
716
- return reportThrown(`${prefix} ${name}`, error, redact, wantsJson(rest));
887
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
717
888
  }
718
889
  }
719
890
  var COMPLETE = "__complete";
720
891
  var FILES = "__files__";
721
- async function optionsOf(run) {
892
+ async function completingOf(run) {
722
893
  completion.active = true;
723
894
  try {
724
895
  await run([]);
725
896
  } catch (error) {
726
897
  if (error instanceof Completing)
727
- return error.options;
898
+ return error;
728
899
  } finally {
729
900
  completion.active = false;
730
901
  }
731
- return {};
902
+ return new Completing({});
903
+ }
904
+ async function optionsOf(run) {
905
+ return (await completingOf(run)).options;
906
+ }
907
+ function candidateLine(candidate) {
908
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
909
+ }
910
+ function positionalBeingTyped(before, { options, positionals }) {
911
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
912
+ let index = 0;
913
+ let at = 0;
914
+ while (at < before.length) {
915
+ const word = before[at];
916
+ if (word === "--") {
917
+ index += before.length - at - 1;
918
+ break;
919
+ }
920
+ if (!word.startsWith("-"))
921
+ index++;
922
+ else if (takesValue(word))
923
+ at++;
924
+ at++;
925
+ }
926
+ const last = positionals.at(-1);
927
+ if (index < positionals.length)
928
+ return positionals[index];
929
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
732
930
  }
733
931
  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}`);
932
+ const completing = await completingOf(run);
933
+ if ((words.at(-1) ?? "").startsWith("-"))
934
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
935
+ const flag = words.at(-2);
936
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
937
+ if (option?.type === "string") {
938
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
939
+ return values === undefined ? [FILES] : values.map(candidateLine);
940
+ }
941
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
942
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
943
+ return values === undefined ? [FILES] : values.map(candidateLine);
737
944
  }
738
945
  async function candidates(scope, defaultCommand, words, before = []) {
739
946
  const [word = "", ...rest] = words;
@@ -744,8 +951,13 @@ async function candidates(scope, defaultCommand, words, before = []) {
744
951
  ({ commands, aliases } = await expand(scope, [...before, ...words]));
745
952
  command = commands[aliases?.[word] ?? word];
746
953
  }
747
- if (listing)
748
- return Promise.all(Object.entries(commands).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
954
+ if (listing) {
955
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
956
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
957
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
958
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
959
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
960
+ }
749
961
  if (command === undefined) {
750
962
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
751
963
  return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
@@ -757,26 +969,73 @@ async function printCandidates(found) {
757
969
  console.log(line);
758
970
  return 0;
759
971
  }
760
- async function runCli(cli, argv = process5.argv.slice(2)) {
972
+ function packageVersion(entry = Bun.main) {
973
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
974
+ try {
975
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
976
+ if (typeof version === "string")
977
+ return version;
978
+ } catch {}
979
+ if (dirname2(dir) === dir)
980
+ return "0.0.0";
981
+ }
982
+ }
983
+ async function runCli(cli, argv = process8.argv.slice(2)) {
984
+ const version = cli.version ?? packageVersion();
761
985
  if (argv[0] === COMPLETE)
762
986
  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 });
987
+ const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(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, redact: cli.redact });
988
+ if (cli.usage !== false) {
989
+ try {
990
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
991
+ } catch {}
992
+ }
993
+ return code;
764
994
  }
765
- async function runMain({ name, version, run, redact }, argv = process5.argv.slice(2)) {
995
+ function commandPath(scope, argv) {
996
+ const path = [];
997
+ let level = scope;
998
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
999
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1000
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1001
+ if (command === undefined)
1002
+ break;
1003
+ path.push(word);
1004
+ if (!("commands" in command))
1005
+ break;
1006
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
1007
+ }
1008
+ return path.length === 0 ? undefined : path.join(" ");
1009
+ }
1010
+ async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
766
1011
  if (argv[0] === COMPLETE)
767
1012
  return printCandidates(leafCandidates(run, argv.slice(1)));
768
1013
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
769
- console.log(version);
1014
+ console.log(version ?? packageVersion());
770
1015
  return 0;
771
1016
  }
1017
+ let code;
772
1018
  try {
773
- return await run(argv);
1019
+ code = await run(argv);
774
1020
  } catch (error) {
775
- return reportThrown(name, error, redact, wantsJson(argv));
1021
+ code = reportThrown(name, error, redact, wantsJson(argv));
1022
+ }
1023
+ if (usage !== false) {
1024
+ try {
1025
+ recordUsage(usageEntry(name, undefined, argv, code));
1026
+ } catch {}
776
1027
  }
1028
+ return code;
1029
+ }
1030
+ // ../kit/src/compose.ts
1031
+ async function captureOutput(argv, { cwd, env } = {}) {
1032
+ const run = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, env: { ...process.env, ...env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
1033
+ const [stdout, stderr, code] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]);
1034
+ return { code, stdout, stderr };
1035
+ }
1036
+ async function compose(args, { flags = [], ...options } = {}) {
1037
+ return captureOutput(["docker", "compose", ...flags, ...args], options);
777
1038
  }
778
- // ../kit/src/logs.ts
779
- var DAY_MS = 24 * 60 * 60 * 1000;
780
1039
  // ../kit/src/secrets.ts
781
1040
  var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
782
1041
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
@@ -788,12 +1047,9 @@ function isSecretName(name) {
788
1047
  var {Glob } = globalThis.Bun;
789
1048
  var SESSION_FILES = new Glob("*.json");
790
1049
  var ACCOUNT_DIRS = new Glob("*/sessions");
791
- // package.json
792
- var version = "0.8.0";
793
-
794
1050
  // src/files.ts
795
1051
  import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
796
- import { basename, dirname, join } from "path";
1052
+ import { basename, dirname as dirname3, join as join3 } from "path";
797
1053
 
798
1054
  // src/dotenv.ts
799
1055
  var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
@@ -876,14 +1132,16 @@ function entries(file) {
876
1132
  }
877
1133
  return map;
878
1134
  }
1135
+ function escapeDouble(value) {
1136
+ return value.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("\r", "\\r").replaceAll(`
1137
+ `, "\\n").replaceAll("$", "\\$");
1138
+ }
879
1139
  function formatAssignment(key, value) {
880
1140
  if (value === "" || !NEEDS_QUOTES.test(value))
881
1141
  return `${key}=${value}`;
882
1142
  if (RAW_ONLY.test(value) && !value.includes("'") && !LINE_BREAK.test(value))
883
1143
  return `${key}='${value.replaceAll("$", "\\$")}'`;
884
- const escaped = value.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("\r", "\\r").replaceAll(`
885
- `, "\\n").replaceAll("$", "\\$");
886
- return `${key}="${escaped}"`;
1144
+ return `${key}="${escapeDouble(value)}"`;
887
1145
  }
888
1146
  function setLine(file, key, value, raw) {
889
1147
  const index = file.lines.findLastIndex((line) => line.key === key);
@@ -952,6 +1210,9 @@ var WEBHOOK_FORMATS = [
952
1210
  ["healthchecks.io ping URL", /^hc-ping\.com\/([\w-]+)/di]
953
1211
  ];
954
1212
  var OPAQUE_SEGMENT = /^(?:(?=[\w-]{20,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\w-]+|(?=[A-Za-z\d]{32,}$)(?=.*[A-Za-z])(?=.*\d).+)$/;
1213
+ function isSecretKey(key) {
1214
+ return isSecretName(key);
1215
+ }
955
1216
  function hint(value) {
956
1217
  const shown = Math.min(3, Math.floor(value.length / 4));
957
1218
  return `${value.slice(0, shown)}***(${value.length})`;
@@ -1084,6 +1345,7 @@ var KNOWN_DEPTH = 3;
1084
1345
  var SKIPPED = new Set(["node_modules", ".git", "vendor"]);
1085
1346
  var LOCK_WAIT_MS = 5000;
1086
1347
  var LOCK_STALE_MS = 30000;
1348
+ var REAP_STALE_MS = 5000;
1087
1349
  async function isFileEntry(entry, path) {
1088
1350
  if (entry.isFile())
1089
1351
  return true;
@@ -1099,7 +1361,7 @@ async function envFiles(folder = process.cwd()) {
1099
1361
  const found = await readdir(folder, { withFileTypes: true });
1100
1362
  const names = [];
1101
1363
  for (const entry of found) {
1102
- if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join(folder, entry.name)))
1364
+ if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join3(folder, entry.name)))
1103
1365
  names.push(entry.name);
1104
1366
  }
1105
1367
  return names.sort();
@@ -1123,7 +1385,7 @@ async function writeAtomic(path, text) {
1123
1385
  if (error.code !== "ENOENT")
1124
1386
  throw error;
1125
1387
  }
1126
- const temp = join(dirname(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1388
+ const temp = join3(dirname3(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1127
1389
  try {
1128
1390
  await writeFile(temp, text, { mode: 384, flag: "wx" });
1129
1391
  if (owner !== undefined)
@@ -1156,12 +1418,30 @@ async function withLocks(paths, fn) {
1156
1418
  await rm(lock, { force: true });
1157
1419
  }
1158
1420
  }
1421
+ async function reap(lock) {
1422
+ const guard = `${lock}.reap`;
1423
+ try {
1424
+ await writeFile(guard, String(process.pid), { flag: "wx", mode: 384 });
1425
+ } catch {
1426
+ try {
1427
+ if (Date.now() - (await stat(guard)).mtimeMs > REAP_STALE_MS)
1428
+ await rm(guard, { force: true });
1429
+ } catch {}
1430
+ return;
1431
+ }
1432
+ try {
1433
+ if (Date.now() - (await stat(lock)).mtimeMs > LOCK_STALE_MS)
1434
+ await rm(lock, { force: true });
1435
+ } catch {} finally {
1436
+ await rm(guard, { force: true });
1437
+ }
1438
+ }
1159
1439
  async function acquire(path) {
1160
1440
  let real = path;
1161
1441
  try {
1162
1442
  real = await realpath(path);
1163
1443
  } catch {}
1164
- const lock = join(dirname(real), `.${basename(real)}.lock`);
1444
+ const lock = join3(dirname3(real), `.${basename(real)}.lock`);
1165
1445
  const deadline = Date.now() + LOCK_WAIT_MS;
1166
1446
  while (true) {
1167
1447
  try {
@@ -1171,10 +1451,7 @@ async function acquire(path) {
1171
1451
  if (error.code !== "EEXIST")
1172
1452
  throw error;
1173
1453
  }
1174
- try {
1175
- if (Date.now() - (await stat(lock)).mtimeMs > LOCK_STALE_MS)
1176
- await rm(lock, { force: true });
1177
- } catch {}
1454
+ await reap(lock);
1178
1455
  if (Date.now() > deadline)
1179
1456
  fail(`${path} is locked by another ev run (${lock})`, 1);
1180
1457
  await Bun.sleep(25);
@@ -1199,7 +1476,7 @@ async function envFilesBelow(folder, depth = 0) {
1199
1476
  return found;
1200
1477
  }
1201
1478
  for (const entry of children) {
1202
- const path = join(folder, entry.name);
1479
+ const path = join3(folder, entry.name);
1203
1480
  if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
1204
1481
  found.push(...await envFilesBelow(path, depth + 1));
1205
1482
  else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
@@ -1333,7 +1610,7 @@ function check(text, known) {
1333
1610
  }
1334
1611
 
1335
1612
  // src/redact.ts
1336
- var usage = `redact [--check]
1613
+ var usage2 = `redact [--check]
1337
1614
 
1338
1615
  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
1616
  --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 +1621,7 @@ var options = {
1344
1621
  "no-env": { type: "boolean", description: "do not search for the values of the .env* files" }
1345
1622
  };
1346
1623
  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"]] });
1624
+ 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
1625
  const known = parsed.values["no-env"] === true ? undefined : await loadKnown();
1349
1626
  if (parsed.values.check === true) {
1350
1627
  const findings = check(await readInput("-"), known);
@@ -1355,8 +1632,8 @@ async function run(args) {
1355
1632
  const redactor = new Redactor(known);
1356
1633
  const decoder = new TextDecoder;
1357
1634
  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());
1635
+ process10.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1636
+ process10.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1360
1637
  return 0;
1361
1638
  }
1362
- process7.exitCode = await runMain({ name: "redact", version, run });
1639
+ process10.exitCode = await runMain({ name: "redact", run });