@kaynooo/cli-proc 0.2.1 → 0.4.0

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,16 +2,37 @@
2
2
  // @bun
3
3
 
4
4
  // src/ports-cli.ts
5
- import process12 from "process";
5
+ import process14 from "process";
6
6
  // ../kit/src/args.ts
7
- import process5 from "process";
7
+ import process6 from "process";
8
8
  import { parseArgs } from "util";
9
9
 
10
10
  // ../kit/src/format.ts
11
- import process3 from "process";
11
+ import process4 from "process";
12
12
 
13
- // ../kit/src/style.ts
13
+ // ../kit/src/mode.ts
14
14
  import process2 from "process";
15
+ var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
16
+ var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
17
+ function isSet(value) {
18
+ return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
19
+ }
20
+ function outputMode(stream = process2.stdout, env = process2.env) {
21
+ const chosen = env.KIT_MODE;
22
+ if (chosen !== undefined && MODES.has(chosen))
23
+ return chosen;
24
+ if (AGENT_VARIABLES.some((name) => isSet(env[name])))
25
+ return "agent";
26
+ if (stream.isTTY === true)
27
+ return "terminal";
28
+ return isSet(env.CI) ? "ci" : "pipe";
29
+ }
30
+ function isInteractive(streams = process2) {
31
+ return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
32
+ }
33
+
34
+ // ../kit/src/style.ts
35
+ import process3 from "process";
15
36
 
16
37
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
17
38
  function x(s) {
@@ -274,21 +295,26 @@ function le(i = {}) {
274
295
  }
275
296
  var t = le();
276
297
 
298
+ // ../kit/src/theme.ts
299
+ var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
300
+ var MAX_FILE_BYTES = 64 * 1024;
301
+ var warned = new Set;
302
+
277
303
  // ../kit/src/style.ts
278
- function takesControlCodes(stream, env = process2.env) {
279
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
304
+ function takesControlCodes(stream, env = process3.env) {
305
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
280
306
  }
281
- function paint(stream, env = process2.env) {
307
+ function paint(stream, env = process3.env) {
282
308
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
283
309
  }
284
- var STATUSES = {
285
- passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
286
- failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
287
- running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
288
- queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
289
- skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
310
+ var STATUS_WORDS = {
311
+ passed: ["passed", "success", "succeeded", "ok"],
312
+ failed: ["failed", "failure", "error", "errored"],
313
+ running: ["running", "in_progress", "started", "holding"],
314
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
315
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
290
316
  };
291
- var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
317
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
292
318
 
293
319
  // ../kit/src/format.ts
294
320
  var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
@@ -317,15 +343,18 @@ var ESCAPE = String.fromCharCode(27);
317
343
  function textWidth(text) {
318
344
  return Bun.stringWidth(text);
319
345
  }
320
- function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
346
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process4.stdout, env = process4.env } = {}) {
321
347
  const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
348
+ if (outputMode(stream, env) === "agent")
349
+ return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
350
+ `);
322
351
  const widths = [];
323
352
  for (const row of cells) {
324
353
  for (const [index, cell] of row.entries())
325
354
  widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
326
355
  }
327
356
  const shown = fit === undefined ? cells : narrow(cells, widths, fit);
328
- const colors = paint(process3.stdout);
357
+ const colors = paint(stream);
329
358
  const lines = shown.map((row) => row.map((cell, index) => {
330
359
  const width = widths[index] ?? 0;
331
360
  const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
@@ -333,7 +362,8 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
333
362
  return `${gap}${cell}`;
334
363
  return index === row.length - 1 ? cell : `${cell}${gap}`;
335
364
  }).join(" ").trimEnd());
336
- return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
365
+ const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
366
+ return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
337
367
  `);
338
368
  }
339
369
  function narrow(rows, widths, limit) {
@@ -352,32 +382,35 @@ function narrow(rows, widths, limit) {
352
382
  }
353
383
  return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
354
384
  }
385
+ function jsonText(value, replacer, { stream = process4.stdout, env = process4.env } = {}) {
386
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
387
+ }
355
388
  function printJson(value) {
356
- console.log(JSON.stringify(value, undefined, 2));
389
+ console.log(jsonText(value));
357
390
  }
358
391
 
359
392
  // ../kit/src/help.ts
360
- import process4 from "process";
393
+ import process5 from "process";
361
394
  var OPTIONAL = /\[[^\]]+\]/g;
