@kaynooo/cli-wait 0.5.1 → 0.6.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/slot-cli.js CHANGED
@@ -1,18 +1,17 @@
1
- #!/usr/bin/env bun
1
+ #!/usr/bin/env -S bun --no-env-file
2
2
  // @bun
3
3
 
4
4
  // src/slot-cli.ts
5
- import process14 from "process";
6
-
5
+ import process15 from "process";
7
6
  // ../kit/src/args.ts
8
- import process4 from "process";
7
+ import process5 from "process";
9
8
  import { parseArgs } from "util";
10
9
 
11
10
  // ../kit/src/format.ts
12
- import process2 from "process";
11
+ import process3 from "process";
13
12
 
14
13
  // ../kit/src/style.ts
15
- import process from "process";
14
+ import process2 from "process";
16
15
 
17
16
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
17
  function x(s) {
@@ -276,10 +275,10 @@ function le(i = {}) {
276
275
  var t = le();
277
276
 
278
277
  // ../kit/src/style.ts
279
- function takesControlCodes(stream, env = process.env) {
278
+ function takesControlCodes(stream, env = process2.env) {
280
279
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
281
280
  }
282
- function paint(stream, env = process.env) {
281
+ function paint(stream, env = process2.env) {
283
282
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
284
283
  }
285
284
  var STATUSES = {
@@ -339,7 +338,7 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
339
338
  widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
340
339
  }
341
340
  const shown = fit === undefined ? cells : narrow(cells, widths, fit);
342
- const colors = paint(process2.stdout);
341
+ const colors = paint(process3.stdout);
343
342
  const lines = shown.map((row) => row.map((cell, index) => {
344
343
  const width = widths[index] ?? 0;
345
344
  const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
@@ -371,24 +370,30 @@ function printJson(value) {
371
370
  }
372
371
 
373
372
  // ../kit/src/help.ts
374
- import process3 from "process";
373
+ import process4 from "process";
375
374
  var OPTIONAL = /\[[^\]]+\]/g;
376
375
  var USAGE_PREFIX = /^usage:\s*/i;
377
376
  var FULL_STOP = /\.$/;
378
- function usageLine(usage, colors = paint(process3.stdout)) {
377
+ function usageLine(usage, colors = paint(process4.stdout)) {
379
378
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
380
379
  }
381
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
382
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
380
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
381
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
383
382
  `);
384
383
  }
385
- function replacesRows(replaces, colors = paint(process3.stdout)) {
384
+ function exitRows(exits, colors = paint(process4.stdout)) {
385
+ if (exits.length === 0)
386
+ return [];
387
+ const width = Math.max(...exits.map(([code]) => String(code).length));
388
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
389
+ }
390
+ function replacesRows(replaces, colors = paint(process4.stdout)) {
386
391
  return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
387
392
  }
388
- function wantsHelpJson(env = process3.env) {
393
+ function wantsHelpJson(env = process4.env) {
389
394
  return env.KIT_HELP === "json";
390
395
  }
391
- function description(usage, { examples = [], replaces } = {}) {
396
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
392
397
  const lines = usage.replace(USAGE_PREFIX, "").split(`
393
398
  `);
394
399
  const first = lines[0];
@@ -399,15 +404,17 @@ function description(usage, { examples = [], replaces } = {}) {
399
404
  synopsis: colon === -1 ? first : first.slice(0, colon),
400
405
  summary: colon === -1 ? fallback : first.slice(colon + 2),
401
406
  ...replaces === undefined ? {} : { replaces },
402
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
407
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
408
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
409
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
403
410
  };
404
411
  }
405
- function exampleRows(examples, colors = paint(process3.stdout)) {
412
+ function exampleRows(examples, colors = paint(process4.stdout)) {
406
413
  if (examples.length === 0)
407
414
  return [];
408
415
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
409
416
  }
410
- function optionRows(options, colors = paint(process3.stdout)) {
417
+ function optionRows(options, colors = paint(process4.stdout)) {
411
418
  const rows = Object.entries(options).map(([name, option]) => {
412
419
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
413
420
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -509,7 +516,7 @@ var OUTPUT_OPTIONS = {
509
516
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
510
517
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
511
518
  };
512
- function applyOutput(color, plain, env = process4.env) {
519
+ function applyOutput(color, plain, env = process5.env) {
513
520
  const when = plain === true ? "never" : color ?? "auto";
514
521
  if (when === "auto")
515
522
  return;
@@ -532,7 +539,7 @@ function parse(args, usage, options, settings = {}) {
532
539
  const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
533
540
  let parsed;
534
541
  try {
535
- parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
542
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
536
543
  } catch (error) {
537
544
  const message = parseError(error);
538
545
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -540,7 +547,7 @@ function parse(args, usage, options, settings = {}) {
540
547
  const values = parsed.values;
541
548
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
542
549
  if (values.help === true) {
543
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
550
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
544
551
  throw new HelpShown;
545
552
  }
546
553
  checkChoices(parsed.values, all);
@@ -582,6 +589,18 @@ function listed(options, allowNegative) {
582
589
  return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
583
590
  }));
584
591
  }
592
+ function withAliases(args, options) {
593
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
594
+ if (named.size === 0)
595
+ return args;
596
+ const separator = args.indexOf("--");
597
+ const own = separator === -1 ? args : args.slice(0, separator);
598
+ return [...own.map((arg) => {
599
+ const at = arg.indexOf("=");
600
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
601
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
602
+ }), ...separator === -1 ? [] : args.slice(separator)];
603
+ }
585
604
  function withBare(args, options) {
586
605
  const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
587
606
  if (bare.size === 0)
@@ -667,11 +686,12 @@ function nearestOption(message, options, allowNegative) {
667
686
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
668
687
  }
669
688
  // ../kit/src/progress.ts
670
- import process6 from "process";
689
+ import process7 from "process";
671
690
 
672
691
  // ../kit/src/process.ts
673
692
  import { constants } from "os";
674
- import process5 from "process";
693
+ import process6 from "process";
694
+ var KILL_GRACE_MS = 2000;
675
695
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
676
696
  function exitCodeOf(code, signal) {
677
697
  if (code !== null)
@@ -692,7 +712,7 @@ function holdSignals(cleanup) {
692
712
  },
693
713
  release: () => {
694
714
  for (const signal of SIGNALS)
695
- process5.off(signal, onSignal);
715
+ process6.off(signal, onSignal);
696
716
  }
697
717
  };
698
718
  function onSignal(signal) {
@@ -705,12 +725,90 @@ function holdSignals(cleanup) {
705
725
  return;
706
726
  held.release();
707
727
  cleanup(signal);
708
- process5.kill(process5.pid, signal);
728
+ process6.kill(process6.pid, signal);
709
729
  }
710
730
  for (const signal of SIGNALS)
711
- process5.on(signal, onSignal);
731
+ process6.on(signal, onSignal);
712
732
  return held;
713
733
  }
734
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
735
+ const chunks = [];
736
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
737
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
738
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
739
+ const timers = [];
740
+ const killGroup = (killing) => {
741
+ if (state.done)
742
+ return;
743
+ try {
744
+ if (grouped)
745
+ process6.kill(-proc.pid, killing);
746
+ else
747
+ proc.kill(killing);
748
+ } catch {}
749
+ };
750
+ const stop = () => {
751
+ killGroup("SIGTERM");
752
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
753
+ };
754
+ const onAbort = () => stop();
755
+ if (timeoutMs !== undefined) {
756
+ timers.push(setTimeout(() => {
757
+ state.timedOut = true;
758
+ stop();
759
+ }, timeoutMs));
760
+ }
761
+ if (signal?.aborted === true)
762
+ onAbort();
763
+ else
764
+ signal?.addEventListener("abort", onAbort, { once: true });
765
+ onStart?.({ kill: (killing) => killGroup(killing) });
766
+ const drain = async (stream, name) => {
767
+ for await (const data of stream) {
768
+ if (state.failure !== undefined)
769
+ continue;
770
+ try {
771
+ onChunk?.({ stream: name, data });
772
+ } catch (error) {
773
+ state.failure = error;
774
+ stop();
775
+ continue;
776
+ }
777
+ if (state.kept + data.length > maxBytes) {
778
+ state.truncated = true;
779
+ continue;
780
+ }
781
+ state.kept += data.length;
782
+ chunks.push({ stream: name, data });
783
+ }
784
+ };
785
+ try {
786
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
787
+ await proc.exited;
788
+ } finally {
789
+ state.done = true;
790
+ for (const timer of timers)
791
+ clearTimeout(timer);
792
+ signal?.removeEventListener("abort", onAbort);
793
+ }
794
+ if (state.failure !== undefined)
795
+ throw state.failure;
796
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
797
+ let output;
798
+ let text;
799
+ return {
800
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
801
+ chunks,
802
+ timedOut: state.timedOut,
803
+ truncated: state.truncated,
804
+ get output() {
805
+ return output ??= joined();
806
+ },
807
+ get text() {
808
+ return text ??= (output ??= joined()).toString();
809
+ }
810
+ };
811
+ }
714
812
 
715
813
  // ../kit/src/progress.ts
716
814
  var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
@@ -723,7 +821,7 @@ var RESET_STYLE = `${ESC}[0m`;
723
821
  var CTRL_C = 3;
724
822
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
725
823
  var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
726
- function liveRegion(render, stream = process6.stderr, env = process6.env) {
824
+ function liveRegion(render, stream = process7.stderr, env = process7.env) {
727
825
  if (!takesControlCodes(stream, env))
728
826
  return { redraw: () => {
729
827
  return;
@@ -764,11 +862,11 @@ function liveRegion(render, stream = process6.stderr, env = process6.env) {
764
862
  clear();
765
863
  restore();
766
864
  release();
767
- process6.off("exit", onExit);
865
+ process7.off("exit", onExit);
768
866
  signals.release();
769
867
  }
770
868
  timer.unref();
771
- process6.on("exit", onExit);
869
+ process7.on("exit", onExit);
772
870
  return {
773
871
  redraw: draw,
774
872
  print: (text) => {
@@ -807,14 +905,14 @@ function cutToWidth(line, width) {
807
905
  return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
808
906
  }
809
907
  function swallowInput() {
810
- const input = process6.stdin;
908
+ const input = process7.stdin;
811
909
  if (!input.isTTY)
812
910
  return () => {
813
911
  return;
814
912
  };
815
913
  const onData = (data) => {
816
914
  if (data.includes(CTRL_C))
817
- process6.kill(process6.pid, "SIGINT");
915
+ process7.kill(process7.pid, "SIGINT");
818
916
  };
819
917
  input.setRawMode(true);
820
918
  input.on("data", onData);
@@ -830,7 +928,7 @@ function swallowInput() {
830
928
  };
831
929
  }
832
930
  function interceptOutput(clear) {
833
- const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process6.stdout, "write"], [process6.stderr, "write"]];
931
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process7.stdout, "write"], [process7.stderr, "write"]];
834
932
  const wrapped = targets.map(([target, name]) => {
835
933
  const original = Reflect.get(target, name);
836
934
  const wrapper = (...args) => {
@@ -848,31 +946,33 @@ function interceptOutput(clear) {
848
946
  };
849
947
  }
850
948
  // ../kit/src/cli.ts
851
- import process9 from "process";
949
+ import { readFileSync, realpathSync } from "fs";
950
+ import { dirname as dirname2, join as join3 } from "path";
951
+ import process10 from "process";
852
952
 
853
953
  // ../kit/src/usage.ts
854
954
  import { appendFileSync, mkdirSync } from "fs";
855
955
  import { homedir as homedir2 } from "os";
856
956
  import { dirname, isAbsolute, join as join2 } from "path";
857
- import process8 from "process";
957
+ import process9 from "process";
858
958
 
859
959
  // ../kit/src/logs.ts
860
960
  import { lstatSync, openSync } from "fs";
861
961
  import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
862
962
  import { homedir, tmpdir } from "os";
863
963
  import { join } from "path";
864
- import process7 from "process";
964
+ import process8 from "process";
865
965
  var DAY_MS = 24 * 60 * 60 * 1000;
866
966
  var CLI_FOLDER = "kaynooo-cli";
867
967
  function isPrivateDirectory(path) {
868
968
  try {
869
969
  const info = lstatSync(path, { throwIfNoEntry: false });
870
- return info !== undefined && info.isDirectory() && info.uid === (process7.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
970
+ return info !== undefined && info.isDirectory() && info.uid === (process8.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
871
971
  } catch {
872
972
  return false;
873
973
  }
874
974
  }
875
- async function privateLogDirectory(name, env = process7.env) {
975
+ async function privateLogDirectory(name, env = process8.env) {
876
976
  const runtime = env.XDG_RUNTIME_DIR;
877
977
  const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
878
978
  const path = join(base, name);
@@ -892,14 +992,14 @@ var usageError;
892
992
  function noteUsageError(message) {
893
993
  usageError = message;
894
994
  }
895
- function stateHome(env = process8.env) {
995
+ function stateHome(env = process9.env) {
896
996
  const dir = env.XDG_STATE_HOME;
897
997
  return dir !== undefined && isAbsolute(dir) ? dir : join2(homedir2(), ".local", "state");
898
998
  }
899
- function usagePath(env = process8.env) {
999
+ function usagePath(env = process9.env) {
900
1000
  return join2(stateHome(env), CLI_FOLDER, "usage.jsonl");
901
1001
  }
902
- function usageRecorded(env = process8.env) {
1002
+ function usageRecorded(env = process9.env) {
903
1003
  const off = env.KAYNOOO_CLI_NO_USAGE;
904
1004
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
905
1005
  }
@@ -913,7 +1013,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
913
1013
  usageError = undefined;
914
1014
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
915
1015
  }
916
- function recordUsage(entry, env = process8.env) {
1016
+ function recordUsage(entry, env = process9.env) {
917
1017
  if (!usageRecorded(env))
918
1018
  return;
919
1019
  try {
@@ -931,8 +1031,8 @@ var LEVEL_OPTIONS = {
931
1031
  };
932
1032
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
933
1033
  function printError(prefix, message, hint, cause) {
934
- const colors = paint(process9.stderr);
935
- const styled = takesControlCodes(process9.stderr);
1034
+ const colors = paint(process10.stderr);
1035
+ const styled = takesControlCodes(process10.stderr);
936
1036
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
937
1037
  const under = (label, text, tint) => text === undefined ? "" : `
938
1038
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1014,11 +1114,22 @@ async function printCandidates(found) {
1014
1114
  console.log(line);
1015
1115
  return 0;
1016
1116
  }
1017
- async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
1117
+ function packageVersion(entry = Bun.main) {
1118
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1119
+ try {
1120
+ const { version } = JSON.parse(readFileSync(join3(dir, "package.json"), "utf8"));
1121
+ if (typeof version === "string")
1122
+ return version;
1123
+ } catch {}
1124
+ if (dirname2(dir) === dir)
1125
+ return "0.0.0";
1126
+ }
1127
+ }
1128
+ async function runMain({ name, version, run, redact, usage }, argv = process10.argv.slice(2)) {
1018
1129
  if (argv[0] === COMPLETE)
1019
1130
  return printCandidates(leafCandidates(run, argv.slice(1)));
1020
1131
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1021
- console.log(version);
1132
+ console.log(version ?? packageVersion());
1022
1133
  return 0;
1023
1134
  }
1024
1135
  let code;
@@ -1027,26 +1138,29 @@ async function runMain({ name, version, run, redact, usage }, argv = process9.ar
1027
1138
  } catch (error) {
1028
1139
  code = reportThrown(name, error, redact, wantsJson(argv));
1029
1140
  }
1030
- if (usage !== false)
1031
- recordUsage(usageEntry(name, undefined, argv, code));
1141
+ if (usage !== false) {
1142
+ try {
1143
+ recordUsage(usageEntry(name, undefined, argv, code));
1144
+ } catch {}
1145
+ }
1032
1146
  return code;
1033
1147
  }
1034
1148
  // ../kit/src/secrets.ts
1035
1149
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1036
1150
  // ../kit/src/sessions.ts
1037
1151
  import { homedir as homedir3 } from "os";
1038
- import { join as join3 } from "path";
1039
- import process10 from "process";
1152
+ import { join as join4 } from "path";
1153
+ import process11 from "process";
1040
1154
  var {Glob } = globalThis.Bun;
1041
1155
  var SESSION_FILES = new Glob("*.json");
1042
1156
  var ACCOUNT_DIRS = new Glob("*/sessions");
1043
1157
  async function sessionDirs() {
1044
1158
  const home = homedir3();
1045
- const dirs = new Set([join3(home, ".claude", "sessions")]);
1046
- if (process10.env.CLAUDE_CONFIG_DIR !== undefined)
1047
- dirs.add(join3(process10.env.CLAUDE_CONFIG_DIR, "sessions"));
1159
+ const dirs = new Set([join4(home, ".claude", "sessions")]);
1160
+ if (process11.env.CLAUDE_CONFIG_DIR !== undefined)
1161
+ dirs.add(join4(process11.env.CLAUDE_CONFIG_DIR, "sessions"));
1048
1162
  try {
1049
- for await (const dir of ACCOUNT_DIRS.scan({ cwd: join3(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
1163
+ for await (const dir of ACCOUNT_DIRS.scan({ cwd: join4(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
1050
1164
  dirs.add(dir);
1051
1165
  } catch {}
1052
1166
  return [...dirs];
@@ -1090,7 +1204,7 @@ async function liveSessions() {
1090
1204
  }
1091
1205
  async function currentSession(sessions) {
1092
1206
  const byPid = new Map(sessions.map((session) => [session.pid, session]));
1093
- let pid = process10.ppid;
1207
+ let pid = process11.ppid;
1094
1208
  for (let depth = 0;depth < 32 && pid > 1; depth++) {
1095
1209
  const session = byPid.get(pid);
1096
1210
  if (session !== undefined)
@@ -1102,24 +1216,21 @@ async function currentSession(sessions) {
1102
1216
  }
1103
1217
  return;
1104
1218
  }
1105
- // package.json
1106
- var version = "0.5.1";
1107
-
1108
1219
  // src/slot.ts
1109
- import { existsSync, mkdirSync as mkdirSync2, readdirSync, readFileSync, unlinkSync } from "fs";
1220
+ import { existsSync, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmSync } from "fs";
1110
1221
  import { availableParallelism } from "os";
1111
- import { join as join4 } from "path";
1112
- import process13 from "process";
1222
+ import { join as join5 } from "path";
1223
+ import process14 from "process";
1113
1224
 
1114
1225
  // src/flock.ts
1115
1226
  import { closeSync, constants as constants2, ftruncateSync, openSync as openSync2, writeSync } from "fs";
1116
- import process12 from "process";
1227
+ import process13 from "process";
1117
1228
  import { dlopen, FFIType } from "bun:ffi";
1118
1229
  var LOCK_EX = 2;
1119
1230
  var LOCK_NB = 4;
1120
1231
  var flock;
1121
1232
  function native() {
1122
- flock ??= dlopen(process12.platform === "darwin" ? "libSystem.B.dylib" : "libc.so.6", { flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 } }).symbols.flock;
1233
+ flock ??= dlopen(process13.platform === "darwin" ? "libSystem.B.dylib" : "libc.so.6", { flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 } }).symbols.flock;
1123
1234
  return flock;
1124
1235
  }
1125
1236
  function tryLock(path) {
@@ -1142,8 +1253,8 @@ slot ls [--json]: lists who holds a slot or a lock and who waits for one (slot l
1142
1253
  The slots and locks are shared by every session, worktree and shell of this user, so heavy jobs (phpunit, playwright, vue-tsc, eslint) queue instead of overloading the machine.
1143
1254
  A slot or lock is freed the moment its holder ends, SIGKILL included, since the kernel drops it with the process.
1144
1255
  A slotted command that runs slot again does not wait for a second slot, so wrapping both a script and the commands inside it cannot deadlock.
1145
- A first word \`ls\` always means the listing, so run the ls command as \`slot -n 4 -- ls\` or by its path.
1146
- Exits with the command's code, 2 on a timeout or a usage error.`;
1256
+ A first word \`ls\` always means the listing, so run the ls command as \`slot -n 4 -- ls\` or by its path.`;
1257
+ var RUN_EXITS = [[0, "the command did"], ["its own", "the code of a command that failed"], [2, "it timed out waiting for the slot or a usage error"], [127, "the command cannot be started"]];
1147
1258
  var LS_USAGE = `slot ls [options]: lists the slots and locks held, with the session, the command and how long ago it started, then who waits for one
1148
1259
 
1149
1260
  --json prints {slots, busy, entries}, each entry as {state, resource, pid, session, command, cwd, since}.`;
@@ -1163,21 +1274,21 @@ function defaultSlots() {
1163
1274
  return Math.max(1, Math.floor(availableParallelism() / 2));
1164
1275
  }
1165
1276
  async function stateDir() {
1166
- const dir = process13.env.SLOT_DIR ?? await privateLogDirectory("slot");
1277
+ const dir = process14.env.SLOT_DIR ?? await privateLogDirectory("slot");
1167
1278
  for (const sub of ["slots", "locks", "waiters"])
1168
- mkdirSync2(join4(dir, sub), { recursive: true, mode: 448 });
1279
+ mkdirSync2(join5(dir, sub), { recursive: true, mode: 448 });
1169
1280
  return dir;
1170
1281
  }
1171
1282
  function readHolder(path) {
1172
1283
  try {
1173
- const holder = JSON.parse(readFileSync(path, "utf8"));
1284
+ const holder = JSON.parse(readFileSync2(path, "utf8"));
1174
1285
  return typeof holder.pid === "number" && typeof holder.command === "string" ? { pid: holder.pid, command: holder.command, cwd: holder.cwd ?? "", since: holder.since ?? 0, ...holder.session === undefined ? {} : { session: holder.session }, ...holder.resource === undefined ? {} : { resource: holder.resource } } : undefined;
1175
1286
  } catch {
1176
1287
  return;
1177
1288
  }
1178
1289
  }
1179
1290
  function pathOf(dir, kind, name) {
1180
- return join4(dir, kind === "slot" ? "slots" : "locks", name);
1291
+ return join5(dir, kind === "slot" ? "slots" : "locks", name);
1181
1292
  }
1182
1293
  function candidates(dir, { kind, name, count }) {
1183
1294
  if (kind === "lock")
@@ -1205,7 +1316,7 @@ function waitingLine(dir, wanted) {
1205
1316
  }
1206
1317
  async function holderOf(command) {
1207
1318
  const session = await currentSession(await liveSessions());
1208
- return { pid: process13.pid, command: command.join(" "), cwd: process13.cwd(), since: Date.now(), ...session === undefined ? {} : { session: session.name } };
1319
+ return { pid: process14.pid, command: command.join(" "), cwd: process14.cwd(), since: Date.now(), ...session === undefined ? {} : { session: session.name } };
1209
1320
  }
1210
1321
  var waiterCount = 0;
1211
1322
  async function acquire(dir, resources, holder, deadline, timeoutMs) {
@@ -1231,7 +1342,7 @@ async function acquire(dir, resources, holder, deadline, timeoutMs) {
1231
1342
  held.release();
1232
1343
  const resource = busy.kind === "lock" ? `lock ${busy.name}` : "slot";
1233
1344
  if (waiter === undefined) {
1234
- const path = join4(dir, "waiters", `${process13.pid}-${waiterCount++}`);
1345
+ const path = join5(dir, "waiters", `${process14.pid}-${waiterCount++}`);
1235
1346
  const held = tryLock(path);
1236
1347
  if (held !== undefined) {
1237
1348
  writeHeld(held, JSON.stringify({ ...holder, resource }));
@@ -1248,14 +1359,14 @@ async function acquire(dir, resources, holder, deadline, timeoutMs) {
1248
1359
  }
1249
1360
  } finally {
1250
1361
  if (waiter !== undefined) {
1251
- unlinkSync(waiter.path);
1362
+ rmSync(waiter.path, { force: true });
1252
1363
  waiter.held.release();
1253
1364
  }
1254
1365
  }
1255
1366
  }
1256
1367
  async function runSlotted(args) {
1257
1368
  const bare = args[0] !== undefined && !args[0].startsWith("-");
1258
- const parsed = parse(bare ? [] : args, RUN_USAGE, RUN_OPTIONS, { rest: true, replaces: "flock wrappers, hand-written heavy.sh queues and parallel runs fighting over one test database", examples: [["slot -- bunx vue-tsc", "wait for a free slot, then type-check"], ["slot --lock booki-test-db -- vendor/bin/phpunit", "one phpunit at a time on the shared test database"], "slot ls"] });
1369
+ const parsed = parse(bare ? [] : args, RUN_USAGE, RUN_OPTIONS, { rest: true, exits: RUN_EXITS, replaces: "flock wrappers, hand-written heavy.sh queues and parallel runs fighting over one test database", examples: [["slot -- bunx vue-tsc", "wait for a free slot, then type-check"], ["slot --lock booki-test-db -- vendor/bin/phpunit", "one phpunit at a time on the shared test database"], "slot ls"] });
1259
1370
  const { values } = parsed;
1260
1371
  const rest = bare ? args : parsed.rest;
1261
1372
  if (rest === undefined || rest.length === 0)
@@ -1272,7 +1383,7 @@ ${RUN_USAGE}`);
1272
1383
  const count = wholeNumber(values.slots, "slots", defaultSlots());
1273
1384
  const timeoutMs = duration(values.timeout, "timeout", Number.POSITIVE_INFINITY);
1274
1385
  const deadline = Date.now() + timeoutMs;
1275
- const holding = new Set((process13.env[HOLDING] ?? "").split(",").filter((token) => token !== ""));
1386
+ const holding = new Set((process14.env[HOLDING] ?? "").split(",").filter((token) => token !== ""));
1276
1387
  const wanted = [...locks.filter((name) => !holding.has(`lock:${name}`)).map((name) => ({ kind: "lock", name, count })), ...values["no-slot"] === true || holding.has("slot") ? [] : [{ kind: "slot", name: "", count }]];
1277
1388
  const signals = holdSignals(() => {
1278
1389
  return;
@@ -1287,7 +1398,7 @@ ${RUN_USAGE}`);
1287
1398
  const tokens = new Set([...holding, ...locks.map((name) => `lock:${name}`), ...wanted.some((resource) => resource.kind === "slot") ? ["slot"] : []]);
1288
1399
  let child;
1289
1400
  try {
1290
- child = Bun.spawn(rest, { stdio: ["inherit", "inherit", "inherit"], env: { ...process13.env, [HOLDING]: [...tokens].join(",") } });
1401
+ child = Bun.spawn(rest, { stdio: ["inherit", "inherit", "inherit"], env: { ...process14.env, [HOLDING]: [...tokens].join(",") } });
1291
1402
  } catch (error) {
1292
1403
  fail(`cannot run ${rest[0]}: ${error instanceof Error ? error.message : String(error)}`, 127);
1293
1404
  }
@@ -1301,14 +1412,14 @@ ${RUN_USAGE}`);
1301
1412
  }
1302
1413
  }
1303
1414
  function scan(dir, state, kind) {
1304
- const folder = join4(dir, kind);
1415
+ const folder = join5(dir, kind);
1305
1416
  const entries = [];
1306
1417
  for (const name of existsSync(folder) ? readdirSync(folder) : []) {
1307
- const path = join4(folder, name);
1418
+ const path = join5(folder, name);
1308
1419
  const probe = tryLock(path);
1309
1420
  if (probe !== undefined) {
1310
1421
  if (kind === "waiters")
1311
- unlinkSync(path);
1422
+ rmSync(path, { force: true });
1312
1423
  probe.release();
1313
1424
  continue;
1314
1425
  }
@@ -1319,7 +1430,7 @@ function scan(dir, state, kind) {
1319
1430
  return entries;
1320
1431
  }
1321
1432
  async function listSlots(args) {
1322
- const { values } = parse(args, LS_USAGE, LS_OPTIONS, { examples: ["slot ls", "slot ls --json"] });
1433
+ const { values } = parse(args, LS_USAGE, LS_OPTIONS, { exits: [[0, "it listed them"], [2, "a usage error"]], examples: ["slot ls", "slot ls --json"] });
1323
1434
  const count = wholeNumber(values.slots, "slots", defaultSlots());
1324
1435
  const dir = await stateDir();
1325
1436
  const holding = [...scan(dir, "holding", "slots"), ...scan(dir, "holding", "locks")].sort((a, b) => a.since - b.since);
@@ -1337,4 +1448,4 @@ async function listSlots(args) {
1337
1448
  }
1338
1449
 
1339
1450
  // src/slot-cli.ts
1340
- process14.exitCode = await runMain({ name: "slot", version, run: async (args) => args[0] === "ls" ? listSlots(args.slice(1)) : runSlotted(args) });
1451
+ process15.exitCode = await runMain({ name: "slot", run: async (args) => args[0] === "ls" ? listSlots(args.slice(1)) : runSlotted(args) });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-wait",
3
3
  "type": "module",
4
- "version": "0.5.1",
4
+ "version": "0.6.1",
5
5
  "description": "waitfor and slot: waits for a log line, a listening port or a URL answering, and queues heavy commands behind machine-wide slots and named locks, for Claude Code, instead of sleep and polling loops.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -37,6 +37,6 @@
37
37
  "waitfor": "$npm_execpath src/cli.ts"
38
38
  },
39
39
  "devDependencies": {
40
- "@kaynooo/cli-kit": "0.20.0"
40
+ "@kaynooo/cli-kit": "0.21.0"
41
41
  }
42
42
  }