@kaynooo/cli-proc 0.7.1 → 0.7.5

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/pid-cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/pid-cli.ts
5
- import process16 from "process";
5
+ import process18 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -390,6 +390,9 @@ function formatSeconds(total) {
390
390
  const next = amounts[first + 1];
391
391
  return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
392
392
  }
393
+ function formatDuration(ms) {
394
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
395
+ }
393
396
  function upTo(text, separator) {
394
397
  const end = text.indexOf(separator);
395
398
  return end === -1 ? text : text.slice(0, end);
@@ -450,24 +453,20 @@ function printJson(value) {
450
453
 
451
454
  // ../kit/src/help.ts
452
455
  import process8 from "process";
453
- var OPTIONAL = /\[[^\]]+\]/g;
456
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
454
457
  var USAGE_PREFIX = /^usage:\s*/i;
455
458
  var FULL_STOP = /\.$/;
456
459
  function usageLine(usage, colors = paint(process8.stdout)) {
457
460
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
458
461
  }
459
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
460
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
462
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
463
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
461
464
  `);
462
465
  }
463
466
  function exitRows(exits, colors = paint(process8.stdout)) {
464
467
  if (exits.length === 0)
465
468
  return [];
466
- const width = Math.max(...exits.map(([code]) => String(code).length));
467
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
468
- }
469
- function replacesRows(replaces, colors = paint(process8.stdout)) {
470
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
469
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
471
470
  }
472
471
  function wantsHelpJson(env = process8.env) {
473
472
  return env.KIT_HELP === "json";
@@ -493,29 +492,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
493
492
  return [];
494
493
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
495
494
  }
495
+ var MAX_INLINE_CHOICES = 24;
496
496
  function optionRows(options, colors = paint(process8.stdout)) {
497
497
  const rows = Object.entries(options).map(([name, option]) => {
498
498
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
499
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
499
+ const choices = option.choices?.join("|");
500
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
501
+ const named = inline ? `<${choices}>` : "<value>";
500
502
  const placeholder = option.optional === undefined ? named : `[${named}]`;
501
503
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
502
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
504
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
505
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
503
506
  });
504
507
  const width = Math.max(0, ...rows.map((row) => row.width));
505
508
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
506
509
  }
507
510
 
508
511
  // ../kit/src/text.ts
509
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
510
512
  function distance(a, b) {
511
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
512
- for (const [i, left] of [...a].entries()) {
513
+ const left = [...a];
514
+ const right = [...b];
515
+ let before = [];
516
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
517
+ for (const [i, x] of left.entries()) {
513
518
  const current = [i + 1];
514
- for (const [j, right] of [...b].entries())
515
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
519
+ for (const [j, y] of right.entries()) {
520
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
521
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
522
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
523
+ current.push(cost);
524
+ }
525
+ before = previous;
516
526
  previous = current;
517
527
  }
518
- return previous[b.length] ?? 0;
528
+ return previous[right.length] ?? 0;
519
529
  }
520
530
  function closest(name, names) {
521
531
  const started = names.find((known) => known.startsWith(name));
@@ -591,7 +601,7 @@ class Completing {
591
601
  }
592
602
  var completion = { active: false };
593
603
  var OUTPUT_OPTIONS = {
594
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
604
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
595
605
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
596
606
  };
597
607
  function applyOutput(color, plain, env = process9.env) {
@@ -763,9 +773,33 @@ function nearestOption(message, options, allowNegative) {
763
773
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
764
774
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
765
775
  }
776
+ // ../kit/src/argv.ts
777
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
778
+ import { resolve as resolve3 } from "path";
779
+ import process10 from "process";
780
+ function commandLine() {
781
+ try {
782
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
783
+ } catch {
784
+ return;
785
+ }
786
+ }
787
+ function realPath(word) {
788
+ try {
789
+ return realpathSync(resolve3(word));
790
+ } catch {
791
+ return;
792
+ }
793
+ }
794
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
795
+ const target = script === undefined ? undefined : realPath(script) ?? script;
796
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
797
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
798
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
799
+ }
766
800
  // ../kit/src/process.ts
767
801
  import { constants } from "os";
768
- import process10 from "process";
802
+ import process11 from "process";
769
803
  var KILL_GRACE_MS = 2000;
770
804
  function exitCodeOf(code, signal) {
771
805
  if (code !== null)
@@ -785,7 +819,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
785
819
  return;
786
820
  try {
787
821
  if (grouped)
788
- process10.kill(-proc.pid, killing);
822
+ process11.kill(-proc.pid, killing);
789
823
  else
790
824
  proc.kill(killing);
791
825
  } catch {}
@@ -859,15 +893,93 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
859
893
  var RESET_STYLE = `${ESC}[0m`;
860
894
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
861
895
  // ../kit/src/cli.ts
862
- import { readFileSync as readFileSync2, realpathSync } from "fs";
896
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
863
897
  import { dirname as dirname3, join as join5 } from "path";
898
+ import process14 from "process";
899
+
900
+ // ../kit/src/completions.ts
901
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
902
+ 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'
903
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
904
+ set -l current (commandline -ct)
905
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
906
+ if test "$line" = __files__
907
+ __fish_complete_path $current
908
+ else
909
+ echo $line
910
+ end
911
+ end
912
+ end`;
913
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
914
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
915
+ local -a lines
916
+ COMPREPLY=()
917
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
918
+ for line in "\${lines[@]}"; do
919
+ if [[ $line == __files__ ]]; then
920
+ COMPREPLY+=($(compgen -f -- "$cur"))
921
+ else
922
+ words+="\${line%%$'\\t'*}"$'\\n'
923
+ fi
924
+ done
925
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
926
+ }`;
927
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
928
+ local line
929
+ local -a described plain
930
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
931
+ if [[ $line == __files__ ]]; then
932
+ _files
933
+ elif [[ $line == *$'\\t'* ]]; then
934
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
935
+ else
936
+ plain+=("$line")
937
+ fi
938
+ done
939
+ (( \${#described} )) && _describe -V value described
940
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
941
+ return 0
942
+ }`;
943
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
944
+ if (shell === "fish")
945
+ return `${header}
946
+ ${FISH_FUNCTION}
947
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
948
+ `).join("")}`;
949
+ if (shell === "bash")
950
+ return `${header}
951
+ ${BASH_FUNCTION}
952
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
953
+ `;
954
+ return `${header}
955
+ ${ZSH_FUNCTION}
956
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
957
+ `;
958
+ }
959
+
960
+ // ../kit/src/notify.ts
864
961
  import process12 from "process";
962
+ var NOTIFY_AFTER_MS = 1e4;
963
+ var CANCELLED = 130;
964
+ function base64(text) {
965
+ return Buffer.from(text).toString("base64");
966
+ }
967
+ function notification(title, body, env = process12.env) {
968
+ const id = `kit${process12.pid}`;
969
+ 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\\`];
970
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
971
+ }
972
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
973
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
974
+ return;
975
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
976
+ }
865
977
 
