@kaynooo/cli-env 0.13.1 → 0.13.2

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/ev.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/ev.ts
5
- import process17 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";
@@ -440,18 +440,14 @@ var FULL_STOP = /\.$/;
440
440
  function usageLine(usage, colors = paint(process8.stdout)) {
441
441
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
442
442
  }
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(`
443
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
444
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
445
445
  `);
446
446
  }
447
447
  function exitRows(exits, colors = paint(process8.stdout)) {
448
448
  if (exits.length === 0)
449
449
  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}`];
450
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
455
451
  }
456
452
  function wantsHelpJson(env = process8.env) {
457
453
  return env.KIT_HELP === "json";
@@ -739,21 +735,45 @@ function nearestOption(message, options, allowNegative) {
739
735
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
740
736
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
741
737
  }
738
+ // ../kit/src/argv.ts
739
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
740
+ import { resolve as resolve3 } from "path";
741
+ import process11 from "process";
742
+ function commandLine() {
743
+ try {
744
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
745
+ } catch {
746
+ return;
747
+ }
748
+ }
749
+ function realPath(word) {
750
+ try {
751
+ return realpathSync(resolve3(word));
752
+ } catch {
753
+ return;
754
+ }
755
+ }
756
+ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
757
+ const target = script === undefined ? undefined : realPath(script) ?? script;
758
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
759
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
760
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
761
+ }
742
762
  // ../kit/src/progress.ts
743
763
  var ESC = String.fromCharCode(27);
744
764
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
745
765
  var RESET_STYLE = `${ESC}[0m`;
746
766
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
747
767
  // ../kit/src/cli.ts
748
- import { readFileSync as readFileSync3, realpathSync } from "fs";
768
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
749
769
  import { dirname as dirname3, join as join5 } from "path";
750
- import process12 from "process";
770
+ import process13 from "process";
751
771
 
752
772
  // ../kit/src/usage.ts
753
773
  import { appendFileSync, mkdirSync } from "fs";
754
774
  import { homedir as homedir3 } from "os";
755
775
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
756
- import process11 from "process";
776
+ import process12 from "process";
757
777
 
758
778
  // ../kit/src/logs.ts
759
779
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -767,14 +787,14 @@ var usageError;
767
787
  function noteUsageError(message) {
768
788
  usageError = message;
769
789
  }
770
- function stateHome(env = process11.env) {
790
+ function stateHome(env = process12.env) {
771
791
  const dir = env.XDG_STATE_HOME;
772
792
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
773
793
  }
774
- function usagePath(env = process11.env) {
794
+ function usagePath(env = process12.env) {
775
795
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
776
796
  }
777
- function usageRecorded(env = process11.env) {
797
+ function usageRecorded(env = process12.env) {
778
798
  const off = env.KAYNOOO_CLI_NO_USAGE;
779
799
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
780
800
  }
@@ -788,7 +808,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
788
808
  usageError = undefined;
789
809
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
790
810
  }
791
- function recordUsage(entry, env = process11.env) {
811
+ function recordUsage(entry, env = process12.env) {
792
812
  if (!usageRecorded(env))
793
813
  return;
794
814
  try {
@@ -865,7 +885,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
865
885
  header(colors, summary),
866
886
  "",
867
887
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
868
- ...replacesRows(replaces, colors),
869
888
  "",
870
889
  ...await commandRows(commands, colors),
871
890
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -879,8 +898,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
879
898
  `);
880
899
  }
