@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/ports-cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/ports-cli.ts
5
- import process17 from "process";
5
+ import process20 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -365,6 +365,9 @@ function formatSeconds(total) {
365
365
  const next = amounts[first + 1];
366
366
  return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
367
367
  }
368
+ function formatDuration(ms) {
369
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
370
+ }
368
371
  function upTo(text, separator) {
369
372
  const end = text.indexOf(separator);
370
373
  return end === -1 ? text : text.slice(0, end);
@@ -425,24 +428,20 @@ function printJson(value) {
425
428
 
426
429
  // ../kit/src/help.ts
427
430
  import process8 from "process";
428
- var OPTIONAL = /\[[^\]]+\]/g;
431
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
429
432
  var USAGE_PREFIX = /^usage:\s*/i;
430
433
  var FULL_STOP = /\.$/;
431
434
  function usageLine(usage, colors = paint(process8.stdout)) {
432
435
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
433
436
  }
434
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
435
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
437
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
438
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
436
439
  `);
437
440
  }
438
441
  function exitRows(exits, colors = paint(process8.stdout)) {
439
442
  if (exits.length === 0)
440
443
  return [];
441
- const width = Math.max(...exits.map(([code]) => String(code).length));
442
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
443
- }
444
- function replacesRows(replaces, colors = paint(process8.stdout)) {
445
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
444
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
446
445
  }
447
446
  function wantsHelpJson(env = process8.env) {
448
447
  return env.KIT_HELP === "json";
@@ -468,29 +467,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
468
467
  return [];
469
468
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
470
469
  }
470
+ var MAX_INLINE_CHOICES = 24;
471
471
  function optionRows(options, colors = paint(process8.stdout)) {
472
472
  const rows = Object.entries(options).map(([name, option]) => {
473
473
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
474
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
474
+ const choices = option.choices?.join("|");
475
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
476
+ const named = inline ? `<${choices}>` : "<value>";
475
477
  const placeholder = option.optional === undefined ? named : `[${named}]`;
476
478
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
477
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
479
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
480
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
478
481
  });
479
482
  const width = Math.max(0, ...rows.map((row) => row.width));
480
483
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
481
484
  }
482
485
 
483
486
  // ../kit/src/text.ts
484
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
485
487
  function distance(a, b) {
486
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
487
- for (const [i, left] of [...a].entries()) {
488
+ const left = [...a];
489
+ const right = [...b];
490
+ let before = [];
491
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
492
+ for (const [i, x] of left.entries()) {
488
493
  const current = [i + 1];
489
- for (const [j, right] of [...b].entries())
490
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
494
+ for (const [j, y] of right.entries()) {
495
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
496
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
497
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
498
+ current.push(cost);
499
+ }
500
+ before = previous;
491
501
  previous = current;
492
502
  }
493
- return previous[b.length] ?? 0;
503
+ return previous[right.length] ?? 0;
494
504
  }
495
505
  function closest(name, names) {
496
506
  const started = names.find((known) => known.startsWith(name));
@@ -566,7 +576,7 @@ class Completing {
566
576
  }
567
577
  var completion = { active: false };
568
578
  var OUTPUT_OPTIONS = {
569
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
579
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
570
580
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
571
581
  };
572
582
  function applyOutput(color, plain, env = process9.env) {
@@ -738,9 +748,33 @@ function nearestOption(message, options, allowNegative) {
738
748
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
739
749
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
740
750
  }
751
+ // ../kit/src/argv.ts
752
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
753
+ import { resolve as resolve3 } from "path";
754
+ import process10 from "process";
755
+ function commandLine() {
756
+ try {
757
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
758
+ } catch {
759
+ return;
760
+ }
761
+ }
762
+ function realPath(word) {
763
+ try {
764
+ return realpathSync(resolve3(word));
765
+ } catch {
766
+ return;
767
+ }
768
+ }
769
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
770
+ const target = script === undefined ? undefined : realPath(script) ?? script;
771
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
772
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
773
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
774
+ }
741
775
  // ../kit/src/process.ts
742
776
  import { constants } from "os";
743
- import process10 from "process";
777
+ import process11 from "process";
744
778
  var KILL_GRACE_MS = 2000;
745
779
  function exitCodeOf(code, signal) {
746
780
  if (code !== null)
@@ -760,7 +794,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
760
794
  return;
761
795
  try {
762
796
  if (grouped)
763
- process10.kill(-proc.pid, killing);
797
+ process11.kill(-proc.pid, killing);
764
798
  else
765
799
  proc.kill(killing);
766
800
  } catch {}
@@ -834,15 +868,93 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
834
868
  var RESET_STYLE = `${ESC}[0m`;
835
869
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
836
870
  // ../kit/src/cli.ts
837
- import { readFileSync as readFileSync2, realpathSync } from "fs";
871
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
838
872
  import { dirname as dirname3, join as join5 } from "path";
873
+ import process14 from "process";
874
+
875
+ // ../kit/src/completions.ts
876
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
877
+ 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'
878
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
879
+ set -l current (commandline -ct)
880
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
881
+ if test "$line" = __files__
882
+ __fish_complete_path $current
883
+ else
884
+ echo $line
885
+ end
886
+ end
887
+ end`;
888
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
889
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
890
+ local -a lines
891
+ COMPREPLY=()
892
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
893
+ for line in "\${lines[@]}"; do
894
+ if [[ $line == __files__ ]]; then
895
+ COMPREPLY+=($(compgen -f -- "$cur"))
896
+ else
897
+ words+="\${line%%$'\\t'*}"$'\\n'
898
+ fi
899
+ done
900
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
901
+ }`;
902
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
903
+ local line
904
+ local -a described plain
905
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
906
+ if [[ $line == __files__ ]]; then
907
+ _files
908
+ elif [[ $line == *$'\\t'* ]]; then
909
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
910
+ else
911
+ plain+=("$line")
912
+ fi
913
+ done
914
+ (( \${#described} )) && _describe -V value described
915
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
916
+ return 0
917
+ }`;
918
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
919
+ if (shell === "fish")
920
+ return `${header}
921
+ ${FISH_FUNCTION}
922
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
923
+ `).join("")}`;
924
+ if (shell === "bash")
925
+ return `${header}
926
+ ${BASH_FUNCTION}
927
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
928
+ `;
929
+ return `${header}
930
+ ${ZSH_FUNCTION}
931
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
932
+ `;
933
+ }
934
+
935
+ // ../kit/src/notify.ts
839
936
  import process12 from "process";
937
+ var NOTIFY_AFTER_MS = 1e4;
938
+ var CANCELLED = 130;
939
+ function base64(text) {
940
+ return Buffer.from(text).toString("base64");
941
+ }
942
+ function notification(title, body, env = process12.env) {
943
+ const id = `kit${process12.pid}`;
944
+ 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\\`];
945
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
946
+ }
947
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
948
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
949
+ return;
950
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
951
+ }
840
952
 