866
978
  // ../kit/src/usage.ts
867
979
  import { appendFileSync, mkdirSync } from "fs";
868
980
  import { homedir as homedir3 } from "os";
869
981
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
870
- import process11 from "process";
982
+ import process13 from "process";
871
983
 
872
984
  // ../kit/src/logs.ts
873
985
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -881,14 +993,14 @@ var usageError;
881
993
  function noteUsageError(message) {
882
994
  usageError = message;
883
995
  }
884
- function stateHome(env = process11.env) {
996
+ function stateHome(env = process13.env) {
885
997
  const dir = env.XDG_STATE_HOME;
886
998
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
887
999
  }
888
- function usagePath(env = process11.env) {
1000
+ function usagePath(env = process13.env) {
889
1001
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
890
1002
  }
891
- function usageRecorded(env = process11.env) {
1003
+ function usageRecorded(env = process13.env) {
892
1004
  const off = env.KAYNOOO_CLI_NO_USAGE;
893
1005
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
894
1006
  }
@@ -902,7 +1014,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
902
1014
  usageError = undefined;
903
1015
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
904
1016
  }
905
- function recordUsage(entry, env = process11.env) {
1017
+ function recordUsage(entry, env = process13.env) {
906
1018
  if (!usageRecorded(env))
907
1019
  return;
908
1020
  try {
@@ -918,7 +1030,11 @@ var LEVEL_OPTIONS = {
918
1030
  ...OUTPUT_OPTIONS,
919
1031
  help: { type: "boolean", short: "h", description: "show this help" }
920
1032
  };
921
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1033
+ var TOP_OPTIONS = {
1034
+ ...LEVEL_OPTIONS,
1035
+ version: { type: "boolean", short: "v", description: "print the version" },
1036
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1037
+ };
922
1038
  async function commandRows(all, colors) {
923
1039
  const commands = shown(all);
924
1040
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -979,7 +1095,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
979
1095
  header(colors, summary),
980
1096
  "",
981
1097
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
982
- ...replacesRows(replaces, colors),
983
1098
  "",
984
1099
  ...await commandRows(commands, colors),
985
1100
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -993,8 +1108,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
993
1108
  `);
994
1109
  }
995
1110
  function printError(prefix, message, hint, cause) {
996
- const colors = paint(process12.stderr);
997
- const styled = takesControlCodes(process12.stderr);
1111
+ const colors = paint(process14.stderr);
1112
+ const styled = takesControlCodes(process14.stderr);
998
1113
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
999
1114
  const under = (label, text, tint) => text === undefined ? "" : `
1000
1115
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1037,11 +1152,11 @@ async function dispatch(level, typed, { version, redact }) {
1037
1152
  }
1038
1153
  }
1039
1154
  if (name === undefined && level.path.length > 1) {
1040
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stderr));
1155
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
1041
1156
  return 2;
1042
1157
  }
1043
1158
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1044
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stdout));
1159
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
1045
1160
  return 0;
1046
1161
  }