362
395
  var USAGE_PREFIX = /^usage:\s*/i;
363
396
  var FULL_STOP = /\.$/;
364
- function usageLine(usage, colors = paint(process4.stdout)) {
397
+ function usageLine(usage, colors = paint(process5.stdout)) {
365
398
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
366
399
  }
367
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
400
+ function helpText(usage, options, colors = paint(process5.stdout), { examples = [], replaces, exits = [] } = {}) {
368
401
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
369
402
  `);
370
403
  }
371
- function exitRows(exits, colors = paint(process4.stdout)) {
404
+ function exitRows(exits, colors = paint(process5.stdout)) {
372
405
  if (exits.length === 0)
373
406
  return [];
374
407
  const width = Math.max(...exits.map(([code]) => String(code).length));
375
408
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
376
409
  }
377
- function replacesRows(replaces, colors = paint(process4.stdout)) {
378
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
410
+ function replacesRows(replaces, colors = paint(process5.stdout)) {
411
+ return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
379
412
  }
380
- function wantsHelpJson(env = process4.env) {
413
+ function wantsHelpJson(env = process5.env) {
381
414
  return env.KIT_HELP === "json";
382
415
  }
383
416
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -396,12 +429,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
396
429
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
397
430
  };
398
431
  }
399
- function exampleRows(examples, colors = paint(process4.stdout)) {
400
- if (examples.length === 0)
432
+ function exampleRows(examples, colors = paint(process5.stdout)) {
433
+ if (examples.length === 0 || outputMode() === "agent")
401
434
  return [];
402
435
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
403
436
  }
404
- function optionRows(options, colors = paint(process4.stdout)) {
437
+ function optionRows(options, colors = paint(process5.stdout)) {
405
438
  const rows = Object.entries(options).map(([name, option]) => {
406
439
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
407
440
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -459,7 +492,6 @@ var DASHES = /^-+/;
459
492
  function jsonOption(holds) {
460
493
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
461
494
  }
462
-
463
495
  class Exit extends Error {
464
496
  code;
465
497
  hint;
@@ -503,7 +535,7 @@ var OUTPUT_OPTIONS = {
503
535
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
504
536
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
505
537
  };
506
- function applyOutput(color, plain, env = process5.env) {
538
+ function applyOutput(color, plain, env = process6.env) {
507
539
  const when = plain === true ? "never" : color ?? "auto";
508
540
  if (when === "auto")
509
541
  return;
@@ -674,7 +706,7 @@ function nearestOption(message, options, allowNegative) {
674
706
  }
675
707
  // ../kit/src/process.ts
676
708
  import { constants } from "os";
677
- import process6 from "process";
709
+ import process7 from "process";
678
710
  var KILL_GRACE_MS = 2000;
679
711
  function exitCodeOf(code, signal) {
680
712
  if (code !== null)
@@ -694,7 +726,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
694
726
  return;
695
727
  try {
696
728
  if (grouped)
697
- process6.kill(-proc.pid, killing);
729
+ process7.kill(-proc.pid, killing);
698
730
  else
699
731
  proc.kill(killing);
700
732
  } catch {}
@@ -770,13 +802,13 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
770
802
  // ../kit/src/cli.ts
771
803
  import { readFileSync, realpathSync } from "fs";
772
804
  import { dirname as dirname2, join as join2 } from "path";
773
- import process8 from "process";
805
+ import process9 from "process";
774
806
 
775
807
  // ../kit/src/usage.ts
776
808
  import { appendFileSync, mkdirSync } from "fs";
777
809
  import { homedir } from "os";
778
810
  import { dirname, isAbsolute, join } from "path";
779
- import process7 from "process";
811
+ import process8 from "process";
780
812
 
781
813
  // ../kit/src/logs.ts
782
814
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -790,14 +822,14 @@ var usageError;
790
822
  function noteUsageError(message) {
791
823
  usageError = message;
792
824
  }
793
- function stateHome(env = process7.env) {
825
+ function stateHome(env = process8.env) {
794
826
  const dir = env.XDG_STATE_HOME;
795
827
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
796
828
  }
797
- function usagePath(env = process7.env) {
829
+ function usagePath(env = process8.env) {
798
830
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
799
831
  }
800
- function usageRecorded(env = process7.env) {
832
+ function usageRecorded(env = process8.env) {
801
833
  const off = env.KAYNOOO_CLI_NO_USAGE;
802
834
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
803
835
  }
@@ -811,7 +843,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
811
843
  usageError = undefined;
812
844
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
813
845
  }
814
- function recordUsage(entry, env = process7.env) {
846
+ function recordUsage(entry, env = process8.env) {
815
847
  if (!usageRecorded(env))
816
848
  return;
817
849
  try {
@@ -828,9 +860,82 @@ var LEVEL_OPTIONS = {
828
860
  help: { type: "boolean", short: "h", description: "show this help" }
829
861
  };
830
862
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
863
+ async function commandRows(all, colors) {
864
+ const commands = shown(all);
865
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
866
+ const groups = new Map([["Commands:", []]]);
867
+ const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
868
+ for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
869
+ const heading = group === undefined ? "Commands:" : `${group}:`;
870
+ const rows = groups.get(heading) ?? [];
871
+ rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
872
+ groups.set(heading, rows);
873
+ }
874
+ return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
875
+ }
876
+ function shown(commands) {
877
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
878
+ }
879
+ function takeOutputFlags(argv) {
880
+ let index = 0;
881
+ for (;index < argv.length; index++) {
882
+ const word = argv[index];
883
+ if (word === "--plain")
884
+ applyOutput(undefined, true);
885
+ else if (word.startsWith("--color="))
886
+ applyOutput(word.slice("--color=".length), undefined);
887
+ else if (word === "--color" && argv[index + 1] !== undefined)
888
+ applyOutput(argv[++index], undefined);
889
+ else
890
+ break;
891
+ }
892
+ return argv.slice(index);
893
+ }
894
+ async function resolveSummary(summary) {
895
+ return typeof summary === "string" ? summary : summary();
896
+ }
897
+ function scopeOf(commands, extra, aliases) {
898
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
899
+ }
900
+ async function expand(scope, words) {
901
+ if (scope.lazy.length === 0)
902
+ return scope;
903
+ const commands = { ...scope.commands };
904
+ for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
905
+ for (const [name, command] of Object.entries(added))
906
+ commands[name] ??= command;
907
+ }
908
+ return { ...scope, commands, lazy: [] };
909
+ }
910
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
911
+ const colors = paint(stream);
912
+ const prefix = path.join(" ");
913
+ const summary = await resolveSummary(lazySummary);
914
+ if (wantsHelpJson())
915
+ return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
916
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
917
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
918
+ const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
919
+ return [
920
+ header(colors, summary),
921
+ "",
922
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
923
+ ...replacesRows(replaces, colors),
924
+ "",
925
+ ...await commandRows(commands, colors),
926
+ ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
927
+ "",
928
+ colors.bold("Options:"),
929
+ ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
930
+ ...exampleRows(examples ?? [], colors),
931
+ "",
932
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
933
+ ].join(`
934
+ `);
935
+ }
831
936
  function printError(prefix, message, hint, cause) {
832
- const colors = paint(process8.stderr);
833
- const styled = takesControlCodes(process8.stderr);
937
+ const colors = paint(process9.stderr);
938
+ const styled = takesControlCodes(process9.stderr);
834
939
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
835
940
  const under = (label, text, tint) => text === undefined ? "" : `
836
941
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -849,12 +954,68 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
849
954
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
850
955
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
851
956
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
852
- if (error instanceof UsageError)
957
+ if (error instanceof Exit && error.code === 2)
853
958
  noteUsageError(error.message);
854
959
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
855
960
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
856
961
  return error instanceof Exit ? error.code : 1;
857
962
  }
963
+ async function dispatch(level, typed, { version, redact }) {
964
+ const prefix = level.path.join(" ");
965
+ let argv;
966
+ try {
967
+ argv = takeOutputFlags(typed);
968
+ } catch (error) {
969
+ return reportThrown(prefix, error);
970
+ }
971
+ const [name, ...args] = argv;
972
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
973
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
974
+ try {
975
+ return await fallback.run([]);
976
+ } catch (error) {
977
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
978
+ }
979
+ }
980
+ if (name === undefined && level.path.length > 1) {
981
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
982
+ return 2;
983
+ }
984
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
985
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
986
+ return 0;
987
+ }
988
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
989
+ console.log(version);
990
+ return 0;
991
+ }
992
+ let command = level.commands[level.aliases?.[name] ?? name];
993
+ let rest = args;
994
+ let ran = name;
995
+ if (command === undefined && level.lazy.length > 0) {
996
+ level = await expand(level, [...level.path.slice(1), ...argv]);
997
+ command = level.commands[level.aliases?.[name] ?? name];
998
+ }
999
+ if (command === undefined && level.defaultCommand !== undefined) {
1000
+ command = level.commands[level.defaultCommand];
1001
+ rest = argv;
1002
+ ran = level.defaultCommand;
1003
+ }
1004
+ if (command === undefined) {
1005
+ const meant = closest(name, Object.keys(shown(level.commands)));
1006
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
1007
+ return 2;
1008
+ }
1009
+ if ("commands" in command) {
1010
+ const { summary } = command;
1011
+ return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
1012
+ }
1013
+ try {
1014
+ return await command.run(rest);
1015
+ } catch (error) {
1016
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
1017
+ }
1018
+ }
858
1019
  var COMPLETE = "__complete";
