@kaynooo/cli-stack 0.7.0 → 0.7.2

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.
Files changed (2) hide show
  1. package/dist/cli.js +217 -63
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process15 from "process";
5
+ import process17 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -317,6 +317,9 @@ function marked(mark, text, stream, detail, env = process6.env) {
317
317
  }
318
318
  return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
319
319
  }
320
+ function warn(text, detail) {
321
+ console.error(marked("warn", text, process6.stderr, detail));
322
+ }
320
323
  var STATUS_WORDS = {
321
324
  passed: ["passed", "success", "succeeded", "ok"],
322
325
  failed: ["failed", "failure", "error", "errored"],
@@ -327,6 +330,23 @@ var STATUS_WORDS = {
327
330
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
328
331
 
329
332
  // ../kit/src/format.ts
333
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
334
+ function formatSeconds(total) {
335
+ let rest = Math.max(0, Math.round(total));
336
+ const amounts = UNITS.map(([unit, size]) => {
337
+ const amount = Math.floor(rest / size);
338
+ rest -= amount * size;
339
+ return `${amount}${unit}`;
340
+ });
341
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
342
+ if (first === -1)
343
+ return "0s";
344
+ const next = amounts[first + 1];
345
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
346
+ }
347
+ function formatDuration(ms) {
348
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
349
+ }
330
350
  function upTo(text, separator) {
331
351
  const end = text.indexOf(separator);
332
352
  return end === -1 ? text : text.slice(0, end);
@@ -341,24 +361,20 @@ function printJson(value) {
341
361
 
342
362
  // ../kit/src/help.ts
343
363
  import process8 from "process";
344
- var OPTIONAL = /\[[^\]]+\]/g;
364
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
345
365
  var USAGE_PREFIX = /^usage:\s*/i;
346
366
  var FULL_STOP = /\.$/;
347
367
  function usageLine(usage, colors = paint(process8.stdout)) {
348
368
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
349
369
  }
350
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
351
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
370
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
371
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
352
372
  `);
353
373
  }
354
374
  function exitRows(exits, colors = paint(process8.stdout)) {
355
375
  if (exits.length === 0)
356
376
  return [];
357
- const width = Math.max(...exits.map(([code]) => String(code).length));
358
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
359
- }
360
- function replacesRows(replaces, colors = paint(process8.stdout)) {
361
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
377
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
362
378
  }
363
379
  function wantsHelpJson(env = process8.env) {
364
380
  return env.KIT_HELP === "json";
@@ -384,29 +400,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
384
400
  return [];
385
401
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
386
402
  }
403
+ var MAX_INLINE_CHOICES = 24;
387
404
  function optionRows(options, colors = paint(process8.stdout)) {
388
405
  const rows = Object.entries(options).map(([name, option]) => {
389
406
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
390
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
407
+ const choices = option.choices?.join("|");
408
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
409
+ const named = inline ? `<${choices}>` : "<value>";
391
410
  const placeholder = option.optional === undefined ? named : `[${named}]`;
392
411
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
393
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
412
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
413
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
394
414
  });
395
415
  const width = Math.max(0, ...rows.map((row) => row.width));
396
416
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
397
417
  }
398
418
 
399
419
  // ../kit/src/text.ts
400
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
401
420
  function distance(a, b) {
402
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
403
- for (const [i, left] of [...a].entries()) {
421
+ const left = [...a];
422
+ const right = [...b];
423
+ let before = [];
424
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
425
+ for (const [i, x] of left.entries()) {
404
426
  const current = [i + 1];
405
- for (const [j, right] of [...b].entries())
406
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
427
+ for (const [j, y] of right.entries()) {
428
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
429
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
430
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
431
+ current.push(cost);
432
+ }
433
+ before = previous;
407
434
  previous = current;
408
435
  }
409
- return previous[b.length] ?? 0;
436
+ return previous[right.length] ?? 0;
410
437
  }
411
438
  function closest(name, names) {
412
439
  const started = names.find((known) => known.startsWith(name));
@@ -471,7 +498,7 @@ class Completing {
471
498
  }
472
499
  var completion = { active: false };
473
500
  var OUTPUT_OPTIONS = {
474
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
501
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
475
502
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
476
503
  };
477
504
  function applyOutput(color, plain, env = process9.env) {
@@ -643,21 +670,123 @@ function nearestOption(message, options, allowNegative) {
643
670
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
644
671
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
645
672
  }
673
+ // ../kit/src/argv.ts
674
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
675
+ import { resolve as resolve3 } from "path";
676
+ import process10 from "process";
677
+ function commandLine() {
678
+ try {
679
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
680
+ } catch {
681
+ return;
682
+ }
683
+ }
684
+ function realPath(word) {
685
+ try {
686
+ return realpathSync(resolve3(word));
687
+ } catch {
688
+ return;
689
+ }
690
+ }
691
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
692
+ const target = script === undefined ? undefined : realPath(script) ?? script;
693
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
694
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
695
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
696
+ }
646
697
  // ../kit/src/progress.ts
647
698
  var ESC = String.fromCharCode(27);
648
699
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
649
700
  var RESET_STYLE = `${ESC}[0m`;
650
701
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
651
702
  // ../kit/src/cli.ts
652
- import { readFileSync as readFileSync2, realpathSync } from "fs";
703
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
653
704
  import { dirname as dirname3, join as join5 } from "path";
705
+ import process13 from "process";
706
+
707
+ // ../kit/src/completions.ts
708
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
709
+ 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'
710
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
711
+ set -l current (commandline -ct)
712
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
713
+ if test "$line" = __files__
714
+ __fish_complete_path $current
715
+ else
716
+ echo $line
717
+ end
718
+ end
719
+ end`;
720
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
721
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
722
+ local -a lines
723
+ COMPREPLY=()
724
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
725
+ for line in "\${lines[@]}"; do
726
+ if [[ $line == __files__ ]]; then
727
+ COMPREPLY+=($(compgen -f -- "$cur"))
728
+ else
729
+ words+="\${line%%$'\\t'*}"$'\\n'
730
+ fi
731
+ done
732
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
733
+ }`;
734
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
735
+ local line
736
+ local -a described plain
737
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
738
+ if [[ $line == __files__ ]]; then
739
+ _files
740
+ elif [[ $line == *$'\\t'* ]]; then
741
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
742
+ else
743
+ plain+=("$line")
744
+ fi
745
+ done
746
+ (( \${#described} )) && _describe -V value described
747
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
748
+ return 0
749
+ }`;
750
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
751
+ if (shell === "fish")
752
+ return `${header}
753
+ ${FISH_FUNCTION}
754
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
755
+ `).join("")}`;
756
+ if (shell === "bash")
757
+ return `${header}
758
+ ${BASH_FUNCTION}
759
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
760
+ `;
761
+ return `${header}
762
+ ${ZSH_FUNCTION}
763
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
764
+ `;
765
+ }
766
+
767
+ // ../kit/src/notify.ts
654
768
  import process11 from "process";
769
+ var NOTIFY_AFTER_MS = 1e4;
770
+ var CANCELLED = 130;
771
+ function base64(text) {
772
+ return Buffer.from(text).toString("base64");
773
+ }
774
+ function notification(title, body, env = process11.env) {
775
+ const id = `kit${process11.pid}`;
776
+ 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\\`];
777
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
778
+ }
779
+ function notifyEnd(command, code, ms, { stream = process11.stderr, env = process11.env } = {}) {
780
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
781
+ return;
782
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
783
+ }
655
784
 