1047
1162
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1097,24 +1212,24 @@ function candidateLine(candidate) {
1097
1212
  }
1098
1213
  function positionalBeingTyped(before, { options, positionals }) {
1099
1214
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1100
- let index = 0;
1215
+ const typed = [];
1101
1216
  let at = 0;
1102
1217
  while (at < before.length) {
1103
1218
  const word = before[at];
1104
1219
  if (word === "--") {
1105
- index += before.length - at - 1;
1220
+ typed.push(...before.slice(at + 1));
1106
1221
  break;
1107
1222
  }
1108
1223
  if (!word.startsWith("-"))
1109
- index++;
1224
+ typed.push(word);
1110
1225
  else if (takesValue(word))
1111
1226
  at++;
1112
1227
  at++;
1113
1228
  }
1114
1229
  const last = positionals.at(-1);
1115
- if (index < positionals.length)
1116
- return positionals[index];
1117
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1230
+ if (typed.length < positionals.length)
1231
+ return { name: positionals[typed.length], typed };
1232
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1118
1233
  }
1119
1234
  async function leafCandidates(run, words) {
1120
1235
  const completing = await completingOf(run);
@@ -1122,12 +1237,12 @@ async function leafCandidates(run, words) {
1122
1237
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1123
1238
  const flag = words.at(-2);
1124
1239
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1240
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1125
1241
  if (option?.type === "string") {
1126
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1242
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1127
1243
  return values === undefined ? [FILES] : values.map(candidateLine);
1128
1244
  }
1129
- const name = positionalBeingTyped(words.slice(0, -1), completing);
1130
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1245
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1131
1246
  return values === undefined ? [FILES] : values.map(candidateLine);
1132
1247
  }
1133
1248
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -1152,15 +1267,32 @@ async function candidates(scope, defaultCommand, words, before = []) {
1152
1267
  }
1153
1268
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1154
1269
  }
1270
+ var COMPLETIONS = "--completions";
1271
+ function flagValue([flag = "", ...rest]) {
1272
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1273
+ }
1274
+ function printCompletionScript(name, args) {
1275
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1276
+ if (shell === undefined || args.length !== 1) {
1277
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1278
+ return 2;
1279
+ }
1280
+ console.log(completionScript(shell, [name]).trimEnd());
1281
+ return 0;
1282
+ }
1155
1283
  async function printCandidates(found) {
1156
1284
  for (const line of await found)
1157
1285
  console.log(line);
1158
1286
  return 0;
1159
1287
  }
