@kaynooo/cli-proc 0.3.0 → 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/proc-cli.js CHANGED
@@ -2,16 +2,37 @@
2
2
  // @bun
3
3
 
4
4
  // src/proc-cli.ts
5
- import process14 from "process";
5
+ import process16 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
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-hrsswv1w.js
293
319
  function $e(t, e = false, i = 1) {
294
320
  let n = typeof e === "object" ? e : { units: e ? "si" : "iec", dp: i }, { units: s = "iec", dp: u = 1 } = n, r = s === "si" ? 1000 : 1024;
@@ -328,15 +354,18 @@ var ESCAPE = String.fromCharCode(27);
328
354
  function textWidth(text) {
329
355
  return Bun.stringWidth(text);
330
356
  }
331
- function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
357
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process4.stdout, env = process4.env } = {}) {
332
358
  const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
359
+ if (outputMode(stream, env) === "agent")
360
+ return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
361
+ `);
333
362
  const widths = [];
334
363
  for (const row of cells) {
335
364
  for (const [index, cell] of row.entries())
336
365
  widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
337
366
  }
338
367
  const shown = fit === undefined ? cells : narrow(cells, widths, fit);
339
- const colors = paint(process3.stdout);
368
+ const colors = paint(stream);
340
369
  const lines = shown.map((row) => row.map((cell, index) => {
341
370
  const width = widths[index] ?? 0;
342
371
  const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
@@ -344,7 +373,8 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
344
373
  return `${gap}${cell}`;
345
374
  return index === row.length - 1 ? cell : `${cell}${gap}`;
346
375
  }).join(" ").trimEnd());
347
- return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
376
+ const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
377
+ return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
348
378
  `);
349
379
  }
350
380
  function narrow(rows, widths, limit) {
@@ -363,32 +393,35 @@ function narrow(rows, widths, limit) {
363
393
  }
364
394
  return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
365
395
  }
396
+ function jsonText(value, replacer, { stream = process4.stdout, env = process4.env } = {}) {
397
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
398
+ }
366
399
  function printJson(value) {
367
- console.log(JSON.stringify(value, undefined, 2));
400
+ console.log(jsonText(value));
368
401
  }
369
402
 
370
403
  // ../kit/src/help.ts
371
- import process4 from "process";
404
+ import process5 from "process";
372
405
  var OPTIONAL = /\[[^\]]+\]/g;
373
406
  var USAGE_PREFIX = /^usage:\s*/i;
374
407
  var FULL_STOP = /\.$/;