656
785
  // ../kit/src/usage.ts
657
786
  import { appendFileSync, mkdirSync } from "fs";
658
787
  import { homedir as homedir3 } from "os";
659
788
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
660
- import process10 from "process";
789
+ import process12 from "process";
661
790
 
662
791
  // ../kit/src/logs.ts
663
792
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -671,14 +800,14 @@ var usageError;
671
800
  function noteUsageError(message) {
672
801
  usageError = message;
673
802
  }
674
- function stateHome(env = process10.env) {
803
+ function stateHome(env = process12.env) {
675
804
  const dir = env.XDG_STATE_HOME;
676
805
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
677
806
  }
678
- function usagePath(env = process10.env) {
807
+ function usagePath(env = process12.env) {
679
808
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
680
809
  }
681
- function usageRecorded(env = process10.env) {
810
+ function usageRecorded(env = process12.env) {
682
811
  const off = env.KAYNOOO_CLI_NO_USAGE;
683
812
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
684
813
  }
@@ -692,7 +821,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
692
821
  usageError = undefined;
693
822
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
694
823
  }
695
- function recordUsage(entry, env = process10.env) {
824
+ function recordUsage(entry, env = process12.env) {
696
825
  if (!usageRecorded(env))
697
826
  return;
698
827
  try {
@@ -708,7 +837,11 @@ var LEVEL_OPTIONS = {
708
837
  ...OUTPUT_OPTIONS,
709
838
  help: { type: "boolean", short: "h", description: "show this help" }
710
839
  };
711
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
840
+ var TOP_OPTIONS = {
841
+ ...LEVEL_OPTIONS,
842
+ version: { type: "boolean", short: "v", description: "print the version" },
843
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
844
+ };
712
845
  async function commandRows(all, colors) {
713
846
  const commands = shown(all);
714
847
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -769,7 +902,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
769
902
  header(colors, summary),
770
903
  "",
771
904
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
772
- ...replacesRows(replaces, colors),
773
905
  "",
774
906
  ...await commandRows(commands, colors),
775
907
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -783,8 +915,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
783
915
  `);
784
916
  }
785
917
  function printError(prefix, message, hint, cause) {
786
- const colors = paint(process11.stderr);
787
- const styled = takesControlCodes(process11.stderr);
918
+ const colors = paint(process13.stderr);
919
+ const styled = takesControlCodes(process13.stderr);
788
920
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
789
921
  const under = (label, text, tint) => text === undefined ? "" : `
790
922
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -827,11 +959,11 @@ async function dispatch(level, typed, { version, redact }) {
827
959
  }
828
960
  }
829
961
  if (name === undefined && level.path.length > 1) {
830
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process11.stderr));
962
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
831
963
  return 2;
832
964
  }
833
965
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
834
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process11.stdout));
966
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
835
967
  return 0;
836
968
  }