859
1020
  var FILES = "__files__";
860
1021
  async function completingOf(run) {
@@ -869,6 +1030,9 @@ async function completingOf(run) {
869
1030
  }
870
1031
  return new Completing({});
871
1032
  }
1033
+ async function optionsOf(run) {
1034
+ return (await completingOf(run)).options;
1035
+ }
872
1036
  function candidateLine(candidate) {
873
1037
  return typeof candidate === "string" ? candidate : candidate.join("\t");
874
1038
  }
@@ -907,6 +1071,28 @@ async function leafCandidates(run, words) {
907
1071
  const values = name === undefined ? undefined : await completing.candidates[name]?.();
908
1072
  return values === undefined ? [FILES] : values.map(candidateLine);
909
1073
  }
1074
+ async function candidates(scope, defaultCommand, words, before = []) {
1075
+ const [word = "", ...rest] = words;
1076
+ const listing = rest.length === 0 && !word.startsWith("-");
1077
+ let { commands, aliases } = scope;
1078
+ let command = commands[aliases?.[word] ?? word];
1079
+ if (listing || command === undefined) {
1080
+ ({ commands, aliases } = await expand(scope, [...before, ...words]));
1081
+ command = commands[aliases?.[word] ?? word];
1082
+ }
1083
+ if (listing) {
1084
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1085
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1086
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1087
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1088
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
1089
+ }
1090
+ if (command === undefined) {
1091
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1092
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
1093
+ }
1094
+ return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1095
+ }
910
1096
  async function printCandidates(found) {
911
1097
  for (const line of await found)
912
1098
  console.log(line);
@@ -923,7 +1109,34 @@ function packageVersion(entry = Bun.main) {
923
1109
  return "0.0.0";
924
1110
  }
925
1111
  }