375
- function usageLine(usage, colors = paint(process4.stdout)) {
408
+ function usageLine(usage, colors = paint(process5.stdout)) {
376
409
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
377
410
  }
378
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
411
+ function helpText(usage, options, colors = paint(process5.stdout), { examples = [], replaces, exits = [] } = {}) {
379
412
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
380
413
  `);
381
414
  }
382
- function exitRows(exits, colors = paint(process4.stdout)) {
415
+ function exitRows(exits, colors = paint(process5.stdout)) {
383
416
  if (exits.length === 0)
384
417
  return [];
385
418
  const width = Math.max(...exits.map(([code]) => String(code).length));
386
419
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
387
420
  }
388
- function replacesRows(replaces, colors = paint(process4.stdout)) {
389
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
421
+ function replacesRows(replaces, colors = paint(process5.stdout)) {
422
+ return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
390
423
  }
391
- function wantsHelpJson(env = process4.env) {
424
+ function wantsHelpJson(env = process5.env) {
392
425
  return env.KIT_HELP === "json";
393
426
  }
394
427
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -407,12 +440,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
407
440
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
408
441
  };
409
442
  }
410
- function exampleRows(examples, colors = paint(process4.stdout)) {
411
- if (examples.length === 0)
443
+ function exampleRows(examples, colors = paint(process5.stdout)) {
444
+ if (examples.length === 0 || outputMode() === "agent")
412
445
  return [];
413
446
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
414
447
  }
415
- function optionRows(options, colors = paint(process4.stdout)) {
448
+ function optionRows(options, colors = paint(process5.stdout)) {
416
449
  const rows = Object.entries(options).map(([name, option]) => {
417
450
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
418
451
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -470,7 +503,6 @@ var DASHES = /^-+/;
470
503
  function jsonOption(holds) {
471
504
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
472
505
  }
473
-
474
506
  class Exit extends Error {
475
507
  code;
476
508
  hint;
@@ -514,7 +546,7 @@ var OUTPUT_OPTIONS = {
514
546
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
515
547
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
516
548
  };
517
- function applyOutput(color, plain, env = process5.env) {
549
+ function applyOutput(color, plain, env = process6.env) {
518
550
  const when = plain === true ? "never" : color ?? "auto";
519
551
  if (when === "auto")
520
552
  return;
@@ -685,7 +717,7 @@ function nearestOption(message, options, allowNegative) {
685
717
  }
686
718
  // ../kit/src/process.ts
687
719
  import { constants } from "os";
688
- import process6 from "process";
720
+ import process7 from "process";
689
721
  var KILL_GRACE_MS = 2000;
690
722
  function exitCodeOf(code, signal) {
691
723
  if (code !== null)
@@ -705,7 +737,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
705
737
  return;
706
738
  try {
707
739
  if (grouped)
708
- process6.kill(-proc.pid, killing);
740
+ process7.kill(-proc.pid, killing);
709
741
  else
710
742
  proc.kill(killing);
711
743
  } catch {}
@@ -781,13 +813,13 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
781
813
  // ../kit/src/cli.ts
782
814
  import { readFileSync, realpathSync } from "fs";
783
815
  import { dirname as dirname2, join as join2 } from "path";
784
- import process8 from "process";
816
+ import process9 from "process";
785
817
 
786
818
  // ../kit/src/usage.ts
787
819
  import { appendFileSync, mkdirSync } from "fs";
788
820
  import { homedir } from "os";
789
821
  import { dirname, isAbsolute, join } from "path";
790
- import process7 from "process";
822
+ import process8 from "process";
791
823
 
792
824
  // ../kit/src/logs.ts
793
825
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -801,14 +833,14 @@ var usageError;
801
833
  function noteUsageError(message) {
802
834
  usageError = message;
803
835
  }
804
- function stateHome(env = process7.env) {
836
+ function stateHome(env = process8.env) {
805
837
  const dir = env.XDG_STATE_HOME;
806
838
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
807
839
  }
808
- function usagePath(env = process7.env) {
840
+ function usagePath(env = process8.env) {
809
841
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
810
842
  }
811
- function usageRecorded(env = process7.env) {
843
+ function usageRecorded(env = process8.env) {
812
844
  const off = env.KAYNOOO_CLI_NO_USAGE;
813
845
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
814
846
  }
@@ -822,7 +854,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
822
854
  usageError = undefined;
823
855
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
824
856
  }
825
- function recordUsage(entry, env = process7.env) {
857
+ function recordUsage(entry, env = process8.env) {
826
858
  if (!usageRecorded(env))
827
859
  return;
828
860
  try {
@@ -913,8 +945,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
913
945
  `);
914
946
  }