841
953
  // ../kit/src/usage.ts
842
954
  import { appendFileSync, mkdirSync } from "fs";
843
955
  import { homedir as homedir3 } from "os";
844
956
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
845
- import process11 from "process";
957
+ import process13 from "process";
846
958
 
847
959
  // ../kit/src/logs.ts
848
960
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -856,14 +968,14 @@ var usageError;
856
968
  function noteUsageError(message) {
857
969
  usageError = message;
858
970
  }
859
- function stateHome(env = process11.env) {
971
+ function stateHome(env = process13.env) {
860
972
  const dir = env.XDG_STATE_HOME;
861
973
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
862
974
  }
863
- function usagePath(env = process11.env) {
975
+ function usagePath(env = process13.env) {
864
976
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
865
977
  }
866
- function usageRecorded(env = process11.env) {
978
+ function usageRecorded(env = process13.env) {
867
979
  const off = env.KAYNOOO_CLI_NO_USAGE;
868
980
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
869
981
  }
@@ -877,7 +989,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
877
989
  usageError = undefined;
878
990
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
879
991
  }
880
- function recordUsage(entry, env = process11.env) {
992
+ function recordUsage(entry, env = process13.env) {
881
993
  if (!usageRecorded(env))
882
994
  return;
883
995
  try {
@@ -893,7 +1005,11 @@ var LEVEL_OPTIONS = {
893
1005
  ...OUTPUT_OPTIONS,
894
1006
  help: { type: "boolean", short: "h", description: "show this help" }
895
1007
  };
896
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1008
+ var TOP_OPTIONS = {
1009
+ ...LEVEL_OPTIONS,
1010
+ version: { type: "boolean", short: "v", description: "print the version" },
1011
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1012
+ };
897
1013
  async function commandRows(all, colors) {
898
1014
  const commands = shown(all);
899
1015
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -954,7 +1070,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
954
1070
  header(colors, summary),
955
1071
  "",
956
1072
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
957
- ...replacesRows(replaces, colors),
958
1073
  "",
959
1074
  ...await commandRows(commands, colors),
960
1075
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -968,8 +1083,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
968
1083
  `);
969
1084
  }
970
1085
  function printError(prefix, message, hint, cause) {
971
- const colors = paint(process12.stderr);
972
- const styled = takesControlCodes(process12.stderr);
1086
+ const colors = paint(process14.stderr);
1087
+ const styled = takesControlCodes(process14.stderr);
973
1088
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
974
1089
  const under = (label, text, tint) => text === undefined ? "" : `
975
1090
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1012,11 +1127,11 @@ async function dispatch(level, typed, { version, redact }) {
1012
1127
  }
1013
1128
  }
1014
1129
  if (name === undefined && level.path.length > 1) {
1015
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stderr));
1130
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
1016
1131
  return 2;
1017
1132
  }
1018
1133
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1019
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stdout));
1134
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
1020
1135
  return 0;
1021
1136
  }
