@kaynooo/cli-base 0.9.0 → 0.11.1

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/proof-cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/proof-cli.ts
5
- import process16 from "process";
5
+ import process18 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -321,6 +321,23 @@ var STATUS_WORDS = {
321
321
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
322
322
 
323
323
  // ../kit/src/format.ts
324
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
325
+ function formatSeconds(total) {
326
+ let rest = Math.max(0, Math.round(total));
327
+ const amounts = UNITS.map(([unit, size]) => {
328
+ const amount = Math.floor(rest / size);
329
+ rest -= amount * size;
330
+ return `${amount}${unit}`;
331
+ });
332
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
333
+ if (first === -1)
334
+ return "0s";
335
+ const next = amounts[first + 1];
336
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
337
+ }
338
+ function formatDuration(ms) {
339
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
340
+ }
324
341
  function upTo(text, separator) {
325
342
  const end = text.indexOf(separator);
326
343
  return end === -1 ? text : text.slice(0, end);
@@ -335,24 +352,20 @@ function printJson(value) {
335
352
 
336
353
  // ../kit/src/help.ts
337
354
  import process8 from "process";
338
- var OPTIONAL = /\[[^\]]+\]/g;
355
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
339
356
  var USAGE_PREFIX = /^usage:\s*/i;
340
357
  var FULL_STOP = /\.$/;
341
358
  function usageLine(usage, colors = paint(process8.stdout)) {
342
359
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
343
360
  }
344
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
345
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
361
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
362
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
346
363
  `);
347
364
  }
348
365
  function exitRows(exits, colors = paint(process8.stdout)) {
349
366
  if (exits.length === 0)
350
367
  return [];
351
- const width = Math.max(...exits.map(([code]) => String(code).length));
352
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
353
- }
354
- function replacesRows(replaces, colors = paint(process8.stdout)) {
355
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
368
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
356
369
  }
357
370
  function wantsHelpJson(env = process8.env) {
358
371
  return env.KIT_HELP === "json";
@@ -378,29 +391,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
378
391
  return [];
379
392
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
380
393
  }
394
+ var MAX_INLINE_CHOICES = 24;
381
395
  function optionRows(options, colors = paint(process8.stdout)) {
382
396
  const rows = Object.entries(options).map(([name, option]) => {
383
397
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
384
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
398
+ const choices = option.choices?.join("|");
399
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
400
+ const named = inline ? `<${choices}>` : "<value>";
385
401
  const placeholder = option.optional === undefined ? named : `[${named}]`;
386
402
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
387
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
403
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
404
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
388
405
  });
389
406
  const width = Math.max(0, ...rows.map((row) => row.width));
390
407
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
391
408
  }
392
409
 
393
410
  // ../kit/src/text.ts
394
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
395
411
  function distance(a, b) {
396
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
397
- for (const [i, left] of [...a].entries()) {
412
+ const left = [...a];
413
+ const right = [...b];
414
+ let before = [];
415
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
416
+ for (const [i, x] of left.entries()) {
398
417
  const current = [i + 1];
399
- for (const [j, right] of [...b].entries())
400
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
418
+ for (const [j, y] of right.entries()) {
419
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
420
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
421
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
422
+ current.push(cost);
423
+ }
424
+ before = previous;
401
425
  previous = current;
402
426
  }
403
- return previous[b.length] ?? 0;
427
+ return previous[right.length] ?? 0;
404
428
  }
405
429
  function closest(name, names) {
406
430
  const started = names.find((known) => known.startsWith(name));
@@ -419,6 +443,17 @@ function wholeNumber(value, name, fallback, min = 1) {
419
443
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
420
444
  return number;
421
445
  }
446
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
447
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
448
+ function duration(value, name, fallback, unit = "s") {
449
+ if (value === undefined)
450
+ return fallback;
451
+ const match = DURATION.exec(value.trim());
452
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
453
+ if (ms < 1)
454
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
455
+ return ms;
456
+ }
422
457
 
423
458
  // ../kit/src/args.ts
424
459
  var DASHES = /^-+/;
@@ -465,7 +500,7 @@ class Completing {
465
500
  }
466
501
  var completion = { active: false };
467
502
  var OUTPUT_OPTIONS = {
468
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
503
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
469
504
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
470
505
  };
471
506
  function applyOutput(color, plain, env = process9.env) {
@@ -637,9 +672,33 @@ function nearestOption(message, options, allowNegative) {
637
672
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
638
673
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
639
674
  }
675
+ // ../kit/src/argv.ts
676
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
677
+ import { resolve as resolve3 } from "path";
678
+ import process10 from "process";
679
+ function commandLine() {
680
+ try {
681
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
682
+ } catch {
683
+ return;
684
+ }
685
+ }
686
+ function realPath(word) {
687
+ try {
688
+ return realpathSync(resolve3(word));
689
+ } catch {
690
+ return;
691
+ }
692
+ }
693
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
694
+ const target = script === undefined ? undefined : realPath(script) ?? script;
695
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
696
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
697
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
698
+ }
640
699
  // ../kit/src/process.ts
641
700
  import { constants } from "os";
642
- import process10 from "process";
701
+ import process11 from "process";
643
702
  var KILL_GRACE_MS = 2000;
644
703
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
645
704
  function exitCodeOf(code, signal) {
@@ -661,7 +720,7 @@ function holdSignals(cleanup) {
661
720
  },
662
721
  release: () => {
663
722
  for (const signal of SIGNALS)
664
- process10.off(signal, onSignal);
723
+ process11.off(signal, onSignal);
665
724
  }
666
725
  };
667
726
  function onSignal(signal) {
@@ -674,10 +733,10 @@ function holdSignals(cleanup) {
674
733
  return;
675
734
  held.release();
676
735
  cleanup(signal);
677
- process10.kill(process10.pid, signal);
736
+ process11.kill(process11.pid, signal);
678
737
  }
679
738
  for (const signal of SIGNALS)
680
- process10.on(signal, onSignal);
739
+ process11.on(signal, onSignal);
681
740
  return held;
682
741
  }
683
742
  async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
@@ -691,7 +750,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
691
750
  return;
692
751
  try {
693
752
  if (grouped)
694
- process10.kill(-proc.pid, killing);
753
+ process11.kill(-proc.pid, killing);
695
754
  else
696
755
  proc.kill(killing);
697
756
  } catch {}
@@ -765,15 +824,93 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
765
824
  var RESET_STYLE = `${ESC}[0m`;
766
825
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
767
826
  // ../kit/src/cli.ts
768
- import { readFileSync as readFileSync2, realpathSync } from "fs";
827
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
769
828
  import { dirname as dirname3, join as join5 } from "path";
829
+ import process14 from "process";
830
+
831
+ // ../kit/src/completions.ts
832
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
833
+ 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'
834
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
835
+ set -l current (commandline -ct)
836
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
837
+ if test "$line" = __files__
838
+ __fish_complete_path $current
839
+ else
840
+ echo $line
841
+ end
842
+ end
843
+ end`;
844
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
845
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
846
+ local -a lines
847
+ COMPREPLY=()
848
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
849
+ for line in "\${lines[@]}"; do
850
+ if [[ $line == __files__ ]]; then
851
+ COMPREPLY+=($(compgen -f -- "$cur"))
852
+ else
853
+ words+="\${line%%$'\\t'*}"$'\\n'
854
+ fi
855
+ done
856
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
857
+ }`;
858
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
859
+ local line
860
+ local -a described plain
861
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
862
+ if [[ $line == __files__ ]]; then
863
+ _files
864
+ elif [[ $line == *$'\\t'* ]]; then
865
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
866
+ else
867
+ plain+=("$line")
868
+ fi
869
+ done
870
+ (( \${#described} )) && _describe -V value described
871
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
872
+ return 0
873
+ }`;
874
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
875
+ if (shell === "fish")
876
+ return `${header}
877
+ ${FISH_FUNCTION}
878
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
879
+ `).join("")}`;
880
+ if (shell === "bash")
881
+ return `${header}
882
+ ${BASH_FUNCTION}
883
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
884
+ `;
885
+ return `${header}
886
+ ${ZSH_FUNCTION}
887
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
888
+ `;
889
+ }
890
+
891
+ // ../kit/src/notify.ts
770
892
  import process12 from "process";
893
+ var NOTIFY_AFTER_MS = 1e4;
894
+ var CANCELLED = 130;
895
+ function base64(text) {
896
+ return Buffer.from(text).toString("base64");
897
+ }
898
+ function notification(title, body, env = process12.env) {
899
+ const id = `kit${process12.pid}`;
900
+ 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\\`];
901
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
902
+ }
903
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
904
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
905
+ return;
906
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
907
+ }
771
908
 