1160
1288
  function packageVersion(entry = Bun.main) {
1161
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1289
+ let resolved = entry;
1290
+ try {
1291
+ resolved = realpathSync2(entry);
1292
+ } catch {}
1293
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1162
1294
  try {
1163
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
1295
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1164
1296
  if (typeof version === "string")
1165
1297
  return version;
1166
1298
  } catch {}
@@ -1168,14 +1300,19 @@ function packageVersion(entry = Bun.main) {
1168
1300
  return "0.0.0";
1169
1301
  }
1170
1302
  }
1171
- async function runCli(cli, argv = process12.argv.slice(2)) {
1303
+ async function runCli(cli, argv = scriptArgs()) {
1172
1304
  const version = cli.version ?? packageVersion();
1173
1305
  if (argv[0] === COMPLETE)
1174
1306
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1307
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1308
+ return printCompletionScript(cli.name, flagValue(argv));
1309
+ const started = performance.now();
1175
1310
  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 });
1311
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1312
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1176
1313
  if (cli.usage !== false) {
1177
1314
  try {
1178
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1315
+ recordUsage(usageEntry(cli.name, command, argv, code));
1179
1316
  } catch {}
1180
1317
  }
1181
1318
  return code;
@@ -1195,19 +1332,23 @@ function commandPath(scope, argv) {
1195
1332
  }
1196
1333
  return path.length === 0 ? undefined : path.join(" ");
1197
1334
  }
1198
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1335
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1199
1336
  if (argv[0] === COMPLETE)
1200
1337
  return printCandidates(leafCandidates(run, argv.slice(1)));
1338
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1339
+ return printCompletionScript(name, flagValue(argv));
1201
1340
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1202
1341
  console.log(version ?? packageVersion());
1203
1342
  return 0;
1204
1343
  }
1205
1344
  let code;
1345
+ const started = performance.now();
1206
1346
  try {
1207
1347
  code = await run(argv);
1208
1348
  } catch (error) {
1209
1349
  code = reportThrown(name, error, redact, wantsJson(argv));
1210
1350
  }