1022
1137
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1072,24 +1187,24 @@ function candidateLine(candidate) {
1072
1187
  }
1073
1188
  function positionalBeingTyped(before, { options, positionals }) {
1074
1189
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1075
- let index = 0;
1190
+ const typed = [];
1076
1191
  let at = 0;
1077
1192
  while (at < before.length) {
1078
1193
  const word = before[at];
1079
1194
  if (word === "--") {
1080
- index += before.length - at - 1;
1195
+ typed.push(...before.slice(at + 1));
1081
1196
  break;
1082
1197
  }
1083
1198
  if (!word.startsWith("-"))
1084
- index++;
1199
+ typed.push(word);
1085
1200
  else if (takesValue(word))
1086
1201
  at++;
1087
1202
  at++;
1088
1203
  }
1089
1204
  const last = positionals.at(-1);
1090
- if (index < positionals.length)
1091
- return positionals[index];
1092
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1205
+ if (typed.length < positionals.length)
1206
+ return { name: positionals[typed.length], typed };
1207
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1093
1208
  }
1094
1209
  async function leafCandidates(run, words) {
1095
1210
  const completing = await completingOf(run);
@@ -1097,12 +1212,12 @@ async function leafCandidates(run, words) {
1097
1212
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1098
1213
  const flag = words.at(-2);
1099
1214
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1215
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1100
1216
  if (option?.type === "string") {
1101
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1217
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1102
1218
  return values === undefined ? [FILES] : values.map(candidateLine);
1103
1219
  }
1104
- const name = positionalBeingTyped(words.slice(0, -1), completing);
1105
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1220
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1106
1221
  return values === undefined ? [FILES] : values.map(candidateLine);
1107
1222
  }
1108
1223
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -1127,15 +1242,32 @@ async function candidates(scope, defaultCommand, words, before = []) {
1127
1242
  }
1128
1243
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1129
1244
  }
1245
+ var COMPLETIONS = "--completions";
1246
+ function flagValue([flag = "", ...rest]) {
1247
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1248
+ }
1249
+ function printCompletionScript(name, args) {
1250
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1251
+ if (shell === undefined || args.length !== 1) {
1252
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1253
+ return 2;
1254
+ }
1255
+ console.log(completionScript(shell, [name]).trimEnd());
1256
+ return 0;
1257
+ }
1130
1258
  async function printCandidates(found) {
1131
1259
  for (const line of await found)
1132
1260
  console.log(line);
1133
1261
  return 0;
1134
1262
  }