772
909
  // ../kit/src/usage.ts
773
910
  import { appendFileSync, mkdirSync } from "fs";
774
911
  import { homedir as homedir3 } from "os";
775
912
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
776
- import process11 from "process";
913
+ import process13 from "process";
777
914
 
778
915
  // ../kit/src/logs.ts
779
916
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -787,14 +924,14 @@ var usageError;
787
924
  function noteUsageError(message) {
788
925
  usageError = message;
789
926
  }
790
- function stateHome(env = process11.env) {
927
+ function stateHome(env = process13.env) {
791
928
  const dir = env.XDG_STATE_HOME;
792
929
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
793
930
  }
794
- function usagePath(env = process11.env) {
931
+ function usagePath(env = process13.env) {
795
932
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
796
933
  }
797
- function usageRecorded(env = process11.env) {
934
+ function usageRecorded(env = process13.env) {
798
935
  const off = env.KAYNOOO_CLI_NO_USAGE;
799
936
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
800
937
  }
@@ -808,7 +945,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
808
945
  usageError = undefined;
809
946
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
810
947
  }
811
- function recordUsage(entry, env = process11.env) {
948
+ function recordUsage(entry, env = process13.env) {
812
949
  if (!usageRecorded(env))
813
950
  return;
814
951
  try {
@@ -824,7 +961,11 @@ var LEVEL_OPTIONS = {
824
961
  ...OUTPUT_OPTIONS,
825
962
  help: { type: "boolean", short: "h", description: "show this help" }
826
963
  };
827
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
964
+ var TOP_OPTIONS = {
965
+ ...LEVEL_OPTIONS,
966
+ version: { type: "boolean", short: "v", description: "print the version" },
967
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
968
+ };
828
969
  async function commandRows(all, colors) {
829
970
  const commands = shown(all);
830
971
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -885,7 +1026,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
885
1026
  header(colors, summary),
886
1027
  "",
887
1028
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
888
- ...replacesRows(replaces, colors),
889
1029
  "",
890
1030
  ...await commandRows(commands, colors),
891
1031
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -899,8 +1039,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
899
1039
  `);
900
1040
  }
901
1041
  function printError(prefix, message, hint, cause) {
902
- const colors = paint(process12.stderr);
903
- const styled = takesControlCodes(process12.stderr);
1042
+ const colors = paint(process14.stderr);
1043
+ const styled = takesControlCodes(process14.stderr);
904
1044
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
905
1045
  const under = (label, text, tint) => text === undefined ? "" : `
906
1046
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -943,11 +1083,11 @@ async function dispatch(level, typed, { version, redact }) {
943
1083
  }
944
1084
  }
945
1085
  if (name === undefined && level.path.length > 1) {
946
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stderr));
1086
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
947
1087
  return 2;
948
1088
  }
949
1089
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
950
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stdout));
1090
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
951
1091
  return 0;
952
1092
  }