926
- async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
1112
+ async function runCli(cli, argv = process9.argv.slice(2)) {
1113
+ const version = cli.version ?? packageVersion();
1114
+ if (argv[0] === COMPLETE)
1115
+ return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1116
+ 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 });
1117
+ if (cli.usage !== false) {
1118
+ try {
1119
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1120
+ } catch {}
1121
+ }
1122
+ return code;
1123
+ }
1124
+ function commandPath(scope, argv) {
1125
+ const path = [];
1126
+ let level = scope;
1127
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
1128
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1129
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1130
+ if (command === undefined)
1131
+ break;
1132
+ path.push(word);
1133
+ if (!("commands" in command))
1134
+ break;
1135
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
1136
+ }
1137
+ return path.length === 0 ? undefined : path.join(" ");
1138
+ }
1139
+ async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
927
1140
  if (argv[0] === COMPLETE)
928
1141
  return printCandidates(leafCandidates(run, argv.slice(1)));
929
1142
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -964,17 +1177,124 @@ function parseSize(text, bareUnit = 1) {
964
1177
  const suffix = match[2].toLowerCase();
965
1178
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
966
1179
  }
1180
+ // ../kit/src/watch.ts
1181
+ import process10 from "process";
1182
+ import { format } from "util";
1183
+ var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1184
+ var DEFAULT_SECONDS = 2;
1185
+ var ATTACHED_SHORT = /^-w./;
1186
+ var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
1187
+ function watchOption(what) {
1188
+ return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
1189
+ }
1190
+ function withoutWatch(args) {
1191
+ const rest = [];
1192
+ for (let at = 0;at < args.length; at++) {
1193
+ const arg = args[at];
1194
+ if (arg === "--watch" || arg === "-w") {
1195
+ if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
1196
+ at++;
1197
+ } else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
1198
+ rest.push(arg);
1199
+ }
1200
+ }
1201
+ return rest;
1202
+ }
1203
+ async function watching(value, step, stream = process10.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1204
+ const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1205
+ if (!takesControlCodes(stream))
1206
+ badUsage("--watch redraws the screen, so it needs a terminal");
1207
+ let code = 0;
1208
+ for (let round = 0;round < rounds; round++) {
1209
+ const held = [];
1210
+ const { log, info } = console;
1211
+ const write = process10.stdout.write.bind(process10.stdout);
1212
+ const hold = (...parts) => void held.push(`${format(...parts)}
1213
+ `);
1214
+ console.log = hold;
1215
+ console.info = hold;
1216
+ process10.stdout.write = (text) => {
1217
+ held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1218
+ return true;
1219
+ };
1220
+ try {
1221
+ code = await step();
1222
+ } finally {
1223
+ console.log = log;
1224
+ console.info = info;
1225
+ process10.stdout.write = write;
1226
+ }
1227
+ stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1228
+ await sleep(interval);
1229
+ }
1230
+ return code;
1231
+ }
967
1232
  // src/ports.ts