915
947
  function printError(prefix, message, hint, cause) {
916
- const colors = paint(process8.stderr);
917
- const styled = takesControlCodes(process8.stderr);
948
+ const colors = paint(process9.stderr);
949
+ const styled = takesControlCodes(process9.stderr);
918
950
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
919
951
  const under = (label, text, tint) => text === undefined ? "" : `
920
952
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -957,11 +989,11 @@ async function dispatch(level, typed, { version, redact }) {
957
989
  }
958
990
  }
959
991
  if (name === undefined && level.path.length > 1) {
960
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
992
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
961
993
  return 2;
962
994
  }
963
995
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
964
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
996
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
965
997
  return 0;
966
998
  }
967
999
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1088,7 +1120,7 @@ function packageVersion(entry = Bun.main) {
1088
1120
  return "0.0.0";
1089
1121
  }
1090
1122
  }
1091
- async function runCli(cli, argv = process8.argv.slice(2)) {
1123
+ async function runCli(cli, argv = process9.argv.slice(2)) {
1092
1124
  const version = cli.version ?? packageVersion();
1093
1125
  if (argv[0] === COMPLETE)
1094
1126
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -1115,7 +1147,7 @@ function commandPath(scope, argv) {
1115
1147
  }
1116
1148
  return path.length === 0 ? undefined : path.join(" ");
1117
1149
  }
1118
- async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
1150
+ async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
1119
1151
  if (argv[0] === COMPLETE)
1120
1152
  return printCandidates(leafCandidates(run, argv.slice(1)));
1121
1153
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1156,8 +1188,60 @@ function parseSize(text, bareUnit = 1) {
1156
1188
  const suffix = match[2].toLowerCase();
1157
1189
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1158
1190
  }
1159
- // src/pid.ts
1191
+ // ../kit/src/watch.ts
1160
1192
  import process10 from "process";
1193
+ import { format } from "util";
1194
+ var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1195
+ var DEFAULT_SECONDS = 2;
1196
+ var ATTACHED_SHORT = /^-w./;
1197
+ var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
1198
+ function watchOption(what) {
1199
+ return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
1200
+ }
1201
+ function withoutWatch(args) {
1202
+ const rest = [];
1203
+ for (let at = 0;at < args.length; at++) {
1204
+ const arg = args[at];
1205
+ if (arg === "--watch" || arg === "-w") {
1206
+ if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
1207
+ at++;
1208
+ } else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
1209
+ rest.push(arg);
1210
+ }
1211
+ }
1212
+ return rest;
1213
+ }
1214
+ async function watching(value, step, stream = process10.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1215
+ const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1216
+ if (!takesControlCodes(stream))
1217
+ badUsage("--watch redraws the screen, so it needs a terminal");
1218
+ let code = 0;
1219
+ for (let round = 0;round < rounds; round++) {
1220
+ const held = [];
1221
+ const { log, info } = console;
1222
+ const write = process10.stdout.write.bind(process10.stdout);
1223
+ const hold = (...parts) => void held.push(`${format(...parts)}
1224
+ `);
1225
+ console.log = hold;
1226
+ console.info = hold;
1227
+ process10.stdout.write = (text) => {
1228
+ held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1229
+ return true;
1230
+ };
1231
+ try {
1232
+ code = await step();
1233
+ } finally {
1234
+ console.log = log;
1235
+ console.info = info;
1236
+ process10.stdout.write = write;
1237
+ }
1238
+ stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1239
+ await sleep(interval);
1240
+ }
1241
+ return code;
1242
+ }
1243
+ // src/pid.ts
1244
+ import process12 from "process";
1161
1245
 
1162
1246
  // src/mask.ts
1163
1247
  import { basename } from "path";
@@ -1548,7 +1632,7 @@ function limitLine(limits, name) {
1548
1632
  return limit === undefined ? "-" : `soft ${limit.soft}, hard ${limit.hard}`;
1549
1633
  }
1550
1634
  function render(info, showEnv) {
1551
- const colors = paint(process10.stdout);
1635
+ const colors = paint(process12.stdout);
1552
1636
  const memory = info.memory;
1553
1637
  const size = (bytes) => bytes === undefined ? "-" : $e(bytes);
1554
1638
  const rows = [
@@ -1601,15 +1685,70 @@ async function pid(args) {
1601
1685
 
1602
1686
  // src/ports.ts
1603
1687
  import { basename as basename2 } from "path";
1604
- import process12 from "process";
1688
+ import process14 from "process";
1689
+
1690
+ // ../kit/src/prompt.ts
1691
+ import process13 from "process";
1692
+
1693
+ // ../kit/src/picker/score.ts
1694
+ var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1695
+ var NONE = Number.NEGATIVE_INFINITY;
1696
+
1697
+ // ../kit/src/picker/state.ts
1698
+ var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1699
+ var PASTE_START = "\x1B[200~";
1700
+ var PASTE_END = "\x1B[201~";
1701
+ var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1702
+ var KEYS = {
1703
+ "\x1B[A": "up",
1704
+ "\x1BOA": "up",
1705
+ "\x10": "up",
1706
+ "\x1B[B": "down",
1707
+ "\x1BOB": "down",
1708
+ "\x0E": "down",
1709
+ "\x1B[5~": "pageup",
1710
+ "\x1B[6~": "pagedown",
1711
+ "\x1B[H": "home",
1712
+ "\x1B[1~": "home",
1713
+ "\x1BOH": "home",
1714
+ "\x1B[F": "end",
1715
+ "\x1B[4~": "end",
1716
+ "\x1BOF": "end",
1717
+ "\r": "enter",
1718
+ "\n": "enter",
1719
+ "\x03": "cancel",
1720
+ "\x1B": "cancel",
1721
+ "\x7F": "erase",
1722
+ "\b": "erase",
1723
+ "\x15": "clear",
1724
+ "\x17": "word",
1725
+ "\t": "tab",
1726
+ "\x1F": "help",
1727
+ "\x1BOP": "help",
1728
+ "\x1B[11~": "help"
1729
+ };
1730
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
1731
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1732
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1733
+ const named = codes.get(sequence);
1734
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1735
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1736
+ paste.active = sequence === PASTE_START;
1737
+ return [];
1738
+ }
1739
+ if (paste.active && (sequence === "\r" || sequence === `
1740
+ `))
1741
+ return [];
1742
+ if (key !== undefined)
1743
+ return [key];
1744
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1745
+ });
1746
+ }
1605
1747
 
1606
1748
  // ../kit/src/prompt.ts
1607
- import process11 from "process";
1608
- var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|[\s\S]/giu;
1609
- var CONTROL = /^[\x00-\x1F\x7F]/;
1610
- var KEYS = { "\x1B[A": "up", "\x1BOA": "up", "\x1B[B": "down", "\x1BOB": "down", "\r": "enter", "\n": "enter", "\x03": "cancel", "\x1B": "cancel", "\x7F": "erase", "\b": "erase" };
1611
- function readKeys(input) {
1612
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => KEYS[sequence] ?? (CONTROL.test(sequence) ? [] : [{ text: sequence }]));
1749
+ var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "erase"]);
1750
+ function readKeys(input, paste = { active: false }) {
1751
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key));
1613
1752
  }
1614
1753
  async function confirm(question, { default: fallback, ...settings } = {}) {
1615
1754
  let answered = fallback;
@@ -1633,27 +1772,34 @@ function asking(colors, question, typed, keys) {
1633
1772
  function answer(colors, question, state, picked) {
1634
1773
  return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1635
1774
  }
1636
- async function ask(question, { hint, terminal = process11 }, render, press) {
1775
+ async function ask(question, { hint, terminal = process13 }, render, press) {
1637
1776
  const { stdin, stderr } = terminal;
1638
- if (stdin.isTTY !== true || stderr.isTTY !== true)
1777
+ if (!isInteractive(terminal))
1639
1778
  fail(`cannot ask "${question}" off a terminal`, 2, hint);
1640
1779
  const colors = paint(stderr);
1641
- let drawn = 0;
1780
+ let drawn = [];
1781
+ let current = "asking";
1642
1782
  let outcome;
1783
+ const columns = () => stderr.columns || 80;
1643
1784
  const draw = (state) => {
1644
- const frame = render(colors, state, { columns: stderr.columns || 80, rows: stderr.rows || 24 });
1645
- stderr.write(`${drawn > 1 ? `\x1B[${drawn - 1}A` : ""}\r\x1B[0J${frame.join(`
1785
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1786
+ const rows = drawn.reduce((sum, line) => sum + Math.max(1, Math.ceil(Bun.stringWidth(line) / columns())), 0);
1787
+ stderr.write(`${rows > 1 ? `\x1B[${rows - 1}A` : ""}\r\x1B[0J${frame.join(`
1646
1788
  `)}`);
1647
- drawn = frame.length;
1789
+ drawn = frame;
1790
+ current = state;
1648
1791
  };
1792
+ const redraw = () => draw(current);
1793
+ const paste = { active: false };
1649
1794
  try {
1795
+ stderr.on?.("resize", redraw);
1650
1796
  stdin.setRawMode(true);
1651
1797
  stdin.resume();
1652
- stderr.write("\x1B[?25l");
1798
+ stderr.write("\x1B[?25l\x1B[?2004h");
1653
1799
  draw("asking");
1654
1800
  return await new Promise((resolve) => {
1655
1801
  function onData(data) {
1656
- for (const key of readKeys(data.toString())) {
1802
+ for (const key of readKeys(data.toString(), paste)) {
1657
1803
  const pressed = press(key);
1658
1804
  if (pressed !== undefined) {
1659
1805
  settle(pressed);
@@ -1675,9 +1821,10 @@ async function ask(question, { hint, terminal = process11 }, render, press) {
1675
1821
  stdin.on("end", onEnd);
1676
1822
  });
1677
1823
  } finally {
1824
+ stderr.off?.("resize", redraw);
1678
1825
  draw(outcome ?? "cancel");
1679
1826
  stderr.write(`
1680
- \x1B[?25h`);
1827
+ \x1B[?25h\x1B[?2004l`);
1681
1828
  stdin.setRawMode(false);
1682
1829
  stdin.pause();
1683
1830
  }
@@ -1768,7 +1915,8 @@ Lists what listens on this machine, TCP and UDP over IPv4 and IPv6, one row per
1768
1915
  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.`;
1769
1916
  var options2 = {
1770
1917
  json: jsonOption("[{ port, protocol, addresses, pid, command, cwd, container }]"),
1771
- kill: { type: "boolean", description: "stop the owner of the given port" },
1918
+ kill: { type: "boolean", conflicts: ["watch"], description: "stop the owner of the given port" },
1919
+ watch: watchOption("the ports"),
1772
1920
  force: { type: "boolean", description: "with --kill, SIGKILL what SIGTERM did not stop within --grace" },
1773
1921
  yes: { type: "boolean", short: "y", description: "with --kill, do not ask first" },
1774
1922
  grace: { type: "string", description: "with --force, how long SIGTERM gets before SIGKILL (5s)" }
@@ -1812,7 +1960,7 @@ function refusal(row, proc, guard) {
1812
1960
  return reason === undefined ? undefined : `pid ${row.pid} is ${reason}`;
1813
1961
  }
1814
1962
  function render2(rows) {
1815
- const colors = paint(process12.stdout);
1963
+ const colors = paint(process14.stdout);
1816
1964
  const cells = rows.map((row) => [
1817
1965
  colors.cyan(String(row.port)),
1818
1966
  row.protocol,
@@ -1824,7 +1972,7 @@ function render2(rows) {
1824
1972
  return table([["PORT", "PROTO", "ADDRESS", "PID", "COMMAND", "CWD"], ...cells], { header: true });
1825
1973
  }
1826
1974
  async function stop(port, rows, procs, values) {
1827
- const guard = { uid: process12.getuid?.() ?? -1, mine: new Set(ancestry(process12.pid, procs)) };
1975
+ const guard = { uid: process14.getuid?.() ?? -1, mine: new Set(ancestry(process14.pid, procs)) };
1828
1976
  const targets = new Map;
1829
1977
  for (const row of rows) {
1830
1978
  const reason = refusal(row, row.pid === undefined ? undefined : procs.get(row.pid), guard);
@@ -1837,7 +1985,7 @@ async function stop(port, rows, procs, values) {
1837
1985
  return 1;
1838
1986
  const names = [...targets].map(([pid, row]) => `${pid} (${truncate(row.command ?? "", 40)})`).join(", ");
1839
1987
  if (values.yes !== true) {
1840
- if (!process12.stdin.isTTY)
1988
+ if (!process14.stdin.isTTY)
1841
1989
  fail(`stopping ${names} needs a terminal to ask on: pass --yes`, 2);
1842
1990
  if (await confirm(`Stop ${names}?`, { default: false }) !== true)
1843
1991
  return 1;
@@ -1860,13 +2008,15 @@ async function ports(args) {
1860
2008
  "ports --json"
1861
2009
  ]
1862
2010
  });
2011
+ if (values.watch !== undefined)
2012
+ return watching(values.watch, async () => ports(withoutWatch(args)));
1863
2013
  const [given] = positionals;
1864
2014
  const port = given === undefined ? undefined : wholeNumber(given, "<port>", 0);
1865
2015
  if (port !== undefined && port > 65535)
1866
2016
  badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`);
1867
2017
  if (values.kill === true && port === undefined)
1868
2018
  badUsage("--kill takes the port to free: ports <port> --kill");
1869
- const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process12.getuid?.())]);
2019
+ const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process14.getuid?.())]);
1870
2020
  const byPid = new Map(procs.map((proc) => [proc.pid, proc]));