953
1093
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1003,24 +1143,24 @@ function candidateLine(candidate) {
1003
1143
  }
1004
1144
  function positionalBeingTyped(before, { options, positionals }) {
1005
1145
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1006
- let index = 0;
1146
+ const typed = [];
1007
1147
  let at = 0;
1008
1148
  while (at < before.length) {
1009
1149
  const word = before[at];
1010
1150
  if (word === "--") {
1011
- index += before.length - at - 1;
1151
+ typed.push(...before.slice(at + 1));
1012
1152
  break;
1013
1153
  }
1014
1154
  if (!word.startsWith("-"))
1015
- index++;
1155
+ typed.push(word);
1016
1156
  else if (takesValue(word))
1017
1157
  at++;
1018
1158
  at++;
1019
1159
  }
1020
1160
  const last = positionals.at(-1);
1021
- if (index < positionals.length)
1022
- return positionals[index];
1023
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1161
+ if (typed.length < positionals.length)
1162
+ return { name: positionals[typed.length], typed };
1163
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1024
1164
  }
1025
1165
  async function leafCandidates(run, words) {
1026
1166
  const completing = await completingOf(run);
@@ -1028,12 +1168,12 @@ async function leafCandidates(run, words) {
1028
1168
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1029
1169
  const flag = words.at(-2);
1030
1170
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1171
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1031
1172
  if (option?.type === "string") {
1032
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1173
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1033
1174
  return values === undefined ? [FILES] : values.map(candidateLine);
1034
1175
  }
1035
- const name = positionalBeingTyped(words.slice(0, -1), completing);
1036
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1176
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1037
1177
  return values === undefined ? [FILES] : values.map(candidateLine);
1038
1178
  }
1039
1179
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -1058,15 +1198,32 @@ async function candidates(scope, defaultCommand, words, before = []) {
1058
1198
  }
1059
1199
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1060
1200
  }