837
969
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -887,24 +1019,24 @@ function candidateLine(candidate) {
887
1019
  }
888
1020
  function positionalBeingTyped(before, { options, positionals }) {
889
1021
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
890
- let index = 0;
1022
+ const typed = [];
891
1023
  let at = 0;
892
1024
  while (at < before.length) {
893
1025
  const word = before[at];
894
1026
  if (word === "--") {
895
- index += before.length - at - 1;
1027
+ typed.push(...before.slice(at + 1));
896
1028
  break;
897
1029
  }
898
1030
  if (!word.startsWith("-"))
899
- index++;
1031
+ typed.push(word);
900
1032
  else if (takesValue(word))
901
1033
  at++;
902
1034
  at++;
903
1035
  }
904
1036
  const last = positionals.at(-1);
905
- if (index < positionals.length)
906
- return positionals[index];
907
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1037
+ if (typed.length < positionals.length)
1038
+ return { name: positionals[typed.length], typed };
1039
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
908
1040
  }
909
1041
  async function leafCandidates(run, words) {
910
1042
  const completing = await completingOf(run);
@@ -912,12 +1044,12 @@ async function leafCandidates(run, words) {
912
1044
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
913
1045
  const flag = words.at(-2);
914
1046
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1047
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
915
1048
  if (option?.type === "string") {
916
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1049
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
917
1050
  return values === undefined ? [FILES] : values.map(candidateLine);
918
1051
  }
919
- const name = positionalBeingTyped(words.slice(0, -1), completing);
920
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1052
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
921
1053
  return values === undefined ? [FILES] : values.map(candidateLine);
922
1054
  }
923
1055
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -942,15 +1074,32 @@ async function candidates(scope, defaultCommand, words, before = []) {
942
1074
  }
943
1075
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
944
1076
  }