1871
2021
  const wanted = sockets.filter((socket) => port === undefined || socket.port === port);
1872
2022
  const needsDocker = wanted.some((socket) => {
@@ -1887,14 +2037,14 @@ async function ports(args) {
1887
2037
  console.log(render2(rows));
1888
2038
  const unknown = rows.filter((row) => row.pid === undefined && row.container === undefined).length;
1889
2039
  if (unknown > 0)
1890
- console.error(paint(process12.stderr).dim(`${unknown} ${unknown === 1 ? "port has" : "ports have"} an owner this user cannot read, shown as -`));
2040
+ console.error(paint(process14.stderr).dim(`${unknown} ${unknown === 1 ? "port has" : "ports have"} an owner this user cannot read, shown as -`));
1891
2041
  return 0;
1892
2042
  }
1893
2043
 
1894
2044
  // src/procs.ts
1895
2045
  import { existsSync } from "fs";
1896
2046
  import { homedir as homedir2 } from "os";
1897
- import process13 from "process";
2047
+ import process15 from "process";
1898
2048
 
1899
2049
  // src/select.ts
1900
2050
  import { basename as basename3, join as join3, relative } from "path";
@@ -2019,7 +2169,8 @@ A process is listed when it is a dev tool (bun, node, vite, nuxt, next, chromium
2019
2169
  Exits 0 when it listed or stopped everything, 1 when a process survived SIGKILL, 2 on a usage error.`;
2020
2170
  var options3 = {
2021
2171
  json: jsonOption("{ groups: [{ origin, kind, count, rss, oldestSeconds, tools, orphans, pids, processes }], skipped }"),
2022
- kill: { type: "boolean", description: "stop the listed processes: a dry run without --yes" },
2172
+ kill: { type: "boolean", conflicts: ["watch"], description: "stop the listed processes: a dry run without --yes" },
2173
+ watch: watchOption("the processes"),
2023
2174
  yes: { type: "boolean", short: "y", description: "with --kill, really stop them, without asking" },
2024
2175
  "min-mem": { type: "string", description: "heavy from this resident size (500M), and the least a left over process must use to be listed; a bare number counts megabytes" },
2025
2176
  older: { type: "string", description: "only processes at least this old: 30m, 2h, 1d" },
@@ -2042,7 +2193,7 @@ function summary(group) {
2042
2193
  };
2043
2194
  }
2044
2195
  function render3(groups) {
2045
- const colors = paint(process13.stdout);
2196
+ const colors = paint(process15.stdout);
2046
2197
  const rows = groups.map((group) => [
2047
2198
  group.origin,
2048
2199
  String(group.members.length),
@@ -2066,10 +2217,12 @@ async function procs(args) {
2066
2217
  const minMem = values["min-mem"] === undefined ? undefined : parseSize(values["min-mem"], 1024 ** 2);
2067
2218
  if (values["min-mem"] !== undefined && minMem === undefined)
2068
2219
  fail(`--min-mem takes a size such as 500M or 1.5G, not ${values["min-mem"]}`, 2);
2220
+ if (values.watch !== undefined)
2221
+ return watching(values.watch, async () => procs(withoutWatch(args)));
2069
2222
  const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0, "m");
2070
- const uid = process13.getuid?.() ?? -1;
2223
+ const uid = process15.getuid?.() ?? -1;
2071
2224
  const all = await snapshot("/proc", (owner) => owner === uid);
2072
- const mine = new Set(ancestry(process13.pid, new Map(all.map((proc) => [proc.pid, proc]))));
2225
+ const mine = new Set(ancestry(process15.pid, new Map(all.map((proc) => [proc.pid, proc]))));
2073
2226
  const { groups, protectedCount } = selectGroups(all, { guard: { uid, mine }, now: Date.now(), home: homedir2(), exists: existsSync, minMem, olderMs });
2074
2227
  const pids = groups.flatMap((group) => group.members.map(({ proc }) => proc.pid));
2075
2228
  const show = (extra = {}) => {
@@ -2081,7 +2234,7 @@ async function procs(args) {
2081
2234
  if (values.kill !== true || pids.length === 0 || values.yes !== true) {
2082
2235
  show();
2083
2236
  if (values.json !== true && protectedCount > 0)
2084
- console.error(paint(process13.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`));
2237
+ console.error(paint(process15.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`));
2085
2238
  if (values.kill === true && pids.length > 0)
2086
2239
  console.error(`dry run: would stop ${pids.length} ${pids.length === 1 ? "process" : "processes"} (${pids.join(" ")}), pass --yes to do it`);
2087
2240
  return 0;
@@ -2096,7 +2249,7 @@ async function procs(args) {
2096
2249
  }
2097
2250
 
2098
2251
  // src/proc-cli.ts
2099
- process14.exitCode = await runCli({
2252
+ process16.exitCode = await runCli({
2100
2253
  name: "proc",
2101
2254
  about: "what a process is, who listens on a port and which dev processes are worth cleaning, read from /proc",
2102
2255
  replaces: "cat /proc/<pid>/..., ss -ltnp, lsof -i and pgrep -f one-liners",