968
1233
  import { basename as basename2 } from "path";
969
- import process11 from "process";
1234
+ import process13 from "process";
970
1235
 
971
1236
  // ../kit/src/prompt.ts
972
- import process10 from "process";
973
- var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|[\s\S]/giu;
974
- var CONTROL = /^[\x00-\x1F\x7F]/;
975
- var KEYS = { "\x1B[A": "up", "\x1BOA": "up", "\x1B[B": "down", "\x1BOB": "down", "\r": "enter", "\n": "enter", "\x03": "cancel", "\x1B": "cancel", "\x7F": "erase", "\b": "erase" };
976
- function readKeys(input) {
977
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => KEYS[sequence] ?? (CONTROL.test(sequence) ? [] : [{ text: sequence }]));
1237
+ import process12 from "process";
1238
+
1239
+ // ../kit/src/picker/score.ts
1240
+ var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1241
+ var NONE = Number.NEGATIVE_INFINITY;
1242
+
1243
+ // ../kit/src/picker/state.ts
1244
+ var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1245
+ var PASTE_START = "\x1B[200~";
1246
+ var PASTE_END = "\x1B[201~";
1247
+ var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1248
+ var KEYS = {
1249
+ "\x1B[A": "up",
1250
+ "\x1BOA": "up",
1251
+ "\x10": "up",
1252
+ "\x1B[B": "down",
1253
+ "\x1BOB": "down",
1254
+ "\x0E": "down",
1255
+ "\x1B[5~": "pageup",
1256
+ "\x1B[6~": "pagedown",
1257
+ "\x1B[H": "home",
1258
+ "\x1B[1~": "home",
1259
+ "\x1BOH": "home",
1260
+ "\x1B[F": "end",
1261
+ "\x1B[4~": "end",
1262
+ "\x1BOF": "end",
1263
+ "\r": "enter",
1264
+ "\n": "enter",
1265
+ "\x03": "cancel",
1266
+ "\x1B": "cancel",
1267
+ "\x7F": "erase",
1268
+ "\b": "erase",
1269
+ "\x15": "clear",
1270
+ "\x17": "word",
1271
+ "\t": "tab",
1272
+ "\x1F": "help",
1273
+ "\x1BOP": "help",
1274
+ "\x1B[11~": "help"
1275
+ };
1276
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
1277
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1278
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1279
+ const named = codes.get(sequence);
1280
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1281
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1282
+ paste.active = sequence === PASTE_START;
1283
+ return [];
1284
+ }
1285
+ if (paste.active && (sequence === "\r" || sequence === `
1286
+ `))
1287
+ return [];
1288
+ if (key !== undefined)
1289
+ return [key];
1290
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1291
+ });
1292
+ }
1293
+
1294
+ // ../kit/src/prompt.ts
1295
+ var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "erase"]);
1296
+ function readKeys(input, paste = { active: false }) {
1297
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key));
978
1298
  }