1135
1263
  function packageVersion(entry = Bun.main) {
1136
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1264
+ let resolved = entry;
1265
+ try {
1266
+ resolved = realpathSync2(entry);
1267
+ } catch {}
1268
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1137
1269
  try {
1138
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
1270
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1139
1271
  if (typeof version === "string")
1140
1272
  return version;
1141
1273
  } catch {}
@@ -1143,14 +1275,19 @@ function packageVersion(entry = Bun.main) {
1143
1275
  return "0.0.0";
1144
1276
  }
1145
1277
  }
1146
- async function runCli(cli, argv = process12.argv.slice(2)) {
1278
+ async function runCli(cli, argv = scriptArgs()) {
1147
1279
  const version = cli.version ?? packageVersion();
1148
1280
  if (argv[0] === COMPLETE)
1149
1281
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1282
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1283
+ return printCompletionScript(cli.name, flagValue(argv));
1284
+ const started = performance.now();
1150
1285
  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 });
1286
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1287
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1151
1288
  if (cli.usage !== false) {
1152
1289
  try {
1153
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1290
+ recordUsage(usageEntry(cli.name, command, argv, code));
1154
1291
  } catch {}
1155
1292
  }
1156
1293
  return code;
@@ -1170,19 +1307,23 @@ function commandPath(scope, argv) {
1170
1307
  }
1171
1308
  return path.length === 0 ? undefined : path.join(" ");
1172
1309
  }
1173
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1310
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1174
1311
  if (argv[0] === COMPLETE)
1175
1312
  return printCandidates(leafCandidates(run, argv.slice(1)));
1313
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1314
+ return printCompletionScript(name, flagValue(argv));
1176
1315
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1177
1316
  console.log(version ?? packageVersion());
1178
1317
  return 0;
1179
1318
  }
1180
1319
  let code;
1320
+ const started = performance.now();
1181
1321
  try {
1182
1322
  code = await run(argv);
1183
1323
  } catch (error) {
1184
1324
  code = reportThrown(name, error, redact, wantsJson(argv));
1185
1325
  }