1351
+ notifyEnd(name, code, performance.now() - started);
1211
1352
  if (usage !== false) {
1212
1353
  try {
1213
1354
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1239,7 +1380,7 @@ function parseSize(text, bareUnit = 1) {
1239
1380
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1240
1381
  }
1241
1382
  // ../kit/src/watch.ts
1242
- import process13 from "process";
1383
+ import process15 from "process";
1243
1384
  import { format } from "util";
1244
1385
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1245
1386
  var DEFAULT_SECONDS = 2;
@@ -1261,7 +1402,7 @@ function withoutWatch(args) {
1261
1402
  }
1262
1403
  return rest;
1263
1404
  }
1264
- async function watching(value, step, stream = process13.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1405
+ async function watching(value, step, stream = process15.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1265
1406
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1266
1407
  if (!takesControlCodes(stream))
1267
1408
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1269,12 +1410,12 @@ async function watching(value, step, stream = process13.stdout, sleep = Bun.slee
1269
1410
  for (let round = 0;round < rounds; round++) {
1270
1411
  const held = [];
1271
1412
  const { log, info } = console;
1272
- const write = process13.stdout.write.bind(process13.stdout);
1413
+ const write = process15.stdout.write.bind(process15.stdout);
1273
1414
  const hold = (...parts) => void held.push(`${format(...parts)}
1274
1415
  `);
1275
1416
  console.log = hold;
1276
1417
  console.info = hold;
1277
- process13.stdout.write = (text) => {
1418
+ process15.stdout.write = (text) => {
1278
1419
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1279
1420
  return true;
1280
1421
  };
@@ -1283,7 +1424,7 @@ async function watching(value, step, stream = process13.stdout, sleep = Bun.slee
1283
1424
  } finally {
1284
1425
  console.log = log;
1285
1426
  console.info = info;
1286
- process13.stdout.write = write;
1427
+ process15.stdout.write = write;
1287
1428
  }
1288
1429
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1289
1430
  await sleep(interval);
@@ -1291,7 +1432,7 @@ async function watching(value, step, stream = process13.stdout, sleep = Bun.slee
1291
1432
  return code;
1292
1433
  }
1293
1434
  // src/pid.ts
1294
- import process15 from "process";
1435
+ import process17 from "process";
1295
1436
 
1296
1437
  // src/mask.ts
1297
1438
  import { basename } from "path";
@@ -1584,10 +1725,22 @@ async function socketsOf(pid, root = "/proc") {
1584
1725
  return inodes;
1585
1726
  }
1586
1727
  async function socketOwners(root = "/proc") {
1587
- const owners = new Map;
1728
+ const holders = new Map;
1588
1729
  for (const pid of await listPids(root)) {
1589
1730
  for (const inode of await socketsOf(pid, root))
1590
- owners.set(inode, pid);
1731
+ holders.set(inode, [...holders.get(inode) ?? [], pid]);
1732
+ }
1733
+ const owners = new Map;
1734
+ const parents = new Map;
1735
+ for (const [inode, pids] of holders) {
1736
+ const [first = 0] = pids;
1737
+ if (pids.length > 1) {
1738
+ for (const pid of pids) {
1739
+ if (!parents.has(pid))
1740
+ parents.set(pid, parseStat(await text2(`${root}/${pid}/stat`) ?? "")?.ppid);
1741
+ }
1742
+ }
1743
+ owners.set(inode, pids.find((pid) => !pids.includes(parents.get(pid) ?? -1)) ?? first);
1591
1744
  }
1592
1745
  return owners;
1593
1746
  }
@@ -1608,9 +1761,8 @@ async function userName(uid) {
1608
1761
  var usage2 = `pid <pid>
1609
1762
 
1610
1763
  Shows what a process is: its executable, working directory, command line, parent chain up to init, user, start time and age, memory, open files and limits, the TCP and UDP ports it listens on and its cgroup. Everything is read from /proc; what the calling user cannot read of another user's process is left out and named at the end.
1611
- The environment is not shown unless --env is given, with every value that looks like a secret masked.
1612
-
1613
- Exits 0 when it showed the process, 1 when no process has this pid, 2 on a usage error.`;
1764
+ The environment is not shown unless --env is given, with every value that looks like a secret masked.`;
1765
+ var EXITS = [[0, "it showed the process"], [1, "no process has this pid"], [2, "a usage error"]];
1614
1766
  var DIGITS2 = /^\d+$/;
1615
1767
  var options = {
1616
1768
  env: { type: "boolean", description: "show the environment, secrets masked" },
@@ -1682,7 +1834,7 @@ function limitLine(limits, name) {
1682
1834
  return limit === undefined ? "-" : `soft ${limit.soft}, hard ${limit.hard}`;
1683
1835
  }
1684
1836
  function render(info, showEnv) {
1685
- const colors = paint(process15.stdout);
1837
+ const colors = paint(process17.stdout);
1686
1838
  const memory = info.memory;
1687
1839
  const size = (bytes) => bytes === undefined ? "-" : tt(bytes);
1688
1840
  const rows = [
@@ -1712,6 +1864,7 @@ function render(info, showEnv) {
1712
1864
  }
1713
1865
  async function pid(args) {
1714
1866
  const { values, positionals } = parse(args, usage2, options, {
1867
+ exits: EXITS,
1715
1868
  positionals: ["<pid>"],
1716
1869
  replaces: "cat /proc/<pid>/{cmdline,environ,limits}, readlink /proc/<pid>/{exe,cwd}, the fish pid function",
1717
1870
  examples: [
@@ -1734,4 +1887,4 @@ async function pid(args) {
1734
1887
  }
1735
1888
 
1736
1889
  // src/pid-cli.ts
1737
- process16.exitCode = await runMain({ name: "pid", run: pid });
1890
+ process18.exitCode = await runMain({ name: "pid", run: pid });