1077
+ var COMPLETIONS = "--completions";
1078
+ function flagValue([flag = "", ...rest]) {
1079
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1080
+ }
1081
+ function printCompletionScript(name, args) {
1082
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1083
+ if (shell === undefined || args.length !== 1) {
1084
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1085
+ return 2;
1086
+ }
1087
+ console.log(completionScript(shell, [name]).trimEnd());
1088
+ return 0;
1089
+ }
945
1090
  async function printCandidates(found) {
946
1091
  for (const line of await found)
947
1092
  console.log(line);
948
1093
  return 0;
949
1094
  }
950
1095
  function packageVersion(entry = Bun.main) {
951
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1096
+ let resolved = entry;
1097
+ try {
1098
+ resolved = realpathSync2(entry);
1099
+ } catch {}
1100
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
952
1101
  try {
953
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
1102
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
954
1103
  if (typeof version === "string")
955
1104
  return version;
956
1105
  } catch {}
@@ -958,14 +1107,19 @@ function packageVersion(entry = Bun.main) {
958
1107
  return "0.0.0";
959
1108
  }
960
1109
  }
961
- async function runCli(cli, argv = process11.argv.slice(2)) {
1110
+ async function runCli(cli, argv = scriptArgs()) {
962
1111
  const version = cli.version ?? packageVersion();
963
1112
  if (argv[0] === COMPLETE)
964
1113
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1114
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1115
+ return printCompletionScript(cli.name, flagValue(argv));
1116
+ const started = performance.now();
965
1117
  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 });
1118
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1119
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
966
1120
  if (cli.usage !== false) {
967
1121
  try {
968
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1122
+ recordUsage(usageEntry(cli.name, command, argv, code));
969
1123
  } catch {}
970
1124
  }
971
1125
  return code;
@@ -988,7 +1142,7 @@ function commandPath(scope, argv) {
988
1142
  // ../kit/src/compose.ts
989
1143
  async function captureOutput(argv, { cwd, env } = {}) {
990
1144
  const run = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, env: { ...process.env, ...env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
991
- const [stdout, stderr, code] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]);
1145
+ const [stdout, stderr, code] = await Promise.all([new Response(run.stdout).text(), new Response(run.stderr).text(), run.exited]);
992
1146
  return { code, stdout, stderr };
993
1147
  }