1326
+ notifyEnd(name, code, performance.now() - started);
1186
1327
  if (usage !== false) {
1187
1328
  try {
1188
1329
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1214,7 +1355,7 @@ function parseSize(text, bareUnit = 1) {
1214
1355
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1215
1356
  }
1216
1357
  // ../kit/src/watch.ts
1217
- import process13 from "process";
1358
+ import process15 from "process";
1218
1359
  import { format } from "util";
1219
1360
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1220
1361
  var DEFAULT_SECONDS = 2;
@@ -1236,7 +1377,7 @@ function withoutWatch(args) {
1236
1377
  }
1237
1378
  return rest;
1238
1379
  }
1239
- async function watching(value, step, stream = process13.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1380
+ async function watching(value, step, stream = process15.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1240
1381
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1241
1382
  if (!takesControlCodes(stream))
1242
1383
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1244,12 +1385,12 @@ async function watching(value, step, stream = process13.stdout, sleep = Bun.slee
1244
1385
  for (let round = 0;round < rounds; round++) {
1245
1386
  const held = [];
1246
1387
  const { log, info } = console;
1247
- const write = process13.stdout.write.bind(process13.stdout);
1388
+ const write = process15.stdout.write.bind(process15.stdout);
1248
1389
  const hold = (...parts) => void held.push(`${format(...parts)}
1249
1390
  `);
1250
1391
  console.log = hold;
1251
1392
  console.info = hold;
1252
- process13.stdout.write = (text) => {
1393
+ process15.stdout.write = (text) => {
1253
1394
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1254
1395
  return true;
1255
1396
  };
@@ -1258,7 +1399,7 @@ async function watching(value, step, stream = process13.stdout, sleep = Bun.slee
1258
1399
  } finally {
1259
1400
  console.log = log;
1260
1401
  console.info = info;
1261
- process13.stdout.write = write;
1402
+ process15.stdout.write = write;
1262
1403
  }
1263
1404
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1264
1405
  await sleep(interval);
@@ -1267,10 +1408,24 @@ async function watching(value, step, stream = process13.stdout, sleep = Bun.slee
1267
1408
  }
1268
1409
  // src/ports.ts
1269
1410
  import { basename as basename2 } from "path";
1270
- import process16 from "process";
1411
+ import process19 from "process";
1271
1412
 
1272
1413
  // ../kit/src/prompt.ts
1273
- import process15 from "process";
1414
+ import process18 from "process";
1415
+
1416
+ // ../kit/src/job.ts
1417
+ import process17 from "process";
1418
+ function stopJob() {
1419
+ process17.kill(0, "SIGTSTP");
1420
+ }
1421
+
1422
+ // ../kit/src/picker/line.ts
1423
+ var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
1424
+ var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
1425
+ var FORWARD_KILLS = new Set(["killnext", "killend"]);
1426
+ function isEditKey(key) {
1427
+ return EDIT_KEYS.has(key);
1428
+ }
1274
1429
 
1275
1430
  // ../kit/src/picker/score.ts
1276
1431
  var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
@@ -1302,10 +1457,29 @@ var KEYS = {
1302
1457
  "\n": "enter",
1303
1458
  "\x03": "cancel",
1304
1459
  "\x1B": "cancel",
1460
+ "\x1B[D": "left",
1461
+ "\x1BOD": "left",
1462
+ "\x1B[C": "right",
1463
+ "\x1BOC": "right",
1464
+ "\x1B[1;5D": "wordleft",
1465
+ "\x1B[1;3D": "wordleft",
1466
+ "\x1Bb": "wordleft",
1467
+ "\x1B[1;5C": "wordright",
1468
+ "\x1B[1;3C": "wordright",
1469
+ "\x1Bf": "wordright",
1470
+ "\x01": "linestart",
1471
+ "\x05": "lineend",
1305
1472
  "\x7F": "erase",
1306
- "\b": "erase",
1473
+ "\x1B[3~": "delete",
1474
+ "\b": "killword",
1475
+ "\x1B\x7F": "killword",
1476
+ "\x1B[3;5~": "killnext",
1477
+ "\x1Bd": "killnext",
1307
1478
  "\x15": "clear",
1479
+ "\v": "killend",
1308
1480
  "\x17": "word",
1481
+ "\x19": "yank",
1482
+ "\x1A": "suspend",
1309
1483
  "\t": "tab",
1310
1484
  "\x1F": "help",
1311
1485
  "\x1BOP": "help",
@@ -1335,10 +1509,21 @@ function parseKeys(input, paste = { active: false }, ctrls = []) {
1335
1509
  });
1336
1510
  }
1337
1511
 
1512
+ // ../kit/src/redraw.ts
1513
+ var SYNC_START = "\x1B[?2026h";
1514
+ var SYNC_END = "\x1B[?2026l";
1515
+ function overwrite(lines, columns) {
1516
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1517
+ `);
1518
+ }
1519
+ function rowsTaken(lines, columns) {
1520
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1521
+ }
1522
+
1338
1523
  // ../kit/src/prompt.ts
1339
- var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "erase"]);
1524
+ var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
1340
1525
  function readKeys(input, paste = { active: false }) {
1341
- return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key));
1526
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
1342
1527
  }
1343
1528
  async function confirm(question, { default: fallback, ...settings } = {}) {
1344
1529
  let answered = fallback;
@@ -1362,7 +1547,7 @@ function asking(colors, question, typed, keys) {
1362
1547
  function answer(colors, question, state, picked) {
1363
1548
  return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1364
1549
  }
1365
- async function ask(question, { hint, terminal = process15 }, render, press) {
1550
+ async function ask(question, { hint, terminal = process18 }, render, press) {
1366
1551
  const { stdin, stderr } = terminal;
1367
1552
  if (!isInteractive(terminal))
1368
1553
  fail(`cannot ask "${question}" off a terminal`, 2, hint);
@@ -1372,12 +1557,22 @@ async function ask(question, { hint, terminal = process15 }, render, press) {
1372
1557
  const columns = () => stderr.columns || 80;
1373
1558
  const draw = (state, last = false) => {
1374
1559
  const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1375
- stderr.write(`\r\x1B[0J${frame.join(`
1376
- `)}${last || frame.length < 2 ? "" : `\x1B[${frame.length - 1}A`}${last ? "" : "\r"}`);
1560
+ const rows = rowsTaken(frame, columns());
1561
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
1377
1562
  current = state;
1378
1563
  };
1379
1564
  const redraw = () => draw(current);
1380
1565
  const paste = { active: false };
1566
+ const stop = terminal.stop ?? (terminal === process18 ? stopJob : undefined);
1567
+ const suspend = () => {
1568
+ if (stop === undefined)
1569
+ return;
1570
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
1571
+ stdin.setRawMode(false);
1572
+ stop();
1573
+ stdin.setRawMode(true);
1574
+ stderr.write("\x1B[?25l\x1B[?2004h");
1575
+ };
1381
1576
  try {
1382
1577
  stderr.on?.("resize", redraw);
1383
1578
  stdin.setRawMode(true);
@@ -1387,6 +1582,10 @@ async function ask(question, { hint, terminal = process15 }, render, press) {
1387
1582
  return await new Promise((resolve) => {
1388
1583
  function onData(data) {
1389
1584
  for (const key of readKeys(data.toString(), paste)) {
1585
+ if (key === "suspend") {
1586
+ suspend();
1587
+ continue;
1588
+ }
1390
1589
  const pressed = press(key);
1391
1590
  if (pressed !== undefined) {
1392
1591
  settle(pressed);
@@ -1673,10 +1872,22 @@ async function socketsOf(pid, root = "/proc") {
1673
1872
  return inodes;
1674
1873
  }
1675
1874
  async function socketOwners(root = "/proc") {
1676
- const owners = new Map;
1875
+ const holders = new Map;
1677
1876
  for (const pid of await listPids(root)) {
1678
1877
  for (const inode of await socketsOf(pid, root))
1679
- owners.set(inode, pid);
1878
+ holders.set(inode, [...holders.get(inode) ?? [], pid]);
1879
+ }
1880
+ const owners = new Map;
1881
+ const parents = new Map;
1882
+ for (const [inode, pids] of holders) {
1883
+ const [first = 0] = pids;
1884
+ if (pids.length > 1) {
1885
+ for (const pid of pids) {
1886
+ if (!parents.has(pid))
1887
+ parents.set(pid, parseStat(await text2(`${root}/${pid}/stat`) ?? "")?.ppid);
1888
+ }
1889
+ }
1890
+ owners.set(inode, pids.find((pid) => !pids.includes(parents.get(pid) ?? -1)) ?? first);
1680
1891
  }
1681
1892
  return owners;
1682
1893
  }
@@ -1808,9 +2019,8 @@ var usage2 = `ports [port]
1808
2019
 
1809
2020
  Lists what listens on this machine, TCP and UDP over IPv4 and IPv6, one row per port with its bound address, the owning process, its command and its working directory. A port Docker publishes is held by docker-proxy, and shows as its compose project and service when docker is installed; the owner of a socket of another user cannot be read and shows as -.
1810
2021
  \`ports <port>\` keeps that port alone and exits 1 when nothing listens on it.
1811
- \`ports <port> --kill\` stops its owner with SIGTERM, and with --force SIGKILL once --grace has passed, after asking on a terminal unless --yes is given. It refuses processes of other users, pid 1, this command and its ancestors, and docker-proxy, for which it names the container to stop instead.
1812
-
1813
- Exits 0 when it listed or stopped, 1 when nothing listens on the given port or the owner could not be stopped, 2 on a usage error.`;
2022
+ \`ports <port> --kill\` stops its owner with SIGTERM, and with --force SIGKILL once --grace has passed, after asking on a terminal unless --yes is given. It refuses processes of other users, pid 1, this command and its ancestors, and docker-proxy, for which it names the container to stop instead.`;
2023
+ var EXITS = [[0, "it listed or stopped"], [1, "nothing listens on the given port or the owner could not be stopped"], [2, "a usage error"]];
1814
2024
  var options = {
1815
2025
  json: jsonOption("[{ port, protocol, addresses, pid, command, cwd, container }]"),
1816
2026
  kill: { type: "boolean", conflicts: ["watch"], description: "stop the owner of the given port" },
@@ -1859,7 +2069,7 @@ function refusal(row, proc, guard) {
1859
2069
  return reason === undefined ? undefined : `pid ${row.pid} is ${reason}`;
1860
2070
  }
1861
2071
  function render(rows) {
1862
- const colors = paint(process16.stdout);
2072
+ const colors = paint(process19.stdout);
1863
2073
  const cells = rows.map((row) => [
1864
2074
  colors.cyan(String(row.port)),
1865
2075
  row.protocol,
@@ -1871,7 +2081,7 @@ function render(rows) {
1871
2081
  return table([["PORT", "PROTO", "ADDRESS", "PID", "COMMAND", "CWD"], ...cells], { header: true });
1872
2082
  }
1873
2083
  async function stop(port, rows, procs, values) {
1874
- const guard = { uid: process16.getuid?.() ?? -1, mine: new Set(ancestry(process16.pid, procs)) };
2084
+ const guard = { uid: process19.getuid?.() ?? -1, mine: new Set(ancestry(process19.pid, procs)) };
1875
2085
  const targets = new Map;
1876
2086
  for (const row of rows) {
1877
2087
  const reason = refusal(row, row.pid === undefined ? undefined : procs.get(row.pid), guard);
@@ -1884,7 +2094,7 @@ async function stop(port, rows, procs, values) {
1884
2094
  return 1;
1885
2095
  const names = [...targets].map(([pid, row]) => `${pid} (${truncate(row.command ?? "", 40)})`).join(", ");
1886
2096
  if (values.yes !== true) {
1887
- if (!process16.stdin.isTTY)
2097
+ if (!process19.stdin.isTTY)
1888
2098
  fail(`stopping ${names} needs a terminal to ask on: pass --yes`, 2);
1889
2099
  if (await confirm(`Stop ${names}?`, { default: false }) !== true)
1890
2100
  return 1;
@@ -1898,6 +2108,7 @@ async function stop(port, rows, procs, values) {
1898
2108
  }
1899
2109
  async function ports(args) {
1900
2110
  const { values, positionals } = parse(args, usage2, options, {
2111
+ exits: EXITS,
1901
2112
  positionals: ["[port]"],
1902
2113
  replaces: "ss -ltnp | grep, lsof -i, fuser -k and lookups of docker-proxy by hand",
1903
2114
  examples: [
@@ -1915,7 +2126,7 @@ async function ports(args) {
1915
2126
  badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`);
1916
2127
  if (values.kill === true && port === undefined)
1917
2128
  badUsage("--kill takes the port to free: ports <port> --kill");
1918
- const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process16.getuid?.())]);
2129
+ const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process19.getuid?.())]);
1919
2130
  const byPid = new Map(procs.map((proc) => [proc.pid, proc]));
1920
2131
  const wanted = sockets.filter((socket) => port === undefined || socket.port === port);
1921
2132
  const needsDocker = wanted.some((socket) => {
@@ -1936,9 +2147,9 @@ async function ports(args) {
1936
2147
  console.log(render(rows));
1937
2148
  const unknown = rows.filter((row) => row.pid === undefined && row.container === undefined).length;
1938
2149
  if (unknown > 0)
1939
- console.error(paint(process16.stderr).dim(`${unknown} ${unknown === 1 ? "port has" : "ports have"} an owner this user cannot read, shown as -`));
2150
+ console.error(paint(process19.stderr).dim(`${unknown} ${unknown === 1 ? "port has" : "ports have"} an owner this user cannot read, shown as -`));
1940
2151
  return 0;
1941
2152
  }
1942
2153
 
1943
2154
  // src/ports-cli.ts
1944
- process17.exitCode = await runMain({ name: "ports", run: ports });
2155
+ process20.exitCode = await runMain({ name: "ports", run: ports });