1201
+ var COMPLETIONS = "--completions";
1202
+ function flagValue([flag = "", ...rest]) {
1203
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1204
+ }
1205
+ function printCompletionScript(name, args) {
1206
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1207
+ if (shell === undefined || args.length !== 1) {
1208
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1209
+ return 2;
1210
+ }
1211
+ console.log(completionScript(shell, [name]).trimEnd());
1212
+ return 0;
1213
+ }
1061
1214
  async function printCandidates(found) {
1062
1215
  for (const line of await found)
1063
1216
  console.log(line);
1064
1217
  return 0;
1065
1218
  }
1066
1219
  function packageVersion(entry = Bun.main) {
1067
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1220
+ let resolved = entry;
1221
+ try {
1222
+ resolved = realpathSync2(entry);
1223
+ } catch {}
1224
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1068
1225
  try {
1069
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
1226
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1070
1227
  if (typeof version === "string")
1071
1228
  return version;
1072
1229
  } catch {}
@@ -1074,14 +1231,19 @@ function packageVersion(entry = Bun.main) {
1074
1231
  return "0.0.0";
1075
1232
  }
1076
1233
  }
1077
- async function runCli(cli, argv = process12.argv.slice(2)) {
1234
+ async function runCli(cli, argv = scriptArgs()) {
1078
1235
  const version = cli.version ?? packageVersion();
1079
1236
  if (argv[0] === COMPLETE)
1080
1237
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1238
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1239
+ return printCompletionScript(cli.name, flagValue(argv));
1240
+ const started = performance.now();
1081
1241
  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 });
1242
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1243
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1082
1244
  if (cli.usage !== false) {
1083
1245
  try {
1084
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1246
+ recordUsage(usageEntry(cli.name, command, argv, code));
1085
1247
  } catch {}
1086
1248
  }
1087
1249
  return code;
@@ -1101,19 +1263,23 @@ function commandPath(scope, argv) {
1101
1263
  }
1102
1264
  return path.length === 0 ? undefined : path.join(" ");
1103
1265
  }
1104
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1266
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1105
1267
  if (argv[0] === COMPLETE)
1106
1268
  return printCandidates(leafCandidates(run, argv.slice(1)));
1269
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1270
+ return printCompletionScript(name, flagValue(argv));
1107
1271
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1108
1272
  console.log(version ?? packageVersion());
