@kaynooo/cli-env 0.13.1 → 0.14.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.
package/dist/redact.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/redact.ts
5
- import process15 from "process";
5
+ import process18 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process10 from "process";
8
8
  import { parseArgs } from "util";
@@ -45,6 +45,9 @@ function outputMode(stream = process2.stdout, env = process2.env) {
45
45
  return "terminal";
46
46
  return isSet(env.CI) ? "ci" : "pipe";
47
47
  }
48
+ function isInteractive(streams = process2) {
49
+ return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
50
+ }
48
51
 
49
52
  // ../kit/src/style.ts
50
53
  import process6 from "process";
@@ -374,6 +377,23 @@ var STATUS_WORDS = {
374
377
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
375
378
 
376
379
  // ../kit/src/format.ts
380
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
381
+ function formatSeconds(total) {
382
+ let rest = Math.max(0, Math.round(total));
383
+ const amounts = UNITS.map(([unit, size]) => {
384
+ const amount = Math.floor(rest / size);
385
+ rest -= amount * size;
386
+ return `${amount}${unit}`;
387
+ });
388
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
389
+ if (first === -1)
390
+ return "0s";
391
+ const next = amounts[first + 1];
392
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
393
+ }
394
+ function formatDuration(ms) {
395
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
396
+ }
377
397
  function upTo(text, separator) {
378
398
  const end = text.indexOf(separator);
379
399
  return end === -1 ? text : text.slice(0, end);
@@ -434,24 +454,20 @@ function printJson(value) {
434
454
 
435
455
  // ../kit/src/help.ts
436
456
  import process8 from "process";
437
- var OPTIONAL = /\[[^\]]+\]/g;
457
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
438
458
  var USAGE_PREFIX = /^usage:\s*/i;
439
459
  var FULL_STOP = /\.$/;
440
460
  function usageLine(usage, colors = paint(process8.stdout)) {
441
461
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
442
462
  }
443
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
444
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
463
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
464
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
445
465
  `);
446
466
  }
447
467
  function exitRows(exits, colors = paint(process8.stdout)) {
448
468
  if (exits.length === 0)
449
469
  return [];
450
- const width = Math.max(...exits.map(([code]) => String(code).length));
451
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
452
- }
453
- function replacesRows(replaces, colors = paint(process8.stdout)) {
454
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
470
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
455
471
  }
456
472
  function wantsHelpJson(env = process8.env) {
457
473
  return env.KIT_HELP === "json";
@@ -477,29 +493,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
477
493
  return [];
478
494
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
479
495
  }
496
+ var MAX_INLINE_CHOICES = 24;
480
497
  function optionRows(options, colors = paint(process8.stdout)) {
481
498
  const rows = Object.entries(options).map(([name, option]) => {
482
499
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
483
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
500
+ const choices = option.choices?.join("|");
501
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
502
+ const named = inline ? `<${choices}>` : "<value>";
484
503
  const placeholder = option.optional === undefined ? named : `[${named}]`;
485
504
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
486
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
505
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
506
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
487
507
  });
488
508
  const width = Math.max(0, ...rows.map((row) => row.width));
489
509
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
490
510
  }
491
511
 
492
512
  // ../kit/src/text.ts
493
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
494
513
  function distance(a, b) {
495
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
496
- for (const [i, left] of [...a].entries()) {
514
+ const left = [...a];
515
+ const right = [...b];
516
+ let before = [];
517
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
518
+ for (const [i, x] of left.entries()) {
497
519
  const current = [i + 1];
498
- for (const [j, right] of [...b].entries())
499
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
520
+ for (const [j, y] of right.entries()) {
521
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
522
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
523
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
524
+ current.push(cost);
525
+ }
526
+ before = previous;
500
527
  previous = current;
501
528
  }
502
- return previous[b.length] ?? 0;
529
+ return previous[right.length] ?? 0;
503
530
  }
504
531
  function closest(name, names) {
505
532
  const started = names.find((known) => known.startsWith(name));
@@ -567,7 +594,7 @@ class Completing {
567
594
  }
568
595
  var completion = { active: false };
569
596
  var OUTPUT_OPTIONS = {
570
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
597
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
571
598
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
572
599
  };
573
600
  function applyOutput(color, plain, env = process10.env) {
@@ -739,21 +766,123 @@ function nearestOption(message, options, allowNegative) {
739
766
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
740
767
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
741
768
  }
769
+ // ../kit/src/argv.ts
770
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
771
+ import { resolve as resolve3 } from "path";
772
+ import process11 from "process";
773
+ function commandLine() {
774
+ try {
775
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
776
+ } catch {
777
+ return;
778
+ }
779
+ }
780
+ function realPath(word) {
781
+ try {
782
+ return realpathSync(resolve3(word));
783
+ } catch {
784
+ return;
785
+ }
786
+ }
787
+ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
788
+ const target = script === undefined ? undefined : realPath(script) ?? script;
789
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
790
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
791
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
792
+ }
742
793
  // ../kit/src/progress.ts
743
794
  var ESC = String.fromCharCode(27);
744
795
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
745
796
  var RESET_STYLE = `${ESC}[0m`;
746
797
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
747
798
  // ../kit/src/cli.ts
748
- import { readFileSync as readFileSync3, realpathSync } from "fs";
799
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
749
800
  import { dirname as dirname3, join as join5 } from "path";
801
+ import process14 from "process";
802
+
803
+ // ../kit/src/completions.ts
804
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
805
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
806
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
807
+ set -l current (commandline -ct)
808
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
809
+ if test "$line" = __files__
810
+ __fish_complete_path $current
811
+ else
812
+ echo $line
813
+ end
814
+ end
815
+ end`;
816
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
817
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
818
+ local -a lines
819
+ COMPREPLY=()
820
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
821
+ for line in "\${lines[@]}"; do
822
+ if [[ $line == __files__ ]]; then
823
+ COMPREPLY+=($(compgen -f -- "$cur"))
824
+ else
825
+ words+="\${line%%$'\\t'*}"$'\\n'
826
+ fi
827
+ done
828
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
829
+ }`;
830
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
831
+ local line
832
+ local -a described plain
833
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
834
+ if [[ $line == __files__ ]]; then
835
+ _files
836
+ elif [[ $line == *$'\\t'* ]]; then
837
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
838
+ else
839
+ plain+=("$line")
840
+ fi
841
+ done
842
+ (( \${#described} )) && _describe -V value described
843
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
844
+ return 0
845
+ }`;
846
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
847
+ if (shell === "fish")
848
+ return `${header}
849
+ ${FISH_FUNCTION}
850
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
851
+ `).join("")}`;
852
+ if (shell === "bash")
853
+ return `${header}
854
+ ${BASH_FUNCTION}
855
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
856
+ `;
857
+ return `${header}
858
+ ${ZSH_FUNCTION}
859
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
860
+ `;
861
+ }
862
+
863
+ // ../kit/src/notify.ts
750
864
  import process12 from "process";
865
+ var NOTIFY_AFTER_MS = 1e4;
866
+ var CANCELLED = 130;
867
+ function base64(text) {
868
+ return Buffer.from(text).toString("base64");
869
+ }
870
+ function notification(title, body, env = process12.env) {
871
+ const id = `kit${process12.pid}`;
872
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
873
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
874
+ }
875
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
876
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
877
+ return;
878
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
879
+ }
751
880
 
752
881
  // ../kit/src/usage.ts
753
882
  import { appendFileSync, mkdirSync } from "fs";
754
883
  import { homedir as homedir3 } from "os";
755
884
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
756
- import process11 from "process";
885
+ import process13 from "process";
757
886
 
758
887
  // ../kit/src/logs.ts
759
888
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -767,14 +896,14 @@ var usageError;
767
896
  function noteUsageError(message) {
768
897
  usageError = message;
769
898
  }
770
- function stateHome(env = process11.env) {
899
+ function stateHome(env = process13.env) {
771
900
  const dir = env.XDG_STATE_HOME;
772
901
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
773
902
  }
774
- function usagePath(env = process11.env) {
903
+ function usagePath(env = process13.env) {
775
904
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
776
905
  }
777
- function usageRecorded(env = process11.env) {
906
+ function usageRecorded(env = process13.env) {
778
907
  const off = env.KAYNOOO_CLI_NO_USAGE;
779
908
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
780
909
  }
@@ -788,7 +917,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
788
917
  usageError = undefined;
789
918
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
790
919
  }
791
- function recordUsage(entry, env = process11.env) {
920
+ function recordUsage(entry, env = process13.env) {
792
921
  if (!usageRecorded(env))
793
922
  return;
794
923
  try {
@@ -804,7 +933,11 @@ var LEVEL_OPTIONS = {
804
933
  ...OUTPUT_OPTIONS,
805
934
  help: { type: "boolean", short: "h", description: "show this help" }
806
935
  };
807
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
936
+ var TOP_OPTIONS = {
937
+ ...LEVEL_OPTIONS,
938
+ version: { type: "boolean", short: "v", description: "print the version" },
939
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
940
+ };
808
941
  async function commandRows(all, colors) {
809
942
  const commands = shown(all);
810
943
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -865,7 +998,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
865
998
  header(colors, summary),
866
999
  "",
867
1000
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
868
- ...replacesRows(replaces, colors),
869
1001
  "",
870
1002
  ...await commandRows(commands, colors),
871
1003
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -879,8 +1011,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
879
1011
  `);