881
900
  function printError(prefix, message, hint, cause) {
882
- const colors = paint(process12.stderr);
883
- const styled = takesControlCodes(process12.stderr);
901
+ const colors = paint(process13.stderr);
902
+ const styled = takesControlCodes(process13.stderr);
884
903
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
885
904
  const under = (label, text, tint) => text === undefined ? "" : `
886
905
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -923,11 +942,11 @@ async function dispatch(level, typed, { version, redact }) {
923
942
  }
924
943
  }
925
944
  if (name === undefined && level.path.length > 1) {
926
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stderr));
945
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
927
946
  return 2;
928
947
  }
929
948
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
930
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stdout));
949
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
931
950
  return 0;
932
951
  }
933
952
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -983,24 +1002,24 @@ function candidateLine(candidate) {
983
1002
  }
984
1003
  function positionalBeingTyped(before, { options, positionals }) {
985
1004
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
986
- let index = 0;
1005
+ const typed = [];
987
1006
  let at = 0;
988
1007
  while (at < before.length) {
989
1008
  const word = before[at];
990
1009
  if (word === "--") {
991
- index += before.length - at - 1;
1010
+ typed.push(...before.slice(at + 1));
992
1011
  break;
993
1012
  }
994
1013
  if (!word.startsWith("-"))
995
- index++;
1014
+ typed.push(word);
996
1015
  else if (takesValue(word))
997
1016
  at++;
998
1017
  at++;
999
1018
  }
1000
1019
  const last = positionals.at(-1);
1001
- if (index < positionals.length)
1002
- return positionals[index];
1003
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1020
+ if (typed.length < positionals.length)
1021
+ return { name: positionals[typed.length], typed };
1022
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1004
1023
  }
1005
1024
  async function leafCandidates(run, words) {
1006
1025
  const completing = await completingOf(run);
@@ -1008,12 +1027,12 @@ async function leafCandidates(run, words) {
1008
1027
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1009
1028
  const flag = words.at(-2);
1010
1029
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1030
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1011
1031
  if (option?.type === "string") {
1012
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1032
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1013
1033
  return values === undefined ? [FILES] : values.map(candidateLine);
1014
1034
  }
1015
- const name = positionalBeingTyped(words.slice(0, -1), completing);
1016
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1035
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1017
1036
  return values === undefined ? [FILES] : values.map(candidateLine);
1018
1037
  }
1019
1038
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -1044,9 +1063,13 @@ async function printCandidates(found) {
1044
1063
  return 0;
1045
1064
  }
1046
1065
  function packageVersion(entry = Bun.main) {
1047
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1066
+ let resolved = entry;
1067
+ try {
1068
+ resolved = realpathSync2(entry);
1069
+ } catch {}
1070
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1048
1071
  try {
1049
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1072
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1050
1073
  if (typeof version === "string")
1051
1074
  return version;
1052
1075
  } catch {}
@@ -1054,7 +1077,7 @@ function packageVersion(entry = Bun.main) {
1054
1077
  return "0.0.0";
1055
1078
  }
1056
1079
  }
1057
- async function runCli(cli, argv = process12.argv.slice(2)) {
1080
+ async function runCli(cli, argv = scriptArgs()) {
1058
1081
  const version = cli.version ?? packageVersion();
1059
1082
  if (argv[0] === COMPLETE)
1060
1083
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -1081,7 +1104,7 @@ function commandPath(scope, argv) {
1081
1104
  }
1082
1105
  return path.length === 0 ? undefined : path.join(" ");
1083
1106
  }
1084
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1107
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1085
1108
  if (argv[0] === COMPLETE)
1086
1109
  return printCandidates(leafCandidates(run, argv.slice(1)));
1087
1110
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1130,8 +1153,8 @@ var SESSION_FILES = new Glob("*.json");
1130
1153
  var ACCOUNT_DIRS = new Glob("*/sessions");
1131
1154
  // src/commands/audit.ts
1132
1155
  import { stat as stat4 } from "fs/promises";
1133
- import { relative, resolve as resolve3 } from "path";
1134
- import process14 from "process";
1156
+ import { relative, resolve as resolve4 } from "path";
1157
+ import process15 from "process";
1135
1158
 
1136
1159
  // ../kit/src/shell.ts
1137
1160
  var SEPARATORS = new Set([`
@@ -1927,8 +1950,8 @@ var usage2 = `ev audit [dir...] [--fix]
1927
1950
 
1928
1951
  Lists the .env files any account on the machine can read or git tracks, and the compose files any account can read that write a secret out (a secret-named value or a URL password) instead of reading it from a .env, never printing a value.
1929
1952
  Looks under each folder (the current one by default) down to 5 levels, skipping node_modules, vendor and .git, and leaves .example, .sample, .template and .dist files out. A folder it cannot read is named on stderr.
1930
- With --fix, moves each secret a listed compose file writes out into the .env beside it as \${KEY}, puts it back when \`docker compose config\` resolves differently after, and shuts other accounts out of both files and of every listed .env; a key the .env already sets to another value stays put.
1931
- Exits 0 when it finds none (with --fix, when none is left), 1 when it finds one, 2 on a usage error.`;
1953
+ With --fix, moves each secret a listed compose file writes out into the .env beside it as \${KEY}, puts it back when \`docker compose config\` resolves differently after, and shuts other accounts out of both files and of every listed .env; a key the .env already sets to another value stays put.`;
1954
+ var EXITS = [[0, "it finds none (with --fix, when none is left)"], [1, "it finds one"], [2, "a usage error"]];
1932
1955
  var options = {
1933
1956
  json: jsonOption("the findings and the folders it could not read"),
1934
1957
  fix: { type: "boolean", description: "move inline compose secrets into a .env and shut other accounts out" }
@@ -1948,12 +1971,12 @@ async function isFolder(path) {
1948
1971
  }
1949
1972
  }
1950
1973
  function shown2(path) {
1951
- return path.startsWith(`${process14.cwd()}/`) ? relative(process14.cwd(), path) : path;
1974
+ return path.startsWith(`${process15.cwd()}/`) ? relative(process15.cwd(), path) : path;
1952
1975
  }
1953
1976
  async function fixAll(exposed, json) {
1954
1977
  const fixed = [];
1955
1978
  let left = false;
1956
- const tint = role("path", process14.stdout);
1979
+ const tint = role("path", process15.stdout);
1957
1980
  for (const { path, readable, group, tracked, secrets } of exposed) {
1958
1981
  const fix = secrets === undefined ? undefined : await fixCompose(path, group === true);
1959
1982
  const open = fix?.open ?? (readable && !await shutOthersOut(path, group === true) ? [path] : []);
@@ -1977,8 +2000,8 @@ async function fixAll(exposed, json) {
1977
2000
  return { fixed, left };
1978
2001
  }
1979
2002
  async function audit2(args) {
1980
- const parsed = parse(args, usage2, options);
1981
- const roots = (parsed.positionals.length > 0 ? parsed.positionals : ["."]).map((dir) => resolve3(dir));
2003
+ const parsed = parse(args, usage2, options, { exits: EXITS });
2004
+ const roots = (parsed.positionals.length > 0 ? parsed.positionals : ["."]).map((dir) => resolve4(dir));
1982
2005
  for (const dir of roots) {
1983
2006
  if (!await isFolder(dir))
1984
2007
  fail(`${dir} is not a folder`);
@@ -2005,8 +2028,8 @@ async function audit2(args) {
2005
2028
  console.log("no exposed .env file nor compose file writing a secret out");
2006
2029
  return 0;
2007
2030
  }
2008
- const uid = process14.getuid?.();
2009
- const tint = role("path", process14.stdout);
2031
+ const uid = process15.getuid?.();
2032
+ const tint = role("path", process15.stdout);
2010
2033
  for (const { path, readable, group, tracked, secrets } of exposed) {
2011
2034
  const sudo = uid !== undefined && uid !== 0 && (await stat4(path)).uid !== uid ? "sudo " : "";
2012
2035
  const problems = [
@@ -2022,27 +2045,25 @@ async function audit2(args) {
2022
2045
  }
2023
2046
 
2024
2047
  // src/commands/compare.ts
2025
- import process15 from "process";
2048
+ import process16 from "process";
2026
2049
  var diffUsage = `ev diff <a> <b>
2027
2050
 
2028
2051
  Names the keys set in one file and not the other, never their values.
2029
2052
 
2030
- --json prints {a, b, onlyA, onlyB}.
2031
-
2032
- Exits 0 when both set the same keys, 1 when they differ, 2 on a usage error.`;
2053
+ --json prints {a, b, onlyA, onlyB}.`;
2054
+ var DIFF_EXITS = [[0, "both set the same keys"], [1, "they differ"], [2, "a usage error"]];
2033
2055
  var missingUsage = `ev missing [file]
2034
2056
 
2035
2057
  Names the keys the reference file sets that the file (.env by default) does not.
2036
2058
 
2037
- --json prints {a, b, onlyA, onlyB} with the reference as a, so onlyA is what is missing.
2038
-
2039
- Exits 0 when none is missing, 1 when some are, 2 on a usage error.`;
2059
+ --json prints {a, b, onlyA, onlyB} with the reference as a, so onlyA is what is missing.`;
2060
+ var MISSING_EXITS = [[0, "none is missing"], [1, "some are"], [2, "a usage error"]];
2040
2061
  var jsonFlag = { json: jsonOption() };
2041
2062
  async function keys(path) {
2042
2063
  return new Set(entries(await readEnv(path)).keys());
2043
2064
  }
2044
2065
  async function diff(args) {
2045
- const parsed = parse(args, diffUsage, jsonFlag);
2066
+ const parsed = parse(args, diffUsage, jsonFlag, { exits: DIFF_EXITS });
2046
2067
  const [a, b] = parsed.positionals;
2047
2068
  if (a === undefined || b === undefined)
2048
2069
  fail(`needs two files
@@ -2056,8 +2077,8 @@ ${diffUsage}`);
2056
2077
  printJson({ a, b, onlyA, onlyB });
2057
2078
  return onlyA.length + onlyB.length === 0 ? 0 : 1;
2058
2079
  }
2059
- const path = role("path", process15.stdout);
2060
- const value = role("value", process15.stdout);
2080
+ const path = role("path", process16.stdout);
2081
+ const value = role("value", process16.stdout);
2061
2082
  const lines = [...onlyA.map((key) => `only in ${path(a)}: ${value(key)}`), ...onlyB.map((key) => `only in ${path(b)}: ${value(key)}`)];
2062
2083
  if (lines.length === 0)
2063
2084
  return 0;
@@ -2066,7 +2087,7 @@ ${diffUsage}`);
2066
2087
  return 1;
2067
2088
  }
2068
2089
  async function missing(args) {
2069
- const parsed = parse(args, missingUsage, { against: { type: "string", description: "the reference file (.env.example by default)" }, ...jsonFlag });
2090
+ const parsed = parse(args, missingUsage, { against: { type: "string", description: "the reference file (.env.example by default)" }, ...jsonFlag }, { exits: MISSING_EXITS });
2070
2091
  const [file = ".env"] = parsed.positionals;
2071
2092
  const against = parsed.values.against ?? ".env.example";
2072
2093
  const have = await keys(file);
@@ -2078,8 +2099,8 @@ async function missing(args) {
2078
2099
  }
2079
2100
  if (absent.length === 0)
2080
2101
  return 0;
2081
- const path = role("path", process15.stdout);
2082
- const value = role("value", process15.stdout);
2102
+ const path = role("path", process16.stdout);
2103
+ const value = role("value", process16.stdout);
2083
2104
  console.log(absent.map((key) => `${value(key)} (set in ${path(against)}, not in ${path(file)})`).join(`
2084
2105
  `));
2085
2106
  return 1;
@@ -2092,24 +2113,20 @@ var KEY_NAME = /^[A-Z_][\w.-]*$/i;
2092
2113
  var QUIET = { quiet: { type: "boolean", short: "q", description: "print nothing on success" } };
2093
2114
  var setUsage = `ev set KEY [file] [--quiet]
2094
2115
 
2095
- Sets KEY in the file (.env by default, created when missing), replacing its line in place or appending one. The value is read from stdin, or from -F <file>, so it never appears in a command line; --empty sets it to an empty value.
2096
-
2097
- Exits 0 when it wrote the key, 1 when it could not, 2 on a usage error.`;
2116
+ Sets KEY in the file (.env by default, created when missing), replacing its line in place or appending one. The value is read from stdin, or from -F <file>, so it never appears in a command line; --empty sets it to an empty value.`;
2117
+ var SET_EXITS = [[0, "it wrote the key"], [1, "it could not"], [2, "a usage error"]];
2098
2118
  var unsetUsage = `ev unset KEY [file] [--quiet]
2099
2119
 
2100
- Removes every line setting KEY from the file (.env by default), leaving comments and other lines as they are.
2101
-
2102
- Exits 0 when it removed the key, 1 when the file does not set it, 2 on a usage error.`;
2120
+ Removes every line setting KEY from the file (.env by default), leaving comments and other lines as they are.`;
2121
+ var UNSET_EXITS = [[0, "it removed the key"], [1, "the file does not set it"], [2, "a usage error"]];
2103
2122
  var mvUsage = `ev mv KEY --from <file> --to <file> [--quiet]
2104
2123
 
2105
- Moves KEY's line from one file to another, as written. Refuses to replace a key the target already sets unless --force.
2106
-
2107
- Exits 0 when it moved the key, 1 when the source lacks it or the target already sets it, 2 on a usage error.`;
2124
+ Moves KEY's line from one file to another, as written. Refuses to replace a key the target already sets unless --force.`;
2125
+ var MV_EXITS = [[0, "it moved the key"], [1, "the source lacks it or the target already sets it"], [2, "a usage error"]];
2108
2126
  var cpUsage = `ev cp KEY --from <file> --to <file> [--as NEWKEY] [--quiet]
2109
2127
 
2110
- Copies KEY's value from one file to another without printing it, replacing the key's line in the target in place or appending one, and prints the masked result as ev set does. --as stores the copy under another key.
2111
-
2112
- Exits 0 when it copied the key, 1 when the source lacks it, 2 on a usage error.`;
2128
+ Copies KEY's value from one file to another without printing it, replacing the key's line in the target in place or appending one, and prints the masked result as ev set does. --as stores the copy under another key.`;
2129
+ var CP_EXITS = [[0, "it copied the key"], [1, "the source lacks it"], [2, "a usage error"]];
2113
2130
  async function readValue(from) {
2114
2131
  const input = await readInput(from ?? "-", { noStdin: "pipe the value on stdin or give -F <file>, it is never taken from the command line" });
2115
2132
  if (input === "")
@@ -2128,7 +2145,7 @@ async function set(args) {
2128
2145
  file: { type: "string", short: "F", description: "read the value from this file instead of stdin" },
2129
2146
  empty: { type: "boolean", description: "set an empty value, reading nothing" },
2130
2147
  ...QUIET
2131
- });
2148
+ }, { exits: SET_EXITS });
2132
2149
  const [key, target = DEFAULT_FILE] = parsed.positionals;
2133
2150
  if (key === undefined)
2134
2151
  fail(`missing KEY
@@ -2150,7 +2167,7 @@ ${setUsage}`);
2150
2167
  return 0;
2151
2168
  }
2152
2169
  async function unset(args) {
2153
- const parsed = parse(args, unsetUsage, QUIET);
2170
+ const parsed = parse(args, unsetUsage, QUIET, { exits: UNSET_EXITS });
2154
2171
  const [key, target = DEFAULT_FILE] = parsed.positionals;
2155
2172
  if (key === undefined)
2156
2173
  fail(`missing KEY
@@ -2191,7 +2208,7 @@ async function mv(args) {
2191
2208
  to: { type: "string", description: "the file to put KEY in, created when missing" },
2192
2209
  force: { type: "boolean", description: "replace KEY when the target already sets it" },
2193
2210
  ...QUIET
2194
- });
2211
+ }, { exits: MV_EXITS });
2195
2212
  const [key] = parsed.positionals;
2196
2213
  const { from, to, force } = parsed.values;
2197
2214
  if (key === undefined || from === undefined || to === undefined)
@@ -2213,7 +2230,7 @@ async function cp(args) {
2213
2230
  to: { type: "string", description: "the file to put the copy in, created when missing" },
2214
2231
  as: { type: "string", description: "store the copy under this key instead" },
2215
2232
  ...QUIET
2216
- });
2233
+ }, { exits: CP_EXITS });
2217
2234
  const [key] = parsed.positionals;
2218
2235
  const { from, to, as } = parsed.values;
2219
2236
  if (key === undefined || from === undefined || to === undefined)
@@ -2229,7 +2246,7 @@ ${cpUsage}`);
2229
2246
 
2230
2247
  // src/commands/pins.ts
2231
2248
  import { readdir as readdir4, stat as stat5 } from "fs/promises";
2232
- import { join as join10, resolve as resolve4 } from "path";
2249
+ import { join as join10, resolve as resolve5 } from "path";
2233
2250
 
2234
2251
  // src/pins.ts
2235
2252
  import { readdir as readdir3, readFile } from "fs/promises";
@@ -2412,8 +2429,8 @@ Checks that an app's tests pin the env that reaches outside.
2412
2429
  Reads the app's env schema (the file calling defineEnv, src/env.ts) and lists its optional URL, key, token, secret, password and host variables, then the ones no \`.env.test\` entry, test-level overrideEnv or local bunfig preload dropping what .env sets pins, and each test file that calls testSite or proxyKeyTests without pinning them all.
2413
2430
  A file whose pages reach none of them says so with a \`// ev pins: none reached, <why>\` comment.
2414
2431
  The dir is an app, or a monorepo holding apps one level down (the current folder by default).
2415
- Reads variable names only, never a value.
2416
- Exits 0 when everything is pinned, 1 when something is not, 2 on a usage error.`;
2432
+ Reads variable names only, never a value.`;
2433
+ var EXITS2 = [[0, "everything is pinned"], [1, "something is not"], [2, "a usage error"]];
2417
2434
  var options2 = {
2418
2435
  json: jsonOption("each app with its reaching, unpinned variables and flagged test files"),
2419
2436
  except: { type: "string", description: "comma-separated variables to leave out, as ones that only link back to the app" }
@@ -2446,9 +2463,9 @@ function name(app, root) {
2446
2463
  return app.app === root ? app.app.split("/").at(-1) ?? app.app : app.app.slice(root.length + 1);
2447
2464
  }
2448
2465
  async function pins(args) {
2449
- const parsed = parse(args, usage3, options2, { positionals: ["[dir]"] });
2466
+ const parsed = parse(args, usage3, options2, { positionals: ["[dir]"], exits: EXITS2 });
2450
2467
  const json = parsed.values.json === true;
2451
- const root = resolve4(parsed.positionals[0] ?? ".");
2468
+ const root = resolve5(parsed.positionals[0] ?? ".");
2452
2469
  const except = new Set((parsed.values.except ?? "").split(",").map((entry) => entry.trim()).filter((entry) => entry !== ""));
2453
2470
  if (!await isFolder2(root))
2454
2471
  fail(`${root} is not a folder`);
@@ -2480,16 +2497,14 @@ var listUsage = `ev list [file]
2480
2497
 
2481
2498
  Prints every key of the folder's .env* files, or of one file, with secret values masked: a few leading characters and the length under a key named like TOKEN, SECRET, PASSWORD, PASS, PWD, KEY, PRIVATE, DSN, AUTH, SALT or COOKIE, any value equal to a secret of the folder's .env* files, and the password and tokens of any URL.
2482
2499
 
2483
- --json prints [{file, key, value, secret}], value masked and secret true when a value was.
2484
-
2485
- Exits 0 when it printed them, 1 when there is no .env* file, 2 on a usage error.`;
2500
+ --json prints [{file, key, value, secret}], value masked and secret true when a value was.`;
2501
+ var LIST_EXITS = [[0, "it printed them"], [1, "there is no .env* file"], [2, "a usage error"]];
2486
2502
  var getUsage = `ev get KEY [file]
2487
2503
 
2488
2504
  Prints the masked value of one key, from every .env* file that sets it or from one file.
2489
2505
 
2490
- --json prints [{file, key, value, secret}] for each file that sets it.
2491
-
2492
- Exits 0 when the key is set, 1 when it is not set anywhere, 2 on a usage error.`;
2506
+ --json prints [{file, key, value, secret}] for each file that sets it.`;
2507
+ var GET_EXITS = [[0, "the key is set"], [1, "it is not set anywhere"], [2, "a usage error"]];
2493
2508
  function display(key, value, known) {
2494
2509
  return maskValue(key, value, known).replaceAll(`
2495
2510
  `, "\\n").replaceAll("\r", "\\r");
@@ -2522,7 +2537,7 @@ async function readAll(names) {
2522
2537
  return { files, known: await loadKnown(process.cwd(), files.map(([, file]) => file)) };
2523
2538
  }
2524
2539
  async function list(args) {
2525
- const parsed = parse(args, listUsage, jsonFlag2);
2540
+ const parsed = parse(args, listUsage, jsonFlag2, { exits: LIST_EXITS });
2526
2541
  const [file] = parsed.positionals;
2527
2542
  const names = file === undefined ? await envFiles() : [file];
2528
2543
  if (names.length === 0)
@@ -2540,7 +2555,7 @@ async function list(args) {
2540
2555
  return 0;
2541
2556
  }
2542
2557
  async function get(args) {
2543
- const parsed = parse(args, getUsage, jsonFlag2);
2558
+ const parsed = parse(args, getUsage, jsonFlag2, { exits: GET_EXITS });
2544
2559
  const [key, file] = parsed.positionals;
2545
2560
  if (key === undefined)
2546
2561
  fail(`missing KEY
@@ -2563,19 +2578,17 @@ var grepUsage = `ev grep [-i] <regex> [file...]
2563
2578
 
2564
2579
  Prints the keys matching the regular expression, from the folder's .env* files or the files given, with their values masked as ev list does. The regex is matched against the key only, never the value: \`ev grep '^DATABASE_'\` instead of \`grep ^DATABASE_ .env\`.
2565
2580
 
2566
- --json prints [{file, key, value, secret}].
2567
-
2568
- Exits 0 when a key matches, 1 when none does, 2 on a usage error.`;
2581
+ --json prints [{file, key, value, secret}].`;
2582
+ var GREP_EXITS = [[0, "a key matches"], [1, "none does"], [2, "a usage error"]];
2569
2583
  var showUsage = `ev show <rev>:<file>
2570
2584
 
2571
2585
  Prints every key of an env file as a git revision holds it, values masked as ev list does: \`ev show HEAD~1:api/.env\` instead of \`git show HEAD~1:api/.env\`.
2572
2586
 
2573
- --json prints [{file, key, value, secret}].
2574
-
2575
- Exits 0 when it printed them, 1 when git cannot show the file, 2 on a usage error.`;
2587
+ --json prints [{file, key, value, secret}].`;
2588
+ var SHOW_EXITS = [[0, "it printed them"], [1, "git cannot show the file"], [2, "a usage error"]];
2576
2589
  var REVISION = /^([^:]+):(.+)$/;
2577
2590
  async function grep(args) {
2578
- const parsed = parse(args, grepUsage, { "ignore-case": { type: "boolean", short: "i", description: "match the key whatever its case" }, ...jsonFlag2 });
2591
+ const parsed = parse(args, grepUsage, { "ignore-case": { type: "boolean", short: "i", description: "match the key whatever its case" }, ...jsonFlag2 }, { exits: GREP_EXITS });
2579
2592
  const [source, ...given] = parsed.positionals;
2580
2593
  if (source === undefined)
2581
2594
  fail(`missing the regex
@@ -2602,7 +2615,7 @@ ${grepUsage}`);
2602
2615
  return 0;
2603
2616
  }
2604
2617
  async function show(args) {
2605
- const parsed = parse(args, showUsage, jsonFlag2);
2618
+ const parsed = parse(args, showUsage, jsonFlag2, { exits: SHOW_EXITS });
2606
2619
  const [target] = parsed.positionals;
2607
2620
  const [, revision, path] = REVISION.exec(target ?? "") ?? [];
2608
2621
  if (revision === undefined || path === undefined)
@@ -2625,7 +2638,7 @@ ${showUsage}`);
2625
2638
  }
