@kaynooo/cli-proc 0.7.2 → 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 process18 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,7 +428,7 @@ 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)) {
@@ -464,29 +467,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
464
467
  return [];
465
468
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
466
469
  }
470
+ var MAX_INLINE_CHOICES = 24;
467
471
  function optionRows(options, colors = paint(process8.stdout)) {
468
472
  const rows = Object.entries(options).map(([name, option]) => {
469
473
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
470
- 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>";
471
477
  const placeholder = option.optional === undefined ? named : `[${named}]`;
472
478
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
473
- 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 };
474
481
  });
475
482
  const width = Math.max(0, ...rows.map((row) => row.width));
476
483
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
477
484
  }
478
485
 
479
486
  // ../kit/src/text.ts
480
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
481
487
  function distance(a, b) {
482
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
483
- 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()) {
484
493
  const current = [i + 1];
485
- for (const [j, right] of [...b].entries())
486
- 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;
487
501
  previous = current;
488
502
  }
489
- return previous[b.length] ?? 0;
503
+ return previous[right.length] ?? 0;
490
504
  }
491
505
  function closest(name, names) {
492
506
  const started = names.find((known) => known.startsWith(name));
@@ -562,7 +576,7 @@ class Completing {
562
576
  }
563
577
  var completion = { active: false };
564
578
  var OUTPUT_OPTIONS = {
565
- 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" },
566
580
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
567
581
  };
568
582
  function applyOutput(color, plain, env = process9.env) {
@@ -856,13 +870,91 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
856
870
  // ../kit/src/cli.ts
857
871
  import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
858
872
  import { dirname as dirname3, join as join5 } from "path";
859
- import process13 from "process";
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
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
+ }
860
952
 
861
953
  // ../kit/src/usage.ts
862
954
  import { appendFileSync, mkdirSync } from "fs";
863
955
  import { homedir as homedir3 } from "os";
864
956
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
865
- import process12 from "process";
957
+ import process13 from "process";
866
958
 
867
959
  // ../kit/src/logs.ts
868
960
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -876,14 +968,14 @@ var usageError;
876
968
  function noteUsageError(message) {
877
969
  usageError = message;
878
970
  }
879
- function stateHome(env = process12.env) {
971
+ function stateHome(env = process13.env) {
880
972
  const dir = env.XDG_STATE_HOME;
881
973
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
882
974
  }
883
- function usagePath(env = process12.env) {
975
+ function usagePath(env = process13.env) {
884
976
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
885
977
  }
886
- function usageRecorded(env = process12.env) {
978
+ function usageRecorded(env = process13.env) {
887
979
  const off = env.KAYNOOO_CLI_NO_USAGE;
888
980
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
889
981
  }
@@ -897,7 +989,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
897
989
  usageError = undefined;
898
990
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
899
991
  }
900
- function recordUsage(entry, env = process12.env) {
992
+ function recordUsage(entry, env = process13.env) {
901
993
  if (!usageRecorded(env))
902
994
  return;
903
995
  try {
@@ -913,7 +1005,11 @@ var LEVEL_OPTIONS = {
913
1005
  ...OUTPUT_OPTIONS,
914
1006
  help: { type: "boolean", short: "h", description: "show this help" }
915
1007
  };
916
- 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
+ };
917
1013
  async function commandRows(all, colors) {
918
1014
  const commands = shown(all);
919
1015
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -987,8 +1083,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
987
1083
  `);
988
1084
  }
989
1085
  function printError(prefix, message, hint, cause) {
990
- const colors = paint(process13.stderr);
991
- const styled = takesControlCodes(process13.stderr);
1086
+ const colors = paint(process14.stderr);
1087
+ const styled = takesControlCodes(process14.stderr);
992
1088
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
993
1089
  const under = (label, text, tint) => text === undefined ? "" : `
994
1090
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1031,11 +1127,11 @@ async function dispatch(level, typed, { version, redact }) {
1031
1127
  }
1032
1128
  }
1033
1129
  if (name === undefined && level.path.length > 1) {
1034
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
1130
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
1035
1131
  return 2;
1036
1132
  }
1037
1133
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1038
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1134
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
1039
1135
  return 0;
1040
1136
  }
1041
1137
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1146,6 +1242,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1146
1242
  }
1147
1243
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1148
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
+ }
1149
1258
  async function printCandidates(found) {
1150
1259
  for (const line of await found)
1151
1260
  console.log(line);
@@ -1170,10 +1279,15 @@ async function runCli(cli, argv = scriptArgs()) {
1170
1279
  const version = cli.version ?? packageVersion();
1171
1280
  if (argv[0] === COMPLETE)
1172
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();
1173
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);
1174
1288
  if (cli.usage !== false) {
1175
1289
  try {
1176
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1290
+ recordUsage(usageEntry(cli.name, command, argv, code));
1177
1291
  } catch {}
1178
1292
  }
1179
1293
  return code;
@@ -1196,16 +1310,20 @@ function commandPath(scope, argv) {
1196
1310
  async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1197
1311
  if (argv[0] === COMPLETE)
1198
1312
  return printCandidates(leafCandidates(run, argv.slice(1)));
1313
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1314
+ return printCompletionScript(name, flagValue(argv));
1199
1315
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1200
1316
  console.log(version ?? packageVersion());
1201
1317
  return 0;
1202
1318
  }
1203
1319
  let code;
1320
+ const started = performance.now();
1204
1321
  try {
1205
1322
  code = await run(argv);
1206
1323
  } catch (error) {
1207
1324
  code = reportThrown(name, error, redact, wantsJson(argv));
1208
1325
  }
1326
+ notifyEnd(name, code, performance.now() - started);
1209
1327
  if (usage !== false) {
1210
1328
  try {
1211
1329
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1237,7 +1355,7 @@ function parseSize(text, bareUnit = 1) {
1237
1355
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1238
1356
  }
1239
1357
  // ../kit/src/watch.ts
1240
- import process14 from "process";
1358
+ import process15 from "process";
1241
1359
  import { format } from "util";
1242
1360
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1243
1361
  var DEFAULT_SECONDS = 2;
@@ -1259,7 +1377,7 @@ function withoutWatch(args) {
1259
1377
  }
1260
1378
  return rest;
1261
1379
  }
1262
- async function watching(value, step, stream = process14.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1380
+ async function watching(value, step, stream = process15.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1263
1381
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1264
1382
  if (!takesControlCodes(stream))
1265
1383
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1267,12 +1385,12 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
1267
1385
  for (let round = 0;round < rounds; round++) {
1268
1386
  const held = [];
1269
1387
  const { log, info } = console;
1270
- const write = process14.stdout.write.bind(process14.stdout);
1388
+ const write = process15.stdout.write.bind(process15.stdout);
1271
1389
  const hold = (...parts) => void held.push(`${format(...parts)}
1272
1390
  `);
1273
1391
  console.log = hold;
1274
1392
  console.info = hold;
1275
- process14.stdout.write = (text) => {
1393
+ process15.stdout.write = (text) => {
1276
1394
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1277
1395
  return true;
1278
1396
  };
@@ -1281,7 +1399,7 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
1281
1399
  } finally {
1282
1400
  console.log = log;
1283
1401
  console.info = info;
1284
- process14.stdout.write = write;
1402
+ process15.stdout.write = write;
1285
1403
  }
1286
1404
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1287
1405
  await sleep(interval);
@@ -1290,10 +1408,24 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
1290
1408
  }
1291
1409
  // src/ports.ts
1292
1410
  import { basename as basename2 } from "path";
1293
- import process17 from "process";
1411
+ import process19 from "process";
1294
1412
 
1295
1413
  // ../kit/src/prompt.ts
1296
- import process16 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
+ }
1297
1429
 
1298
1430
  // ../kit/src/picker/score.ts
1299
1431
  var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
@@ -1325,10 +1457,29 @@ var KEYS = {
1325
1457
  "\n": "enter",
1326
1458
  "\x03": "cancel",
1327
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",
1328
1472
  "\x7F": "erase",
1329
- "\b": "erase",
1473
+ "\x1B[3~": "delete",
1474
+ "\b": "killword",
1475
+ "\x1B\x7F": "killword",
1476
+ "\x1B[3;5~": "killnext",
1477
+ "\x1Bd": "killnext",
1330
1478
  "\x15": "clear",
1479
+ "\v": "killend",
1331
1480
  "\x17": "word",
1481
+ "\x19": "yank",
1482
+ "\x1A": "suspend",
1332
1483
  "\t": "tab",
1333
1484
  "\x1F": "help",
1334
1485
  "\x1BOP": "help",
@@ -1358,10 +1509,21 @@ function parseKeys(input, paste = { active: false }, ctrls = []) {
1358
1509
  });
1359
1510
  }
1360
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
+
1361
1523
  // ../kit/src/prompt.ts
1362
- 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"]);
1363
1525
  function readKeys(input, paste = { active: false }) {
1364
- 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));
1365
1527
  }
1366
1528
  async function confirm(question, { default: fallback, ...settings } = {}) {
1367
1529
  let answered = fallback;
@@ -1385,7 +1547,7 @@ function asking(colors, question, typed, keys) {
1385
1547
  function answer(colors, question, state, picked) {
1386
1548
  return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1387
1549
  }
1388
- async function ask(question, { hint, terminal = process16 }, render, press) {
1550
+ async function ask(question, { hint, terminal = process18 }, render, press) {
1389
1551
  const { stdin, stderr } = terminal;
1390
1552
  if (!isInteractive(terminal))
1391
1553
  fail(`cannot ask "${question}" off a terminal`, 2, hint);
@@ -1395,12 +1557,22 @@ async function ask(question, { hint, terminal = process16 }, render, press) {
1395
1557
  const columns = () => stderr.columns || 80;
1396
1558
  const draw = (state, last = false) => {
1397
1559
  const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1398
- stderr.write(`\r\x1B[0J${frame.join(`
1399
- `)}${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}`);
1400
1562
  current = state;
1401
1563
  };
1402
1564
  const redraw = () => draw(current);
1403
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
+ };
1404
1576
  try {
1405
1577
  stderr.on?.("resize", redraw);
1406
1578
  stdin.setRawMode(true);
@@ -1410,6 +1582,10 @@ async function ask(question, { hint, terminal = process16 }, render, press) {
1410
1582
  return await new Promise((resolve) => {
1411
1583
  function onData(data) {
1412
1584
  for (const key of readKeys(data.toString(), paste)) {
1585
+ if (key === "suspend") {
1586
+ suspend();
1587
+ continue;
1588
+ }
1413
1589
  const pressed = press(key);
1414
1590
  if (pressed !== undefined) {
1415
1591
  settle(pressed);
@@ -1696,10 +1872,22 @@ async function socketsOf(pid, root = "/proc") {
1696
1872
  return inodes;
1697
1873
  }
1698
1874
  async function socketOwners(root = "/proc") {
1699
- const owners = new Map;
1875
+ const holders = new Map;
1700
1876
  for (const pid of await listPids(root)) {
1701
1877
  for (const inode of await socketsOf(pid, root))
1702
- 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);
1703
1891
  }
1704
1892
  return owners;
1705
1893
  }
@@ -1881,7 +2069,7 @@ function refusal(row, proc, guard) {
1881
2069
  return reason === undefined ? undefined : `pid ${row.pid} is ${reason}`;
1882
2070
  }
1883
2071
  function render(rows) {
1884
- const colors = paint(process17.stdout);
2072
+ const colors = paint(process19.stdout);
1885
2073
  const cells = rows.map((row) => [
1886
2074
  colors.cyan(String(row.port)),
1887
2075
  row.protocol,
@@ -1893,7 +2081,7 @@ function render(rows) {
1893
2081
  return table([["PORT", "PROTO", "ADDRESS", "PID", "COMMAND", "CWD"], ...cells], { header: true });
1894
2082
  }
1895
2083
  async function stop(port, rows, procs, values) {
1896
- const guard = { uid: process17.getuid?.() ?? -1, mine: new Set(ancestry(process17.pid, procs)) };
2084
+ const guard = { uid: process19.getuid?.() ?? -1, mine: new Set(ancestry(process19.pid, procs)) };
1897
2085
  const targets = new Map;
1898
2086
  for (const row of rows) {
1899
2087
  const reason = refusal(row, row.pid === undefined ? undefined : procs.get(row.pid), guard);
@@ -1906,7 +2094,7 @@ async function stop(port, rows, procs, values) {
1906
2094
  return 1;
1907
2095
  const names = [...targets].map(([pid, row]) => `${pid} (${truncate(row.command ?? "", 40)})`).join(", ");
1908
2096
  if (values.yes !== true) {
1909
- if (!process17.stdin.isTTY)
2097
+ if (!process19.stdin.isTTY)
1910
2098
  fail(`stopping ${names} needs a terminal to ask on: pass --yes`, 2);
1911
2099
  if (await confirm(`Stop ${names}?`, { default: false }) !== true)
1912
2100
  return 1;
@@ -1938,7 +2126,7 @@ async function ports(args) {
1938
2126
  badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`);
1939
2127
  if (values.kill === true && port === undefined)
1940
2128
  badUsage("--kill takes the port to free: ports <port> --kill");
1941
- const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process17.getuid?.())]);
2129
+ const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process19.getuid?.())]);
1942
2130
  const byPid = new Map(procs.map((proc) => [proc.pid, proc]));
1943
2131
  const wanted = sockets.filter((socket) => port === undefined || socket.port === port);
1944
2132
  const needsDocker = wanted.some((socket) => {
@@ -1959,9 +2147,9 @@ async function ports(args) {
1959
2147
  console.log(render(rows));
1960
2148
  const unknown = rows.filter((row) => row.pid === undefined && row.container === undefined).length;
1961
2149
  if (unknown > 0)
1962
- console.error(paint(process17.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 -`));
1963
2151
  return 0;
1964
2152
  }
1965
2153
 
1966
2154
  // src/ports-cli.ts
1967
- process18.exitCode = await runMain({ name: "ports", run: ports });
2155
+ process20.exitCode = await runMain({ name: "ports", run: ports });