979
1299
  async function confirm(question, { default: fallback, ...settings } = {}) {
980
1300
  let answered = fallback;
@@ -998,27 +1318,34 @@ function asking(colors, question, typed, keys) {
998
1318
  function answer(colors, question, state, picked) {
999
1319
  return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1000
1320
  }
1001
- async function ask(question, { hint, terminal = process10 }, render, press) {
1321
+ async function ask(question, { hint, terminal = process12 }, render, press) {
1002
1322
  const { stdin, stderr } = terminal;
1003
- if (stdin.isTTY !== true || stderr.isTTY !== true)
1323
+ if (!isInteractive(terminal))
1004
1324
  fail(`cannot ask "${question}" off a terminal`, 2, hint);
1005
1325
  const colors = paint(stderr);
1006
- let drawn = 0;
1326
+ let drawn = [];
1327
+ let current = "asking";
1007
1328
  let outcome;
1329
+ const columns = () => stderr.columns || 80;
1008
1330
  const draw = (state) => {
1009
- const frame = render(colors, state, { columns: stderr.columns || 80, rows: stderr.rows || 24 });
1010
- stderr.write(`${drawn > 1 ? `\x1B[${drawn - 1}A` : ""}\r\x1B[0J${frame.join(`
1331
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1332
+ const rows = drawn.reduce((sum, line) => sum + Math.max(1, Math.ceil(Bun.stringWidth(line) / columns())), 0);
1333
+ stderr.write(`${rows > 1 ? `\x1B[${rows - 1}A` : ""}\r\x1B[0J${frame.join(`
1011
1334
  `)}`);
1012
- drawn = frame.length;
1335
+ drawn = frame;
1336
+ current = state;
1013
1337
  };
1338
+ const redraw = () => draw(current);
1339
+ const paste = { active: false };
1014
1340
  try {
1341
+ stderr.on?.("resize", redraw);
1015
1342
  stdin.setRawMode(true);
1016
1343
  stdin.resume();
1017
- stderr.write("\x1B[?25l");
1344
+ stderr.write("\x1B[?25l\x1B[?2004h");
1018
1345
  draw("asking");
1019
1346
  return await new Promise((resolve) => {
1020
1347
  function onData(data) {
1021
- for (const key of readKeys(data.toString())) {
1348
+ for (const key of readKeys(data.toString(), paste)) {
1022
1349
  const pressed = press(key);
1023
1350
  if (pressed !== undefined) {
1024
1351
  settle(pressed);
@@ -1040,9 +1367,10 @@ async function ask(question, { hint, terminal = process10 }, render, press) {
1040
1367
  stdin.on("end", onEnd);
1041
1368
  });
1042
1369
  } finally {
1370
+ stderr.off?.("resize", redraw);
1043
1371
  draw(outcome ?? "cancel");
1044
1372
  stderr.write(`
1045
- \x1B[?25h`);
1373
+ \x1B[?25h\x1B[?2004l`);
1046
1374
  stdin.setRawMode(false);
1047
1375
  stdin.pause();
1048
1376
  }
@@ -1444,7 +1772,8 @@ Lists what listens on this machine, TCP and UDP over IPv4 and IPv6, one row per
1444
1772
  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.`;
1445
1773
  var options = {
1446
1774
  json: jsonOption("[{ port, protocol, addresses, pid, command, cwd, container }]"),
1447
- kill: { type: "boolean", description: "stop the owner of the given port" },
1775
+ kill: { type: "boolean", conflicts: ["watch"], description: "stop the owner of the given port" },
1776
+ watch: watchOption("the ports"),
1448
1777
  force: { type: "boolean", description: "with --kill, SIGKILL what SIGTERM did not stop within --grace" },
1449
1778
  yes: { type: "boolean", short: "y", description: "with --kill, do not ask first" },
1450
1779
  grace: { type: "string", description: "with --force, how long SIGTERM gets before SIGKILL (5s)" }
@@ -1488,7 +1817,7 @@ function refusal(row, proc, guard) {
1488
1817
  return reason === undefined ? undefined : `pid ${row.pid} is ${reason}`;
1489
1818
  }
1490
1819
  function render(rows) {
1491
- const colors = paint(process11.stdout);
1820
+ const colors = paint(process13.stdout);
1492
1821
  const cells = rows.map((row) => [
1493
1822
  colors.cyan(String(row.port)),
1494
1823
  row.protocol,
@@ -1500,7 +1829,7 @@ function render(rows) {
1500
1829
  return table([["PORT", "PROTO", "ADDRESS", "PID", "COMMAND", "CWD"], ...cells], { header: true });
1501
1830
  }
1502
1831
  async function stop(port, rows, procs, values) {
1503
- const guard = { uid: process11.getuid?.() ?? -1, mine: new Set(ancestry(process11.pid, procs)) };
1832
+ const guard = { uid: process13.getuid?.() ?? -1, mine: new Set(ancestry(process13.pid, procs)) };
1504
1833
  const targets = new Map;
1505
1834
  for (const row of rows) {
1506
1835
  const reason = refusal(row, row.pid === undefined ? undefined : procs.get(row.pid), guard);
@@ -1513,7 +1842,7 @@ async function stop(port, rows, procs, values) {
1513
1842
  return 1;
1514
1843
  const names = [...targets].map(([pid, row]) => `${pid} (${truncate(row.command ?? "", 40)})`).join(", ");
1515
1844
  if (values.yes !== true) {
1516
- if (!process11.stdin.isTTY)
1845
+ if (!process13.stdin.isTTY)
1517
1846
  fail(`stopping ${names} needs a terminal to ask on: pass --yes`, 2);
1518
1847
  if (await confirm(`Stop ${names}?`, { default: false }) !== true)
1519
1848
  return 1;
@@ -1536,13 +1865,15 @@ async function ports(args) {
1536
1865
  "ports --json"
1537
1866
  ]
1538
1867
  });
1868
+ if (values.watch !== undefined)
1869
+ return watching(values.watch, async () => ports(withoutWatch(args)));
1539
1870
  const [given] = positionals;
1540
1871
  const port = given === undefined ? undefined : wholeNumber(given, "<port>", 0);
1541
1872
  if (port !== undefined && port > 65535)
1542
1873
  badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`);
1543
1874
  if (values.kill === true && port === undefined)
1544
1875
  badUsage("--kill takes the port to free: ports <port> --kill");
1545
- const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process11.getuid?.())]);
1876
+ const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process13.getuid?.())]);
1546
1877
  const byPid = new Map(procs.map((proc) => [proc.pid, proc]));
1547
1878
  const wanted = sockets.filter((socket) => port === undefined || socket.port === port);
1548
1879
  const needsDocker = wanted.some((socket) => {
@@ -1563,9 +1894,9 @@ async function ports(args) {
1563
1894
  console.log(render(rows));
1564
1895
  const unknown = rows.filter((row) => row.pid === undefined && row.container === undefined).length;
1565
1896
  if (unknown > 0)
1566
- console.error(paint(process11.stderr).dim(`${unknown} ${unknown === 1 ? "port has" : "ports have"} an owner this user cannot read, shown as -`));
1897
+ console.error(paint(process13.stderr).dim(`${unknown} ${unknown === 1 ? "port has" : "ports have"} an owner this user cannot read, shown as -`));
1567
1898
  return 0;
1568
1899
  }
1569
1900
 
1570
1901
  // src/ports-cli.ts
1571
- process12.exitCode = await runMain({ name: "ports", run: ports });
1902
+ process14.exitCode = await runMain({ name: "ports", run: ports });