880
1012
  }
881
1013
  function printError(prefix, message, hint, cause) {
882
- const colors = paint(process12.stderr);
883
- const styled = takesControlCodes(process12.stderr);
1014
+ const colors = paint(process14.stderr);
1015
+ const styled = takesControlCodes(process14.stderr);
884
1016
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
885
1017
  const under = (label, text, tint) => text === undefined ? "" : `
886
1018
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -923,11 +1055,11 @@ async function dispatch(level, typed, { version, redact }) {
923
1055
  }
924
1056
  }
925
1057
  if (name === undefined && level.path.length > 1) {
926
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stderr));
1058
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
927
1059
  return 2;
928
1060
  }
929
1061
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
930
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stdout));
1062
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
931
1063
  return 0;
932
1064
  }
933
1065
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -983,24 +1115,24 @@ function candidateLine(candidate) {
983
1115
  }
984
1116
  function positionalBeingTyped(before, { options, positionals }) {
985
1117
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
986
- let index = 0;
1118
+ const typed = [];
987
1119
  let at = 0;
988
1120
  while (at < before.length) {
989
1121
  const word = before[at];
990
1122
  if (word === "--") {
991
- index += before.length - at - 1;
1123
+ typed.push(...before.slice(at + 1));
992
1124
  break;
993
1125
  }
994
1126
  if (!word.startsWith("-"))
995
- index++;
1127
+ typed.push(word);
996
1128
  else if (takesValue(word))
997
1129
  at++;
998
1130
  at++;
999
1131
  }
1000
1132
  const last = positionals.at(-1);
1001
- if (index < positionals.length)
1002
- return positionals[index];
1003
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1133
+ if (typed.length < positionals.length)
1134
+ return { name: positionals[typed.length], typed };
1135
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1004
1136
  }
1005
1137
  async function leafCandidates(run, words) {
1006
1138
  const completing = await completingOf(run);
@@ -1008,12 +1140,12 @@ async function leafCandidates(run, words) {
1008
1140
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1009
1141
  const flag = words.at(-2);
1010
1142
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1143
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1011
1144
  if (option?.type === "string") {
1012
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1145
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1013
1146
  return values === undefined ? [FILES] : values.map(candidateLine);
1014
1147
  }
1015
- const name = positionalBeingTyped(words.slice(0, -1), completing);
1016
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1148
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1017
1149
  return values === undefined ? [FILES] : values.map(candidateLine);
1018
1150
  }
1019
1151
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -1038,15 +1170,32 @@ async function candidates(scope, defaultCommand, words, before = []) {
1038
1170
  }
1039
1171
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1040
1172
  }
1173
+ var COMPLETIONS = "--completions";
1174
+ function flagValue([flag = "", ...rest]) {
1175
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1176
+ }
1177
+ function printCompletionScript(name, args) {
1178
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1179
+ if (shell === undefined || args.length !== 1) {
1180
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1181
+ return 2;
1182
+ }
1183
+ console.log(completionScript(shell, [name]).trimEnd());
1184
+ return 0;
1185
+ }
1041
1186
  async function printCandidates(found) {
1042
1187
  for (const line of await found)
1043
1188
  console.log(line);
1044
1189
  return 0;
1045
1190
  }
1046
1191
  function packageVersion(entry = Bun.main) {
1047
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1192
+ let resolved = entry;
1193
+ try {
1194
+ resolved = realpathSync2(entry);
1195
+ } catch {}
1196
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1048
1197
  try {
1049
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1198
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1050
1199
  if (typeof version === "string")
1051
1200
  return version;
1052
1201
  } catch {}
@@ -1054,14 +1203,19 @@ function packageVersion(entry = Bun.main) {
1054
1203
  return "0.0.0";
1055
1204
  }
1056
1205
  }
1057
- async function runCli(cli, argv = process12.argv.slice(2)) {
1206
+ async function runCli(cli, argv = scriptArgs()) {
1058
1207
  const version = cli.version ?? packageVersion();
1059
1208
  if (argv[0] === COMPLETE)
1060
1209
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1210
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1211
+ return printCompletionScript(cli.name, flagValue(argv));
1212
+ const started = performance.now();
1061
1213
  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 });
1214
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1215
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1062
1216
  if (cli.usage !== false) {
1063
1217
  try {
1064
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1218
+ recordUsage(usageEntry(cli.name, command, argv, code));
1065
1219
  } catch {}
1066
1220
  }
1067
1221
  return code;
@@ -1081,19 +1235,23 @@ function commandPath(scope, argv) {
1081
1235
  }
1082
1236
  return path.length === 0 ? undefined : path.join(" ");
1083
1237
  }
1084
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1238
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1085
1239
  if (argv[0] === COMPLETE)
1086
1240
  return printCandidates(leafCandidates(run, argv.slice(1)));
1241
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1242
+ return printCompletionScript(name, flagValue(argv));
1087
1243
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1088
1244
  console.log(version ?? packageVersion());
1089
1245
  return 0;
1090
1246
  }
1091
1247
  let code;
1248
+ const started = performance.now();
1092
1249
  try {
1093
1250
  code = await run(argv);
1094
1251
  } catch (error) {
1095
1252
  code = reportThrown(name, error, redact, wantsJson(argv));
1096
1253
  }
1254
+ notifyEnd(name, code, performance.now() - started);
1097
1255
  if (usage !== false) {
1098
1256
  try {
1099
1257
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1111,12 +1269,18 @@ async function compose(args, { flags = [], ...options } = {}) {
1111
1269
  return captureOutput(["docker", "compose", ...flags, ...args], options);
1112
1270
  }
1113
1271
  // ../kit/src/folders.ts
1272
+ import { homedir as homedir4 } from "os";
1273
+ import { join as join6 } from "path";
1274
+ import process15 from "process";
1114
1275
  var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1115
1276
  function ignoredFolders(extra = [], where = {}) {
1116
1277
  const configured = readUserConfig("config", where).ignore;
1117
1278
  const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
1118
1279
  return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
1119
1280
  }
1281
+ function cacheFolder({ home = homedir4(), env = process15.env } = {}) {
1282
+ return env.XDG_CACHE_HOME ?? join6(home, ".cache");
1283
+ }
1120
1284
  // ../kit/src/secrets.ts
1121
1285
  var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
1122
1286
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
@@ -1129,11 +1293,11 @@ var {Glob } = globalThis.Bun;
1129
1293
  var SESSION_FILES = new Glob("*.json");
1130
1294
  var ACCOUNT_DIRS = new Glob("*/sessions");
1131
1295
  // src/commands/redact.ts
1132
- import process14 from "process";
1296
+ import process17 from "process";
1133
1297
 
1134
1298
  // src/files.ts
1135
1299
  import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
1136
- import { basename, dirname as dirname4, join as join6 } from "path";
1300
+ import { basename, dirname as dirname4, join as join7 } from "path";
1137
1301
 
1138
1302
  // src/dotenv.ts
1139
1303
  var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
@@ -1191,7 +1355,8 @@ function parseDotenv(text) {
1191
1355
  let body = start.slice(1);
1192
1356
  let raw = line;
1193
1357
  let end = closingQuote(body, quote);
1194
- while (end === -1 && index + 1 < physical.length) {
1358
+ const first = index;
1359
+ while (end === -1 && index + 1 < physical.length && !ASSIGNMENT.test(physical[index + 1] ?? "")) {
1195
1360
  index++;
1196
1361
  body += `
1197
1362
  ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
@@ -1199,6 +1364,11 @@ ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
1199
1364
  ${physical[index] ?? ""}`;
1200
1365
  end = closingQuote(body, quote);
1201
1366
  }
1367
+ if (end === -1 && index + 1 < physical.length) {
1368
+ index = first;
1369
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()), unterminated: true });
1370
+ continue;
1371
+ }
1202
1372
  const inner = end === -1 ? body : body.slice(0, end);
1203
1373
  lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
1204
1374
  }
@@ -1264,9 +1434,30 @@ var ESCAPE2 = /[.*+?^${}()|[\]\\]/g;
1264
1434
  function isPlaceholder(value) {
1265
1435
  return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
1266
1436
  }
1437
+ var STRONG_NAME = "password|passwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key";
1438
+ var WEAK_NAME = "token|credentials?|auth";
1439
+ var PLAIN_WORD = /^[a-z]+$/i;
1440
+ var AFTER_COLON = /:\s*$/;
1441
+ var DIGIT = /\d/;
1442
+ var KEY_VALUE_GAP = "\\s*[:=]\\s*";
1443
+ function isProse(value, before) {
1444
+ return isPlaceholder(value) || AFTER_COLON.test(before) && PLAIN_WORD.test(value);
1445
+ }
1446
+ function isWeak(value, before) {
1447
+ return isProse(value, before) || !(DIGIT.test(value) || value.length >= 16);
1448
+ }
1449
+ function keyed(names, value) {
1450
+ return new RegExp(`(?<![\\w-])["']?(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?["']?${KEY_VALUE_GAP}${value}`, "dgi");
1451
+ }
1267
1452
  var TOKEN_FORMATS = [
1268
1453
  { kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
1269
- { kind: "GitLab token", pattern: /\bglpat-[\w-]{20,}/dg },
1454
+ { kind: "GitLab token", pattern: /\bgl(?:pat|rt|dt|ptt)-[\w-]{20,}/dg },
1455
+ { kind: "Hugging Face token", pattern: /\bhf_[A-Za-z]{30,}/dg },
1456
+ { kind: "webhook secret", pattern: /\bwhsec_\w{20,}/dg },
1457
+ { kind: "DigitalOcean token", pattern: /\bdop_v1_\w{20,}/dg },
1458
+ { kind: "Shopify token", pattern: /\bshp(?:at|ca|pa|ss)_\w{20,}/dg },
1459
+ { kind: "password", pattern: /\bmysql(?:dump|admin)?\s+(?:\S+\s+)*?-p([^\s"'|;&-]\S{3,})/dg },
1460
+ { kind: "password", pattern: /\bsshpass\s+(?:-[a-oq-z]\s+)*-p\s*([^\s"'|;&]{4,})/dg },
1270
1461
  { kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
1271
1462
  { kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
1272
1463
  { kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
@@ -1277,8 +1468,10 @@ var TOKEN_FORMATS = [
1277
1468
  { kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
1278
1469
  { kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
1279
1470
  { kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
1280
- { kind: "password", pattern: /(?<![\w-])(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?=([^\s"'&;,]{4,})/dgi, skip: isPlaceholder },
1281
- { kind: "password", pattern: /(?<![\w-])["']?(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?["']?\s*[:=]\s*(["'])((?:\\.|(?!\1)[^\\\n]){4,})\1/dgi, skip: isPlaceholder }
1471
+ { kind: "password", pattern: keyed(STRONG_NAME, `([^\\s"'&;,]{4,})`), skip: isProse },
1472
+ { kind: "password", pattern: keyed(WEAK_NAME, `([^\\s"'&;,]{4,})`), skip: isWeak },
1473
+ { kind: "password", pattern: keyed(STRONG_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isPlaceholder },
1474
+ { kind: "password", pattern: keyed(WEAK_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isWeak }
1282
1475
  ];
1283
1476
  var PEM_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
1284
1477
  var PEM_END = /-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
@@ -1383,7 +1576,7 @@ function findSecrets(line, known) {
1383
1576
  if (start === undefined || end === undefined)
1384
1577
  continue;
1385
1578
  const value = line.slice(start, end);
1386
- if (!skip?.(value))
1579
+ if (!skip?.(value, line.slice(0, start)))
1387
1580
  found.push({ start, end, kind, mask: hint(value) });
1388
1581
  }
1389
1582
  }
@@ -1445,7 +1638,7 @@ async function envFiles(folder = process.cwd()) {
1445
1638
  const found = await readdir(folder, { withFileTypes: true });
1446
1639
  const names = [];
1447
1640
  for (const entry of found) {
1448
- if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join6(folder, entry.name)))
1641
+ if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join7(folder, entry.name)))
1449
1642
  names.push(entry.name);
1450
1643
  }
1451
1644
  return names.sort();
@@ -1469,7 +1662,7 @@ async function writeAtomic(path, text) {
1469
1662
  if (error.code !== "ENOENT")
1470
1663
  throw error;
1471
1664
  }
1472
- const temp = join6(dirname4(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1665
+ const temp = join7(dirname4(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1473
1666
  try {
1474
1667
  await writeFile(temp, text, { mode: 384, flag: "wx" });
1475
1668
  if (owner !== undefined)
@@ -1525,7 +1718,7 @@ async function acquire(path) {
1525
1718
  try {
1526
1719
  real = await realpath(path);
1527
1720
  } catch {}
1528
- const lock = join6(dirname4(real), `.${basename(real)}.lock`);
1721
+ const lock = join7(dirname4(real), `.${basename(real)}.lock`);
1529
1722
  const deadline = Date.now() + LOCK_WAIT_MS;
1530
1723
  while (true) {
1531
1724
  try {
@@ -1560,7 +1753,7 @@ async function envFilesBelow(folder, depth = 0) {
1560
1753
  return found;
1561
1754
  }
1562
1755
  for (const entry of children) {
1563
- const path = join6(folder, entry.name);
1756
+ const path = join7(folder, entry.name);
1564
1757
  if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
1565
1758
  found.push(...await envFilesBelow(path, depth + 1));
1566
1759
  else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
@@ -1697,15 +1890,14 @@ function check(text, known) {
1697
1890
  var usage2 = `redact [--check]
1698
1891
 
1699
1892
  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.
1700
- --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\`.
1701
-
1702
- Exits 0 when it copied the input or found no secret, 1 when --check finds one, 2 on a usage error.`;
1893
+ --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\`.`;
1894
+ var EXITS = [[0, "it copied the input or found no secret"], [1, "--check finds one"], [2, "a usage error"]];
1703
1895
  var options = {
1704
1896
  check: { type: "boolean", description: "list where secrets are instead of masking them, exit 1 when found" },
1705
1897
  "no-env": { type: "boolean", description: "do not search for the values of the .env* files" }
1706
1898
  };
1707
1899
  async function redact(args) {
1708
- 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"]] });
1900
+ const parsed = parse(args, usage2, options, { exits: EXITS, 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"]] });
1709
1901
  const known = parsed.values["no-env"] === true ? undefined : await loadKnown();
1710
1902
  if (parsed.values.check === true) {
1711
1903
  const findings = check(await readInput("-"), known);
@@ -1716,10 +1908,10 @@ async function redact(args) {
1716
1908
  const redactor = new Redactor(known);
1717
1909
  const decoder = new TextDecoder;
1718
1910
  for await (const chunk of Bun.stdin.stream())
1719
- process14.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1720
- process14.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1911
+ process17.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1912
+ process17.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1721
1913
  return 0;
1722
1914
  }
1723
1915
 
1724
1916
  // src/redact.ts
1725
- process15.exitCode = await runMain({ name: "redact", run: redact });
1917
+ process18.exitCode = await runMain({ name: "redact", run: redact });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-env",
3
3
  "type": "module",
4
- "version": "0.13.1",
4
+ "version": "0.14.1",
5
5
  "description": "ev lists and edits .env files with secrets masked, redact masks secrets in any piped output.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -36,7 +36,7 @@
36
36
  "ev": "$npm_execpath src/ev.ts",
37
37
  "redact": "$npm_execpath src/redact.ts"
38
38
  },
39
- "devDependencies": {
40
- "@kaynooo/cli-kit": "0.37.0"
39
+ "dependencies": {
40
+ "@kaynooo/cli-kit": "0.41.0"
41
41
  }
42
42
  }