2626
2639
 
2627
2640
  // src/commands/redact.ts
2628
- import process16 from "process";
2641
+ import process17 from "process";
2629
2642
 
2630
2643
  // src/redactor.ts
2631
2644
  var DIFF_START = /^(?:diff --git |@@ )/;
@@ -2746,15 +2759,14 @@ function check(text, known) {
2746
2759
  var usage4 = `redact [--check]
2747
2760
 
2748
2761
  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.
2749
- --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\`.
2750
-
2751
- Exits 0 when it copied the input or found no secret, 1 when --check finds one, 2 on a usage error.`;
2762
+ --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\`.`;
2763
+ var EXITS3 = [[0, "it copied the input or found no secret"], [1, "--check finds one"], [2, "a usage error"]];
2752
2764
  var options3 = {
2753
2765
  check: { type: "boolean", description: "list where secrets are instead of masking them, exit 1 when found" },
2754
2766
  "no-env": { type: "boolean", description: "do not search for the values of the .env* files" }
2755
2767
  };
2756
2768
  async function redact(args) {
2757
- const parsed = parse(args, usage4, options3, { 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"]] });
2769
+ const parsed = parse(args, usage4, options3, { exits: EXITS3, 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"]] });
2758
2770
  const known = parsed.values["no-env"] === true ? undefined : await loadKnown();
2759
2771
  if (parsed.values.check === true) {
2760
2772
  const findings = check(await readInput("-"), known);
@@ -2765,13 +2777,13 @@ async function redact(args) {
2765
2777
  const redactor = new Redactor(known);
2766
2778
  const decoder = new TextDecoder;
2767
2779
  for await (const chunk of Bun.stdin.stream())
2768
- process16.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
2769
- process16.stdout.write(redactor.push(decoder.decode()) + redactor.end());
2780
+ process17.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
2781
+ process17.stdout.write(redactor.push(decoder.decode()) + redactor.end());
2770
2782
  return 0;
2771
2783
  }
2772
2784
 
2773
2785
  // src/ev.ts
2774
- process17.exitCode = await runCli({
2786
+ process18.exitCode = await runCli({
2775
2787
  name: "ev",
2776
2788
  about: ".env files listed and edited with secrets masked",
2777
2789
  replaces: "cat .env, grep on env files and editing them by hand",
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 process16 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process10 from "process";
8
8
  import { parseArgs } from "util";
@@ -440,18 +440,14 @@ var FULL_STOP = /\.$/;
440
440
  function usageLine(usage, colors = paint(process8.stdout)) {
441
441
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
442
442
  }
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(`
443
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
444
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
445
445
  `);
446
446
  }
447
447
  function exitRows(exits, colors = paint(process8.stdout)) {
448
448
  if (exits.length === 0)
449
449
  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}`];
450
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
455
451
  }
456
452
  function wantsHelpJson(env = process8.env) {
457
453
  return env.KIT_HELP === "json";
@@ -739,21 +735,45 @@ function nearestOption(message, options, allowNegative) {
739
735
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
740
736
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
741
737
  }
738
+ // ../kit/src/argv.ts
739
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
740
+ import { resolve as resolve3 } from "path";
741
+ import process11 from "process";
742
+ function commandLine() {
743
+ try {
744
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
745
+ } catch {
746
+ return;
747
+ }
748
+ }
749
+ function realPath(word) {
750
+ try {
751
+ return realpathSync(resolve3(word));
752
+ } catch {
753
+ return;
754
+ }
755
+ }
756
+ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
757
+ const target = script === undefined ? undefined : realPath(script) ?? script;
758
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
759
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
760
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
761
+ }
742
762
  // ../kit/src/progress.ts
743
763
  var ESC = String.fromCharCode(27);
744
764
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
745
765
  var RESET_STYLE = `${ESC}[0m`;
746
766
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
747
767
  // ../kit/src/cli.ts
748
- import { readFileSync as readFileSync3, realpathSync } from "fs";
768
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
749
769
  import { dirname as dirname3, join as join5 } from "path";
750
- import process12 from "process";
770
+ import process13 from "process";
751
771
 
752
772
  // ../kit/src/usage.ts
753
773
  import { appendFileSync, mkdirSync } from "fs";
754
774
  import { homedir as homedir3 } from "os";
755
775
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
756
- import process11 from "process";
776
+ import process12 from "process";
757
777
 
758
778
  // ../kit/src/logs.ts
759
779
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -767,14 +787,14 @@ var usageError;
767
787
  function noteUsageError(message) {
768
788
  usageError = message;
769
789
  }
770
- function stateHome(env = process11.env) {
790
+ function stateHome(env = process12.env) {
771
791
  const dir = env.XDG_STATE_HOME;
772
792
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
773
793
  }
774
- function usagePath(env = process11.env) {
794
+ function usagePath(env = process12.env) {
775
795
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
776
796
  }
777
- function usageRecorded(env = process11.env) {
797
+ function usageRecorded(env = process12.env) {
778
798
  const off = env.KAYNOOO_CLI_NO_USAGE;
779
799
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
780
800
  }
@@ -788,7 +808,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
788
808
  usageError = undefined;
789
809
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
790
810
  }
791
- function recordUsage(entry, env = process11.env) {
811
+ function recordUsage(entry, env = process12.env) {
792
812
  if (!usageRecorded(env))
793
813
  return;
794
814
  try {
@@ -865,7 +885,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
865
885
  header(colors, summary),
866
886
  "",
867
887
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
868
- ...replacesRows(replaces, colors),
869
888
  "",
870
889
  ...await commandRows(commands, colors),
871
890
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -879,8 +898,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
879
898
  `);
880
899
  }
881
900
  function printError(prefix, message, hint, cause) {
882
- const colors = paint(process12.stderr);
883
- const styled = takesControlCodes(process12.stderr);
901
+ const colors = paint(process13.stderr);
902
+ const styled = takesControlCodes(process13.stderr);
884
903
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
885
904
  const under = (label, text, tint) => text === undefined ? "" : `
886
905
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -923,11 +942,11 @@ async function dispatch(level, typed, { version, redact }) {
923
942
  }
924
943
  }
925
944
  if (name === undefined && level.path.length > 1) {
926
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stderr));
945
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
927
946
  return 2;
928
947
  }
929
948
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
930
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stdout));
949
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
931
950
  return 0;
932
951
  }
933
952
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -983,24 +1002,24 @@ function candidateLine(candidate) {
983
1002
  }
984
1003
  function positionalBeingTyped(before, { options, positionals }) {
985
1004
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
986
- let index = 0;
1005
+ const typed = [];
987
1006
  let at = 0;
988
1007
  while (at < before.length) {
989
1008
  const word = before[at];
990
1009
  if (word === "--") {
991
- index += before.length - at - 1;
1010
+ typed.push(...before.slice(at + 1));
992
1011
  break;
993
1012
  }
994
1013
  if (!word.startsWith("-"))
995
- index++;
1014
+ typed.push(word);
996
1015
  else if (takesValue(word))
997
1016
  at++;
998
1017
  at++;
999
1018
  }
1000
1019
  const last = positionals.at(-1);
1001
- if (index < positionals.length)
1002
- return positionals[index];
1003
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1020
+ if (typed.length < positionals.length)
1021
+ return { name: positionals[typed.length], typed };
1022
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1004
1023
  }
1005
1024
  async function leafCandidates(run, words) {
1006
1025
  const completing = await completingOf(run);
@@ -1008,12 +1027,12 @@ async function leafCandidates(run, words) {
1008
1027
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1009
1028
  const flag = words.at(-2);
1010
1029
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1030
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1011
1031
  if (option?.type === "string") {
1012
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1032
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1013
1033
  return values === undefined ? [FILES] : values.map(candidateLine);
1014
1034
  }
1015
- const name = positionalBeingTyped(words.slice(0, -1), completing);
1016
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1035
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1017
1036
  return values === undefined ? [FILES] : values.map(candidateLine);
1018
1037
  }
1019
1038
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -1044,9 +1063,13 @@ async function printCandidates(found) {
1044
1063
  return 0;
1045
1064
  }
1046
1065
  function packageVersion(entry = Bun.main) {
1047
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1066
+ let resolved = entry;
1067
+ try {
1068
+ resolved = realpathSync2(entry);
1069
+ } catch {}
1070
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1048
1071
  try {
1049
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1072
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1050
1073
  if (typeof version === "string")
1051
1074
  return version;
1052
1075
  } catch {}
@@ -1054,7 +1077,7 @@ function packageVersion(entry = Bun.main) {
1054
1077
  return "0.0.0";
1055
1078
  }
1056
1079
  }
1057
- async function runCli(cli, argv = process12.argv.slice(2)) {
1080
+ async function runCli(cli, argv = scriptArgs()) {
1058
1081
  const version = cli.version ?? packageVersion();
1059
1082
  if (argv[0] === COMPLETE)
1060
1083
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -1081,7 +1104,7 @@ function commandPath(scope, argv) {
1081
1104
  }
1082
1105
  return path.length === 0 ? undefined : path.join(" ");
1083
1106
  }
1084
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1107
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1085
1108
  if (argv[0] === COMPLETE)
1086
1109
  return printCandidates(leafCandidates(run, argv.slice(1)));
1087
1110
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1129,7 +1152,7 @@ var {Glob } = globalThis.Bun;
1129
1152
  var SESSION_FILES = new Glob("*.json");
1130
1153
  var ACCOUNT_DIRS = new Glob("*/sessions");
1131
1154
  // src/commands/redact.ts
1132
- import process14 from "process";
1155
+ import process15 from "process";
1133
1156
 
1134
1157
  // src/files.ts
1135
1158
  import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
@@ -1697,15 +1720,14 @@ function check(text, known) {
1697
1720
  var usage2 = `redact [--check]
1698
1721
 
1699
1722
  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.`;
1723
+ --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\`.`;
1724
+ var EXITS = [[0, "it copied the input or found no secret"], [1, "--check finds one"], [2, "a usage error"]];
1703
1725
  var options = {
1704
1726
  check: { type: "boolean", description: "list where secrets are instead of masking them, exit 1 when found" },
1705
1727
  "no-env": { type: "boolean", description: "do not search for the values of the .env* files" }
1706
1728
  };
1707
1729
  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"]] });
1730
+ 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
1731
  const known = parsed.values["no-env"] === true ? undefined : await loadKnown();
1710
1732
  if (parsed.values.check === true) {
1711
1733
  const findings = check(await readInput("-"), known);
@@ -1716,10 +1738,10 @@ async function redact(args) {
1716
1738
  const redactor = new Redactor(known);
1717
1739
  const decoder = new TextDecoder;
1718
1740
  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());
1741
+ process15.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1742
+ process15.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1721
1743
  return 0;
1722
1744
  }
1723
1745
 
1724
1746
  // src/redact.ts
1725
- process15.exitCode = await runMain({ name: "redact", run: redact });
1747
+ process16.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.13.2",
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",
@@ -37,6 +37,6 @@
37
37
  "redact": "$npm_execpath src/redact.ts"
38
38
  },
39
39
  "devDependencies": {
40
- "@kaynooo/cli-kit": "0.37.0"
40
+ "@kaynooo/cli-kit": "0.38.2"
41
41
  }
42
42
  }
@@ -1,3 +1,4 @@
1
+ import type { ExitRow } from '@kaynooo/cli-kit'
1
2
  import type { Exposure } from '../audit'
2
3
  import type { ComposeFix } from '../fix'
3
4
  import { stat } from 'node:fs/promises'
@@ -12,8 +13,9 @@ const usage = `ev audit [dir...] [--fix]
12
13
 
13
14
  Lists the .env files any account on the machine can read or git tracks, and the compose files any account can read that write a secret out (a secret-named value or a URL password) instead of reading it from a .env, never printing a value.
14
15
  Looks under each folder (the current one by default) down to 5 levels, skipping node_modules, vendor and .git, and leaves .example, .sample, .template and .dist files out. A folder it cannot read is named on stderr.
15
- With --fix, moves each secret a listed compose file writes out into the .env beside it as \${KEY}, puts it back when \`docker compose config\` resolves differently after, and shuts other accounts out of both files and of every listed .env; a key the .env already sets to another value stays put.
16
- Exits 0 when it finds none (with --fix, when none is left), 1 when it finds one, 2 on a usage error.`
16
+ With --fix, moves each secret a listed compose file writes out into the .env beside it as \${KEY}, puts it back when \`docker compose config\` resolves differently after, and shuts other accounts out of both files and of every listed .env; a key the .env already sets to another value stays put.`
17
+
18
+ const EXITS: ExitRow[] = [[0, 'it finds none (with --fix, when none is left)'], [1, 'it finds one'], [2, 'a usage error']]
17
19
 
18
20
  const options = {
19
21
  json: jsonOption('the findings and the folders it could not read'),
@@ -76,7 +78,7 @@ async function fixAll(exposed: Exposure[], json: boolean): Promise<{ fixed: Comp
76
78
  }
77
79
 
78
80
  export async function audit(args: string[]): Promise<number> {
79
- const parsed = parse(args, usage, options)
81
+ const parsed = parse(args, usage, options, { exits: EXITS })
80
82
 
81
83
  const roots = (parsed.positionals.length > 0 ? parsed.positionals : ['.']).map(dir => resolve(dir))
82
84
 
@@ -1,3 +1,4 @@
1
+ import type { ExitRow } from '@kaynooo/cli-kit'
1
2
  import process from 'node:process'
2
3
  import { fail, jsonOption, parse, printJson, role } from '@kaynooo/cli-kit'
3
4
  import { entries } from '../dotenv'
@@ -7,17 +8,17 @@ const diffUsage = `ev diff <a> <b>
7
8
 
8
9
  Names the keys set in one file and not the other, never their values.
9
10
 
10
- --json prints {a, b, onlyA, onlyB}.
11
+ --json prints {a, b, onlyA, onlyB}.`
11
12
 
12
- Exits 0 when both set the same keys, 1 when they differ, 2 on a usage error.`
13
+ const DIFF_EXITS: ExitRow[] = [[0, 'both set the same keys'], [1, 'they differ'], [2, 'a usage error']]
13
14
 
14
15
  const missingUsage = `ev missing [file]
15
16
 
16
17
  Names the keys the reference file sets that the file (.env by default) does not.
17
18
 
18
- --json prints {a, b, onlyA, onlyB} with the reference as a, so onlyA is what is missing.
19
+ --json prints {a, b, onlyA, onlyB} with the reference as a, so onlyA is what is missing.`
19
20
 
20
- Exits 0 when none is missing, 1 when some are, 2 on a usage error.`
21
+ const MISSING_EXITS: ExitRow[] = [[0, 'none is missing'], [1, 'some are'], [2, 'a usage error']]
21
22
 
22
23
  const jsonFlag = { json: jsonOption() } as const
23
24
 
@@ -26,7 +27,7 @@ async function keys(path: string): Promise<Set<string>> {
26
27
  }
27
28
 
28
29
  export async function diff(args: string[]): Promise<number> {
29
- const parsed = parse(args, diffUsage, jsonFlag)
30
+ const parsed = parse(args, diffUsage, jsonFlag, { exits: DIFF_EXITS })
30
31
 
31
32
  const [a, b] = parsed.positionals
32
33
 
@@ -57,7 +58,7 @@ export async function diff(args: string[]): Promise<number> {
57
58
  }
58
59
 
59
60
  export async function missing(args: string[]): Promise<number> {
60
- const parsed = parse(args, missingUsage, { against: { type: 'string', description: 'the reference file (.env.example by default)' }, ...jsonFlag })
61
+ const parsed = parse(args, missingUsage, { against: { type: 'string', description: 'the reference file (.env.example by default)' }, ...jsonFlag }, { exits: MISSING_EXITS })
61
62
 
62
63
  const [file = '.env'] = parsed.positionals
63
64
  const against = parsed.values.against ?? '.env.example'
@@ -1,3 +1,4 @@
1
+ import type { ExitRow } from '@kaynooo/cli-kit'
1
2
  import { badUsage, fail, parse, readInput } from '@kaynooo/cli-kit'
2
3
  import { entries, lastLine, removeKey, setLine } from '../dotenv'
3
4
  import { loadKnown, readEnv, withLocks, writeEnv } from '../files'
@@ -11,27 +12,27 @@ const QUIET = { quiet: { type: 'boolean', short: 'q', description: 'print nothin
11
12
 
12
13
  const setUsage = `ev set KEY [file] [--quiet]
13
14
 
14
- Sets KEY in the file (.env by default, created when missing), replacing its line in place or appending one. The value is read from stdin, or from -F <file>, so it never appears in a command line; --empty sets it to an empty value.
15
+ Sets KEY in the file (.env by default, created when missing), replacing its line in place or appending one. The value is read from stdin, or from -F <file>, so it never appears in a command line; --empty sets it to an empty value.`
15
16
 
16
- Exits 0 when it wrote the key, 1 when it could not, 2 on a usage error.`
17
+ const SET_EXITS: ExitRow[] = [[0, 'it wrote the key'], [1, 'it could not'], [2, 'a usage error']]
17
18
 
18
19
  const unsetUsage = `ev unset KEY [file] [--quiet]
19
20
 
20
- Removes every line setting KEY from the file (.env by default), leaving comments and other lines as they are.
21
+ Removes every line setting KEY from the file (.env by default), leaving comments and other lines as they are.`
21
22
 
22
- Exits 0 when it removed the key, 1 when the file does not set it, 2 on a usage error.`
23
+ const UNSET_EXITS: ExitRow[] = [[0, 'it removed the key'], [1, 'the file does not set it'], [2, 'a usage error']]
23
24
 
24
25
  const mvUsage = `ev mv KEY --from <file> --to <file> [--quiet]
25
26
 
26
- Moves KEY's line from one file to another, as written. Refuses to replace a key the target already sets unless --force.
27
+ Moves KEY's line from one file to another, as written. Refuses to replace a key the target already sets unless --force.`
27
28
 
28
- Exits 0 when it moved the key, 1 when the source lacks it or the target already sets it, 2 on a usage error.`
29
+ const MV_EXITS: ExitRow[] = [[0, 'it moved the key'], [1, 'the source lacks it or the target already sets it'], [2, 'a usage error']]
29
30
 
30
31
  const cpUsage = `ev cp KEY --from <file> --to <file> [--as NEWKEY] [--quiet]
31
32
 
32
- Copies KEY's value from one file to another without printing it, replacing the key's line in the target in place or appending one, and prints the masked result as ev set does. --as stores the copy under another key.
33
+ Copies KEY's value from one file to another without printing it, replacing the key's line in the target in place or appending one, and prints the masked result as ev set does. --as stores the copy under another key.`
33
34
 
34
- Exits 0 when it copied the key, 1 when the source lacks it, 2 on a usage error.`
35
+ const CP_EXITS: ExitRow[] = [[0, 'it copied the key'], [1, 'the source lacks it'], [2, 'a usage error']]
35
36
 
36
37
  async function readValue(from: string | undefined): Promise<string> {
37
38
  const input = await readInput(from ?? '-', { noStdin: 'pipe the value on stdin or give -F <file>, it is never taken from the command line' })
@@ -57,7 +58,7 @@ export async function set(args: string[]): Promise<number> {
57
58
  file: { type: 'string', short: 'F', description: 'read the value from this file instead of stdin' },
58
59
  empty: { type: 'boolean', description: 'set an empty value, reading nothing' },
59
60
  ...QUIET,
60
- })
61
+ }, { exits: SET_EXITS })
61
62
 
62
63
  const [key, target = DEFAULT_FILE] = parsed.positionals
63
64
 
@@ -87,7 +88,7 @@ export async function set(args: string[]): Promise<number> {
87
88
  }
88
89
 
89
90
  export async function unset(args: string[]): Promise<number> {
90
- const parsed = parse(args, unsetUsage, QUIET)
91
+ const parsed = parse(args, unsetUsage, QUIET, { exits: UNSET_EXITS })
91
92
 
92
93
  const [key, target = DEFAULT_FILE] = parsed.positionals
93
94
 
@@ -145,7 +146,7 @@ export async function mv(args: string[]): Promise<number> {
145
146
  to: { type: 'string', description: 'the file to put KEY in, created when missing' },
146
147
  force: { type: 'boolean', description: 'replace KEY when the target already sets it' },
147
148
  ...QUIET,
148
- })
149
+ }, { exits: MV_EXITS })
149
150
 
150
151
  const [key] = parsed.positionals
151
152
  const { from, to, force } = parsed.values
@@ -172,7 +173,7 @@ export async function cp(args: string[]): Promise<number> {
172
173
  to: { type: 'string', description: 'the file to put the copy in, created when missing' },
173
174
  as: { type: 'string', description: 'store the copy under this key instead' },
174
175
  ...QUIET,
175
- })
176
+ }, { exits: CP_EXITS })
176
177
 
177
178
  const [key] = parsed.positionals
178
179
  const { from, to, as } = parsed.values
@@ -1,3 +1,4 @@
1
+ import type { ExitRow } from '@kaynooo/cli-kit'
1
2
  import type { AppPins } from '../pins'
2
3
  import { readdir, stat } from 'node:fs/promises'
3
4
  import { join, resolve } from 'node:path'
@@ -10,8 +11,9 @@ Checks that an app's tests pin the env that reaches outside.
10
11
  Reads the app's env schema (the file calling defineEnv, src/env.ts) and lists its optional URL, key, token, secret, password and host variables, then the ones no \`.env.test\` entry, test-level overrideEnv or local bunfig preload dropping what .env sets pins, and each test file that calls testSite or proxyKeyTests without pinning them all.
11
12
  A file whose pages reach none of them says so with a \`// ev pins: none reached, <why>\` comment.
12
13
  The dir is an app, or a monorepo holding apps one level down (the current folder by default).
13
- Reads variable names only, never a value.
14
- Exits 0 when everything is pinned, 1 when something is not, 2 on a usage error.`
14
+ Reads variable names only, never a value.`
15
+
16
+ const EXITS: ExitRow[] = [[0, 'everything is pinned'], [1, 'something is not'], [2, 'a usage error']]
15
17
 
16
18
  const options = {
17
19
  json: jsonOption('each app with its reaching, unpinned variables and flagged test files'),
@@ -57,7 +59,7 @@ function name(app: AppPins, root: string): string {
57
59
  }
58
60
 
59
61
  export async function pins(args: string[]): Promise<number> {
60
- const parsed = parse(args, usage, options, { positionals: ['[dir]'] })
62
+ const parsed = parse(args, usage, options, { positionals: ['[dir]'], exits: EXITS })
61
63
  const json = parsed.values.json === true
62
64
  const root = resolve(parsed.positionals[0] ?? '.')
63
65
  const except = new Set((parsed.values.except ?? '').split(',').map(entry => entry.trim()).filter(entry => entry !== ''))
@@ -1,3 +1,4 @@
1
+ import type { ExitRow } from '@kaynooo/cli-kit'
1
2
  import type { Dotenv } from '../dotenv'
2
3
  import type { KnownSecrets } from '../mask'
3
4
  import { fail, jsonOption, parse, printJson, role, table } from '@kaynooo/cli-kit'
@@ -10,17 +11,17 @@ const listUsage = `ev list [file]
10
11
 
11
12
  Prints every key of the folder's .env* files, or of one file, with secret values masked: a few leading characters and the length under a key named like TOKEN, SECRET, PASSWORD, PASS, PWD, KEY, PRIVATE, DSN, AUTH, SALT or COOKIE, any value equal to a secret of the folder's .env* files, and the password and tokens of any URL.
12
13
 
13
- --json prints [{file, key, value, secret}], value masked and secret true when a value was.
14
+ --json prints [{file, key, value, secret}], value masked and secret true when a value was.`
14
15
 
15
- Exits 0 when it printed them, 1 when there is no .env* file, 2 on a usage error.`
16
+ const LIST_EXITS: ExitRow[] = [[0, 'it printed them'], [1, 'there is no .env* file'], [2, 'a usage error']]
16
17
 
17
18
  const getUsage = `ev get KEY [file]
18
19
 
19
20
  Prints the masked value of one key, from every .env* file that sets it or from one file.
20
21
 
21
- --json prints [{file, key, value, secret}] for each file that sets it.
22
+ --json prints [{file, key, value, secret}] for each file that sets it.`
22
23
 
23
- Exits 0 when the key is set, 1 when it is not set anywhere, 2 on a usage error.`
24
+ const GET_EXITS: ExitRow[] = [[0, 'the key is set'], [1, 'it is not set anywhere'], [2, 'a usage error']]
24
25
 
25
26
  function display(key: string, value: string, known: KnownSecrets): string {
26
27
  return maskValue(key, value, known).replaceAll('\n', '\\n').replaceAll('\r', '\\r')
@@ -69,7 +70,7 @@ async function readAll(names: string[]): Promise<{ files: [name: string, file: D
69
70
  }
70
71
 
71
72
  export async function list(args: string[]): Promise<number> {
72
- const parsed = parse(args, listUsage, jsonFlag)
73
+ const parsed = parse(args, listUsage, jsonFlag, { exits: LIST_EXITS })
73
74
 
74
75
  const [file] = parsed.positionals
75
76
  const names = file === undefined ? await envFiles() : [file]
@@ -95,7 +96,7 @@ export async function list(args: string[]): Promise<number> {
95
96
  }
96
97
 
97
98
  export async function get(args: string[]): Promise<number> {
98
- const parsed = parse(args, getUsage, jsonFlag)
99
+ const parsed = parse(args, getUsage, jsonFlag, { exits: GET_EXITS })
99
100
 
100
101
  const [key, file] = parsed.positionals
101
102
 
@@ -126,22 +127,22 @@ const grepUsage = `ev grep [-i] <regex> [file...]
126
127
 
127
128
  Prints the keys matching the regular expression, from the folder's .env* files or the files given, with their values masked as ev list does. The regex is matched against the key only, never the value: \`ev grep '^DATABASE_'\` instead of \`grep ^DATABASE_ .env\`.
128
129
 
129
- --json prints [{file, key, value, secret}].
130
+ --json prints [{file, key, value, secret}].`
130
131
 
131
- Exits 0 when a key matches, 1 when none does, 2 on a usage error.`
132
+ const GREP_EXITS: ExitRow[] = [[0, 'a key matches'], [1, 'none does'], [2, 'a usage error']]
132
133
 
133
134
  const showUsage = `ev show <rev>:<file>
134
135
 
135
136
  Prints every key of an env file as a git revision holds it, values masked as ev list does: \`ev show HEAD~1:api/.env\` instead of \`git show HEAD~1:api/.env\`.
136
137
 
137
- --json prints [{file, key, value, secret}].
138
+ --json prints [{file, key, value, secret}].`
138
139
 
139
- Exits 0 when it printed them, 1 when git cannot show the file, 2 on a usage error.`
140
+ const SHOW_EXITS: ExitRow[] = [[0, 'it printed them'], [1, 'git cannot show the file'], [2, 'a usage error']]
140
141
 
141
142
  const REVISION = /^([^:]+):(.+)$/
142
143
 
143
144
  export async function grep(args: string[]): Promise<number> {
144
- const parsed = parse(args, grepUsage, { 'ignore-case': { type: 'boolean', short: 'i', description: 'match the key whatever its case' }, ...jsonFlag })
145
+ const parsed = parse(args, grepUsage, { 'ignore-case': { type: 'boolean', short: 'i', description: 'match the key whatever its case' }, ...jsonFlag }, { exits: GREP_EXITS })
145
146
 
146
147
  const [source, ...given] = parsed.positionals
147
148
 
@@ -178,7 +179,7 @@ export async function grep(args: string[]): Promise<number> {
178
179
  }
179
180
 
180
181
  export async function show(args: string[]): Promise<number> {
181
- const parsed = parse(args, showUsage, jsonFlag)
182
+ const parsed = parse(args, showUsage, jsonFlag, { exits: SHOW_EXITS })
182
183
 
183
184
  const [target] = parsed.positionals
184
185
  const [, revision, path] = REVISION.exec(target ?? '') ?? []
@@ -1,3 +1,4 @@
1
+ import type { ExitRow } from '@kaynooo/cli-kit'
1
2
  import process from 'node:process'
2
3
  import { parse, readInput } from '@kaynooo/cli-kit'
3
4
  import { loadKnown } from '../files'
@@ -6,7 +7,9 @@ import { check, Redactor } from '../redactor'
6
7
  const usage = `redact [--check]
7
8
 
8
9
  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.
9
- --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\`.\n\nExits 0 when it copied the input or found no secret, 1 when --check finds one, 2 on a usage error.`
10
+ --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\`.`
11
+
12
+ const EXITS: ExitRow[] = [[0, 'it copied the input or found no secret'], [1, '--check finds one'], [2, 'a usage error']]
10
13
 
11
14
  const options = {
12
15
  'check': { type: 'boolean', description: 'list where secrets are instead of masking them, exit 1 when found' },
@@ -14,7 +17,7 @@ const options = {
14
17
  } as const
15
18
 
16
19
  export async function redact(args: string[]): Promise<number> {
17
- 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']] })
20
+ const parsed = parse(args, usage, 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']] })
18
21
 
19
22
  const known = parsed.values['no-env'] === true ? undefined : await loadKnown()
20
23