994
1148
  async function compose(args, { flags = [], ...options } = {}) {
@@ -1030,8 +1184,8 @@ var SESSION_FILES = new Glob("*.json");
1030
1184
  var ACCOUNT_DIRS = new Glob("*/sessions");
1031
1185
  // src/commands/audit.ts
1032
1186
  import { homedir as homedir4 } from "os";
1033
- import { resolve as resolve4 } from "path";
1034
- import process14 from "process";
1187
+ import { resolve as resolve5 } from "path";
1188
+ import process16 from "process";
1035
1189
 
1036
1190
  // src/audit/compose.ts
1037
1191
  import { join as join6 } from "path";
@@ -1044,8 +1198,8 @@ var dockerCompose = async (root, files) => {
1044
1198
 
1045
1199
  // src/audit/render.ts
1046
1200
  import { basename } from "path";
1047
- import process13 from "process";
1048
- var line = (finding) => ` ${marked(finding.level === "error" ? "problem" : "warn", `[${finding.check}] ${finding.message}`, process13.stdout)}`;
1201
+ import process15 from "process";
1202
+ var line = (finding) => ` ${marked(finding.level === "error" ? "problem" : "warn", `[${finding.check}] ${finding.message}`, process15.stdout)}`;
1049
1203
  function errorsOf(result) {
1050
1204
  return result.findings.filter((finding) => finding.level === "error");
1051
1205
  }
@@ -1057,7 +1211,7 @@ function render(result, limit = Number.POSITIVE_INFINITY) {
1057
1211
  const errors = errorsOf(result);
1058
1212
  const warnings = result.findings.filter((finding) => finding.level === "warn");
1059
1213
  if (result.findings.length === 0)
1060
- return marked("ok", `${basename(result.root)}: compose ${result.composeFiles.join(", ")} and release.config.ts agree.`, process13.stdout);
1214
+ return marked("ok", `${basename(result.root)}: compose ${result.composeFiles.join(", ")} and release.config.ts agree.`, process15.stdout);
1061
1215
  return [
1062
1216
  ...section2("Errors", errors, limit),
1063
1217
  ...section2("Warnings", warnings, limit),
@@ -1071,8 +1225,8 @@ import { existsSync as existsSync5 } from "fs";
1071
1225
  import { join as join9 } from "path";
1072
1226
 
1073
1227
  // src/audit/checks.ts
1074
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
1075
- import { isAbsolute as isAbsolute2, join as join7, relative, resolve as resolve3 } from "path";
1228
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
1229
+ import { isAbsolute as isAbsolute2, join as join7, relative, resolve as resolve4 } from "path";
1076
1230
  var ENV_REF = /(?<!\$)\$(?:\{([A-Z_]\w*)(\s*:?[-?+][^}]*)?\}|([A-Z_]\w*))/gi;
1077
1231
  var REQUIRED_OPERATOR = /^\s*:?\?/;
1078
1232
  var COMMENT_START = /(?:^|\s)#.*$/;
@@ -1108,7 +1262,7 @@ function buildFindings(root, releases, env, home) {
1108
1262
  missing(release, "dockerfile");
1109
1263
  for (const secret of release.buildSecrets ?? []) {
1110
1264
  if (secret.src !== undefined && secret.src !== "") {
1111
- const path = secret.src.startsWith("~") ? join7(home, secret.src.slice(1)) : resolve3(root, secret.src);
1265
+ const path = secret.src.startsWith("~") ? join7(home, secret.src.slice(1)) : resolve4(root, secret.src);
1112
1266
  if (!existsSync3(path))
1113
1267
  findings.push({ level: "error", check: "build", message: `${release.slug}: buildSecret "${secret.id}" src does not exist: ${secret.src}` });
1114
1268
  }
@@ -1126,7 +1280,7 @@ function withoutComment(line) {
1126
1280
  }
1127
1281
  function envRefs(root, composeFiles) {
1128
1282
  return composeFiles.flatMap((file) => {
1129
- const text = readFileSync3(join7(root, file), "utf8").split(`
1283
+ const text = readFileSync4(join7(root, file), "utf8").split(`
1130
1284
  `).map(withoutComment).join(`
1131
1285
  `);
1132
1286
  return [...text.matchAll(ENV_REF)].map((match) => ({ name: match[1] ?? match[3], defaulted: match[2] !== undefined && !REQUIRED_OPERATOR.test(match[2]), file }));
@@ -1244,13 +1398,13 @@ function relativeSource(root, written) {
1244
1398
  return;
1245
1399
  if (source.startsWith("."))
1246
1400
  return source;
1247
- const inRoot = relative(resolve3(root), source);
1401
+ const inRoot = relative(resolve4(root), source);
1248
1402
  return isAbsolute2(source) && inRoot !== "" && !inRoot.startsWith("..") ? `./${inRoot}` : undefined;
1249
1403
  }
1250
1404
  function layoutFindings(root, base, model) {
1251
1405
  if (base === undefined)
1252
1406
  return [];
1253
- const header = readFileSync3(join7(root, base), "utf8").split(SERVICES_KEY)[0] ?? "";
1407
+ const header = readFileSync4(join7(root, base), "utf8").split(SERVICES_KEY)[0] ?? "";
1254
1408
  const findings = [];
1255
1409
  for (const [name, service] of services(model)) {
1256
1410
  for (const volume of service.volumes ?? []) {
@@ -1263,12 +1417,12 @@ function layoutFindings(root, base, model) {
1263
1417
  }
1264
1418
  function gitignoreFindings(root) {
1265
1419
  const path = join7(root, ".gitignore");
1266
- const text = existsSync3(path) ? readFileSync3(path, "utf8") : "";
1420
+ const text = existsSync3(path) ? readFileSync4(path, "utf8") : "";
1267
1421
  return [".release-logs", ".release-worktrees"].filter((entry) => !text.includes(entry)).map((entry) => ({ level: "warn", check: "gitignore", message: `${entry}/ is not in .gitignore` }));
1268
1422
  }
1269
1423
 
1270
1424
  // src/audit/nuxt.ts
1271
- import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
1425
+ import { existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
1272
1426
  import { basename as basename2, join as join8 } from "path";
1273
1427
  var CAMEL_BOUNDARY = /([a-z0-9])([A-Z])/g;
1274
1428
  var KEY = /([A-Z_]\w*)\s*(?:\?\s*)?:/gi;
@@ -1319,14 +1473,14 @@ function nuxtFindings(root, releases, model) {
1319
1473
  let level = "error";
1320
1474
  let source;
1321
1475
  if (schemaPath !== undefined) {
1322
- const schema = readFileSync4(schemaPath, "utf8");
1476
+ const schema = readFileSync5(schemaPath, "utf8");
1323
1477
  allowed = new Set([
1324
1478
  ...schemaEnvNames(schema, "SharedRuntimeConfig", "NUXT_"),
1325
1479
  ...schemaEnvNames(schema, "SharedPublicRuntimeConfig", "NUXT_PUBLIC_")
1326
1480
  ]);
1327
1481
  source = `${basename2(dir)}/${schemaPath.slice(dir.length + 1)}`;
1328
1482
  } else {
1329
- const config = readFileSync4(join8(dir, "nuxt.config.ts"), "utf8");
1483
+ const config = readFileSync5(join8(dir, "nuxt.config.ts"), "utf8");
1330
1484
  const at = config.indexOf("runtimeConfig:");
1331
1485
  const block = at < 0 ? undefined : braceBody(config, at);
1332
1486
  if (block === undefined)
@@ -1432,11 +1586,11 @@ var options = {
1432
1586
  };
1433
1587
  async function audit2(args, overrides = {}) {
1434
1588
  const parsed = parse(args, usage2, options);
1435
- const root = resolve4(parsed.positionals[0] ?? ".");
1589
+ const root = resolve5(parsed.positionals[0] ?? ".");
1436
1590
  if (!hasConfig(root)) {
1437
1591
  fail(`no ${CONFIG_FILE} in ${root}`);
1438
1592
  }
1439
- const result = await audit(await loadConfig(root), { root, loadCompose: dockerCompose, env: process14.env, home: homedir4(), ...overrides });
1593
+ const result = await audit(await loadConfig(root), { root, loadCompose: dockerCompose, env: process16.env, home: homedir4(), ...overrides });
1440
1594
  if (parsed.values.json === true)
1441
1595
  printJson(result);
1442
1596
  else
@@ -1495,12 +1649,12 @@ async function port(args) {
1495
1649
  }
1496
1650
  console.log(number);
1497
1651
  if (isListening(number))
1498
- console.error(`port ${number} is already in use on this machine`);
1652
+ warn(`port ${number} is already in use on this machine`);
1499
1653
  return 0;
1500
1654
  }
1501
1655
 
1502
1656
  // src/cli.ts
1503
- process15.exitCode = await runCli({
1657
+ process17.exitCode = await runCli({
1504
1658
  name: "stack",
1505
1659
  about: "a stable port per service name, and a compose release audit",
1506
1660
  replaces: "picking a free host port by hand, and reading compose files against release.config.ts",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-stack",
3
3
  "type": "module",
4
- "version": "0.7.0",
4
+ "version": "0.7.2",
5
5
  "description": "stack: a stable port per service name, and an audit of a compose release setup against its release.config.ts.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -28,6 +28,6 @@
28
28
  "stack": "$npm_execpath src/cli.ts"
29
29
  },
30
30
  "devDependencies": {
31
- "@kaynooo/cli-kit": "0.36.0"
31
+ "@kaynooo/cli-kit": "0.41.0"
32
32
  }
33
33
  }