1109
1273
  return 0;
1110
1274
  }
1111
1275
  let code;
1276
+ const started = performance.now();
1112
1277
  try {
1113
1278
  code = await run(argv);
1114
1279
  } catch (error) {
1115
1280
  code = reportThrown(name, error, redact, wantsJson(argv));
1116
1281
  }
1282
+ notifyEnd(name, code, performance.now() - started);
1117
1283
  if (usage !== false) {
1118
1284
  try {
1119
1285
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1130,13 +1296,13 @@ var {Glob } = globalThis.Bun;
1130
1296
  var SESSION_FILES = new Glob("*.json");
1131
1297
  var ACCOUNT_DIRS = new Glob("*/sessions");
1132
1298
  // src/proof.ts
1133
- import process15 from "process";
1299
+ import process17 from "process";
1134
1300
 
1135
1301
  // src/worktree.ts
1136
- import { cpSync, existsSync as existsSync3, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync2, rmSync, symlinkSync, unlinkSync } from "fs";
1302
+ import { cpSync, existsSync as existsSync3, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync3, rmSync, symlinkSync, unlinkSync } from "fs";
1137
1303
  import { tmpdir } from "os";
1138
- import { basename, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative, resolve as resolve3, sep } from "path";
1139
- import process14 from "process";
1304
+ import { basename, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative, resolve as resolve4, sep } from "path";
1305
+ import process16 from "process";
1140
1306
  var WHITESPACE = /\s/;
1141
1307
  var ORIGIN_PREFIX = /^origin\//;
1142
1308
  var ENV_FILE = /^\.env(?:\..+)?$/;
@@ -1182,12 +1348,12 @@ async function defaultProofRef(root) {
1182
1348
  return base.code === 0 && stdoutOf(base) !== stdoutOf(head) ? stdoutOf(base) : "HEAD";
1183
1349
  }
1184
1350
  function keptPaths(root, cwd, paths) {
1185
- const realRoot = realpathSync2(root);
1351
+ const realRoot = realpathSync3(root);
1186
1352
  return paths.map((path) => {
1187
- const absolute = resolve3(cwd, path);
1353
+ const absolute = resolve4(cwd, path);
1188
1354
  if (!existsSync3(dirname4(absolute)))
1189
1355
  fail(`--keep ${path}: no such file`);
1190
- const inRepo = relative(realRoot, join6(realpathSync2(dirname4(absolute)), basename(absolute)));
1356
+ const inRepo = relative(realRoot, join6(realpathSync3(dirname4(absolute)), basename(absolute)));
1191
1357
  if (inRepo === "" || inRepo === ".." || inRepo.startsWith(PARENT) || isAbsolute2(inRepo))
1192
1358
  fail(`--keep ${path} is outside the repository`);
1193
1359
  if (!existsSync3(absolute))
@@ -1260,7 +1426,7 @@ function moduleLinks(root, folder) {
1260
1426
  }
1261
1427
  function workspaceTarget(root, path) {
1262
1428
  try {
1263
- const inRepo = relative(realpathSync2(root), realpathSync2(join6(root, path)));
1429
+ const inRepo = relative(realpathSync3(root), realpathSync3(join6(root, path)));
1264
1430
  return inRepo === "" || inRepo.startsWith(PARENT) || inRepo.split(sep).includes("node_modules") ? undefined : inRepo;
1265
1431
  } catch {
1266
1432
  return;
@@ -1292,7 +1458,7 @@ async function sweepStale(root) {
1292
1458
  continue;
1293
1459
  const path = join6(tmpdir(), name);
1294
1460
  const stat = lstatSync(path, { throwIfNoEntry: false });
1295
- if (stat?.isDirectory() === true && stat.uid === process14.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1461
+ if (stat?.isDirectory() === true && stat.uid === process16.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1296
1462
  rmSync(path, { recursive: true, force: true });
1297
1463
  }
1298
1464
  await git2(["worktree", "prune"], root);
@@ -1310,7 +1476,8 @@ function shellCommand(given) {
1310
1476
  const [only] = given;
1311
1477
  return given.length === 1 && only !== undefined && WHITESPACE.test(only) ? ["sh", "-c", only] : given;
1312
1478
  }
1313
- async function runIn(dir, command, signals, capture = false) {
1479
+ var TIMEOUT_DRAIN_MS = 500;
1480
+ async function runIn(dir, command, signals, capture = false, timeoutMs) {
1314
1481
  if (signals.signal !== undefined)
1315
1482
  return { code: exitCodeOf(null, signals.signal), output: "", started: true };
1316
1483
  let child;
@@ -1321,10 +1488,16 @@ async function runIn(dir, command, signals, capture = false) {
1321
1488
  }
1322
1489
  signals.forward(child);
1323
1490
  const chunks = [];
1324
- if (capture)
1325
- await Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]);
1491
+ let timedOut = false;
1492
+ const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
1493
+ timedOut = true;
1494
+ child.kill("SIGKILL");
1495
+ }, timeoutMs);
1496
+ const collected = capture ? Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]) : Promise.resolve([]);
1326
1497
  await child.exited;
1327
- return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true };
1498
+ clearTimeout(timer);
1499
+ await (timedOut ? Promise.race([collected, Bun.sleep(TIMEOUT_DRAIN_MS)]) : collected);
1500
+ return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true, ...timedOut ? { timedOut } : {} };
1328
1501
  }
1329
1502
  async function collect(stream, chunks) {
1330
1503
  for await (const chunk of stream)
@@ -1363,19 +1536,20 @@ async function inWorktree(options, body) {
1363
1536
  }
1364
1537
 
1365
1538
  // src/proof.ts
1366
- var USAGE = `proof [--ref <rev>] [--runs <n>] [--keep <path>...] [--no-link] [--json] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, then in the working tree, to show that a test fails before a change and passes after it
1539
+ var USAGE = `proof [--ref <rev>] [--runs <n>] [--keep <path>...] [--timeout <duration>] [--no-link] [--json] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, then in the working tree, to show that a test fails before a change and passes after it
1367
1540
 
1368
- The ref defaults to the merge base with the default branch of origin (origin/main unless origin/HEAD names another) when HEAD is on a branch ahead of it, else HEAD. --runs <n> runs the command n times now, for a flaky test, and every run must pass.`;
1369
- var EXITS = [[0, "the command fails before and passes in every run now"], [1, "it passes before too, fails in any run now, or passes before and fails now"], [2, "a usage error, an unknown ref, a command that cannot start or ends with exit 126, 127 or a signal"], [130, "interrupted (128 plus the signal)"]];
1541
+ The ref defaults to the merge base with the default branch of origin (origin/main unless origin/HEAD names another) when HEAD is on a branch ahead of it, else HEAD. --runs <n> runs the command n times now, for a flaky test, and every run must pass. --timeout kills a run that lasts longer (a hung test), which says nothing about the change and ends with exit 2.`;
1542
+ var EXITS = [[0, "the command fails before and passes in every run now"], [1, "it passes before too, fails in any run now, or passes before and fails now"], [2, "a usage error, an unknown ref, a command that cannot start, ends with exit 126, 127, 125 or a signal, or runs past --timeout"], [130, "interrupted (128 plus the signal)"]];
1370
1543
  var OPTIONS = {
1371
1544
  ref: { type: "string", short: "r", description: "the commit to run before at (default: the merge base with the default branch of origin on a branch ahead of it, else HEAD)" },
1372
1545
  runs: { type: "string", short: "n", description: "run the command this many times now, every run must pass (1)" },
1373
1546
  keep: { type: "string", short: "k", multiple: true, description: "a working-tree file or folder copied over to the ref, such as the new test, repeatable" },
1547
+ timeout: { type: "string", short: "t", description: "kill each run lasting longer than this (30s, 5m, 1h), a result of neither side" },
1374
1548
  "no-link": { type: "boolean", description: "do not link the ignored env files, node_modules, vendor and .venv of the checkout" },
1375
1549
  json: jsonOption("{outcome, proved, ref, sha, before: {code, output}, now: {code, output}}")
1376
1550
  };
1377
1551
  function abnormal(code) {
1378
- return code === 126 || code === 127 || code > 128 && code < 160;
1552
+ return code === 125 || code === 126 || code === 127 || code > 128 && code < 160;
1379
1553
  }
1380
1554
  function outcomeOf(before, now) {
1381
1555
  const failed = now.filter((code) => code !== 0).length;
@@ -1412,19 +1586,20 @@ ${USAGE}`);
1412
1586
  if (runsInContainer(given))
1413
1587
  fail("a container of the compose project mounts the main checkout, not the temporary worktree, so the command would not run at the ref: run the tool on the host, or check the ref out by hand");
1414
1588
  const command = shellCommand(given);
1415
- const cwd = process15.cwd();
1589
+ const cwd = process17.cwd();
1416
1590
  const { root, prefix } = await checkout(cwd);
1417
1591
  const runs = wholeNumber(parsed.values.runs, "runs", 1, 1);
1418
1592
  const ref = parsed.values.ref ?? await defaultProofRef(root);
1419
1593
  const sha = await resolveRef(root, ref);
1420
1594
  const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
1595
+ const timeoutMs = parsed.values.timeout === undefined ? undefined : duration(parsed.values.timeout, "timeout", 0);
1421
1596
  const signals = holdSignals();
1422
1597
  let before;
1423
1598
  const nowRuns = [];
1424
1599
  try {
1425
- before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true));
1600
+ before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true, timeoutMs));
1426
1601
  for (let i = 0;i < runs && signals.signal === undefined; i++)
1427
- nowRuns.push(await runIn(cwd, command, signals, true));
1602
+ nowRuns.push(await runIn(cwd, command, signals, true, timeoutMs));
1428
1603
  } finally {
1429
1604
  signals.release();
1430
1605
  }
@@ -1433,6 +1608,10 @@ ${USAGE}`);
1433
1608
  for (const [run, where] of [[before, `at ${sha.slice(0, 7)}`], ...nowRuns.map((each, i) => [each, runs > 1 ? `now (run ${i + 1})` : "now"])]) {
1434
1609
  if (!run.started)
1435
1610
  fail(run.output);
1611
+ if (run.timedOut === true)
1612
+ fail(`the command ran past --timeout ${parsed.values.timeout} ${where} and was killed, which says nothing about the change${run.output.trim() === "" ? "" : `
1613
+
1614
+ ${folded(run.output)}`}`);
1436
1615
  if (abnormal(run.code))
1437
1616
  fail(`the command did not run properly ${where}: exit ${run.code}, a missing command or a kill, not a test result${run.output.trim() === "" ? "" : `
1438
1617
 
@@ -1447,7 +1626,7 @@ ${folded(run.output)}`}`);
1447
1626
  printJson({ outcome, proved, ref, sha, before: { code: before.code, output: before.output }, now: { code: now.code, output: now.output }, runs: nowRuns.map((run) => ({ code: run.code })) });
1448
1627
  return proved ? 0 : 1;
1449
1628
  }
1450
- console.log(role(proved ? "ok" : "problem", process15.stdout)(message));
1629
+ console.log(role(proved ? "ok" : "problem", process17.stdout)(message));
1451
1630
  if (runs > 1)
1452
1631
  console.log(`now: ${codes.map((code, i) => `run ${i + 1} ${code === 0 ? "passed" : `failed (exit ${code})`}`).join(", ")}`);
1453
1632
  const shown = side === "before" ? before : now;
@@ -1458,4 +1637,4 @@ ${folded(shown.output)}`);
1458
1637
  }
1459
1638
 
1460
1639
  // src/proof-cli.ts
1461
- process16.exitCode = await runMain({ name: "proof", run: proof });
1640
+ process18.exitCode = await runMain({ name: "proof", run: proof });