@kaynooo/cli-wait 0.5.0 → 0.5.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.
Files changed (3) hide show
  1. package/dist/cli.js +316 -147
  2. package/dist/slot-cli.js +322 -153
  3. package/package.json +2 -2
package/dist/slot-cli.js CHANGED
@@ -2,10 +2,10 @@
2
2
  // @bun
3
3
 
4
4
  // src/slot-cli.ts
5
- import process12 from "process";
5
+ import process14 from "process";
6
6
 
7
7
  // ../kit/src/args.ts
8
- import process3 from "process";
8
+ import process4 from "process";
9
9
  import { parseArgs } from "util";
10
10
 
11
11
  // ../kit/src/format.ts
@@ -14,7 +14,7 @@ import process2 from "process";
14
14
  // ../kit/src/style.ts
15
15
  import process from "process";
16
16
 
17
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
17
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
18
  function x(s) {
19
19
  let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
20
20
  if (!/^[a-f0-9]+$/.test(r))
@@ -234,7 +234,7 @@ class e {
234
234
  }
235
235
  }
236
236
 
237
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
237
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
238
238
  var r = 39;
239
239
  var o = 49;
240
240
  var f2 = "\x1B[";
@@ -370,6 +370,55 @@ function printJson(value) {
370
370
  console.log(JSON.stringify(value, undefined, 2));
371
371
  }
372
372
 
373
+ // ../kit/src/help.ts
374
+ import process3 from "process";
375
+ var OPTIONAL = /\[[^\]]+\]/g;
376
+ var USAGE_PREFIX = /^usage:\s*/i;
377
+ var FULL_STOP = /\.$/;
378
+ function usageLine(usage, colors = paint(process3.stdout)) {
379
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
380
+ }
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(`
383
+ `);
384
+ }
385
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
386
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
387
+ }
388
+ function wantsHelpJson(env = process3.env) {
389
+ return env.KIT_HELP === "json";
390
+ }
391
+ function description(usage, { examples = [], replaces } = {}) {
392
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
393
+ `);
394
+ const first = lines[0];
395
+ const colon = first.indexOf(": ");
396
+ const prose = lines[lines.indexOf("") + 1] ?? "";
397
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
398
+ return {
399
+ synopsis: colon === -1 ? first : first.slice(0, colon),
400
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
401
+ ...replaces === undefined ? {} : { replaces },
402
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
403
+ };
404
+ }
405
+ function exampleRows(examples, colors = paint(process3.stdout)) {
406
+ if (examples.length === 0)
407
+ return [];
408
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
409
+ }
410
+ function optionRows(options, colors = paint(process3.stdout)) {
411
+ const rows = Object.entries(options).map(([name, option]) => {
412
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
413
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
414
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
415
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
416
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
417
+ });
418
+ const width = Math.max(0, ...rows.map((row) => row.width));
419
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
420
+ }
421
+
373
422
  // ../kit/src/text.ts
374
423
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
375
424
  function distance(a, b) {
@@ -389,8 +438,30 @@ function closest(name, names) {
389
438
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
390
439
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
391
440
  }
441
+ // ../kit/src/input.ts
442
+ var WHOLE = /^\d+$/;
443
+ function wholeNumber(value, name, fallback, min = 1) {
444
+ if (value === undefined)
445
+ return fallback;
446
+ const number = Number(value);
447
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
448
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
449
+ return number;
450
+ }
451
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
452
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
453
+ function duration(value, name, fallback, unit = "s") {
454
+ if (value === undefined)
455
+ return fallback;
456
+ const match = DURATION.exec(value.trim());
457
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
458
+ if (ms < 1)
459
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
460
+ return ms;
461
+ }
392
462
 
393
463
  // ../kit/src/args.ts
464
+ var DASHES = /^-+/;
394
465
  function jsonOption(holds) {
395
466
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
396
467
  }
@@ -425,61 +496,20 @@ class HelpShown extends Exit {
425
496
 
426
497
  class Completing {
427
498
  options;
428
- constructor(options) {
499
+ positionals;
500
+ candidates;
501
+ constructor(options, positionals = [], candidates = {}) {
429
502
  this.options = options;
503
+ this.positionals = positionals;
504
+ this.candidates = candidates;
430
505
  }
431
506
  }
432
507
  var completion = { active: false };
433
- var OPTIONAL = /\[[^\]]+\]/g;
434
- var USAGE_PREFIX = /^usage:\s*/i;
435
- var FULL_STOP = /\.$/;
436
- var DASHES = /^-+/;
437
- function usageLine(usage, colors = paint(process3.stdout)) {
438
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
439
- }
440
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
441
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
442
- `);
443
- }
444
- function replacesRows(replaces, colors = paint(process3.stdout)) {
445
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
446
- }
447
- function wantsHelpJson(env = process3.env) {
448
- return env.KIT_HELP === "json";
449
- }
450
- function description(usage, { examples = [], replaces } = {}) {
451
- const lines = usage.replace(USAGE_PREFIX, "").split(`
452
- `);
453
- const first = lines[0];
454
- const colon = first.indexOf(": ");
455
- const prose = lines[lines.indexOf("") + 1] ?? "";
456
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
457
- return {
458
- synopsis: colon === -1 ? first : first.slice(0, colon),
459
- summary: colon === -1 ? fallback : first.slice(colon + 2),
460
- ...replaces === undefined ? {} : { replaces },
461
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
462
- };
463
- }
464
- function exampleRows(examples, colors = paint(process3.stdout)) {
465
- if (examples.length === 0)
466
- return [];
467
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
468
- }
469
- function optionRows(options, colors = paint(process3.stdout)) {
470
- const rows = Object.entries(options).map(([name, option]) => {
471
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
472
- const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
473
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
474
- });
475
- const width = Math.max(0, ...rows.map((row) => row.width));
476
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
477
- }
478
508
  var OUTPUT_OPTIONS = {
479
509
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
480
510
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
481
511
  };
482
- function applyOutput(color, plain, env = process3.env) {
512
+ function applyOutput(color, plain, env = process4.env) {
483
513
  const when = plain === true ? "never" : color ?? "auto";
484
514
  if (when === "auto")
485
515
  return;
@@ -496,14 +526,13 @@ function applyOutput(color, plain, env = process3.env) {
496
526
  function parse(args, usage, options, settings = {}) {
497
527
  const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
498
528
  const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
529
+ const listing = listed(all, settings.allowNegative === true);
499
530
  if (completion.active)
500
- throw new Completing(all);
501
- const separator = settings.rest === true ? args.indexOf("--") : -1;
502
- const own = separator === -1 ? args : args.slice(0, separator);
503
- const rest = separator === -1 ? undefined : args.slice(separator + 1);
531
+ throw new Completing(listing, settings.positionals, settings.candidates);
532
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
504
533
  let parsed;
505
534
  try {
506
- parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
535
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
507
536
  } catch (error) {
508
537
  const message = parseError(error);
509
538
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -511,12 +540,84 @@ function parse(args, usage, options, settings = {}) {
511
540
  const values = parsed.values;
512
541
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
513
542
  if (values.help === true) {
514
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
543
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
515
544
  throw new HelpShown;
516
545
  }
546
+ checkChoices(parsed.values, all);
547
+ checkConflicts(parsed.values, all);
517
548
  if (settings.positionals !== undefined)
518
549
  checkPositionals(parsed.positionals, settings.positionals);
519
- return { ...parsed, positionals: parsed.positionals, rest };
550
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
551
+ }
552
+ function splitRest(args, passes) {
553
+ const separator = passes ? args.indexOf("--") : -1;
554
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
555
+ }
556
+ function splitTrailing(args, options, count) {
557
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
558
+ let seen = 0;
559
+ if (count === 0)
560
+ return { own: args, rest: undefined };
561
+ for (let at = 0;at < args.length; at++) {
562
+ const word = args[at];
563
+ if (word === "--")
564
+ break;
565
+ if (word.startsWith("-")) {
566
+ if (takesValue(word))
567
+ at++;
568
+ continue;
569
+ }
570
+ seen++;
571
+ if (seen === count)
572
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
573
+ }
574
+ return { own: args, rest: undefined };
575
+ }
576
+ function listed(options, allowNegative) {
577
+ if (!allowNegative)
578
+ return options;
579
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
580
+ if (option.type !== "boolean" || option.negative === undefined)
581
+ return [[name, option]];
582
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
583
+ }));
584
+ }
585
+ function withBare(args, options) {
586
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
587
+ if (bare.size === 0)
588
+ return args;
589
+ const separator = args.indexOf("--");
590
+ const own = separator === -1 ? args : args.slice(0, separator);
591
+ return [...own.flatMap((arg, index) => {
592
+ const optional = bare.get(arg);
593
+ const next = own[index + 1];
594
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
595
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
596
+ }), ...separator === -1 ? [] : args.slice(separator)];
597
+ }
598
+ function checkConflicts(values, options) {
599
+ const given = (name) => values[name] !== undefined && values[name] !== false;
600
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
601
+ const other = given(name) ? conflicts.find(given) : undefined;
602
+ if (other !== undefined)
603
+ badUsage(`--${name} cannot be used with --${other}`);
604
+ }
605
+ }
606
+ function checkChoices(values, options) {
607
+ for (const [name, option] of Object.entries(options)) {
608
+ if (option.choices === undefined)
609
+ continue;
610
+ const given = values[name];
611
+ for (const value of Array.isArray(given) ? given : [given]) {
612
+ if (typeof value === "string")
613
+ oneOf(value, name, option.choices);
614
+ }
615
+ }
616
+ }
617
+ function oneOf(value, name, choices) {
618
+ if (!choices.includes(value))
619
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
620
+ return value;
520
621
  }
521
622
  function checkPositionals(given, names) {
522
623
  const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
@@ -565,32 +666,12 @@ function nearestOption(message, options, allowNegative) {
565
666
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
566
667
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
567
668
  }
568
- var WHOLE = /^\d+$/;
569
- function wholeNumber(value, name, fallback, min = 1) {
570
- if (value === undefined)
571
- return fallback;
572
- const number = Number(value);
573
- if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
574
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
575
- return number;
576
- }
577
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
578
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
579
- function duration(value, name, fallback, unit = "s") {
580
- if (value === undefined)
581
- return fallback;
582
- const match = DURATION.exec(value.trim());
583
- const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
584
- if (ms < 1)
585
- badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
586
- return ms;
587
- }
588
669
  // ../kit/src/progress.ts
589
- import process5 from "process";
670
+ import process6 from "process";
590
671
 
591
672
  // ../kit/src/process.ts
592
673
  import { constants } from "os";
593
- import process4 from "process";
674
+ import process5 from "process";
594
675
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
595
676
  function exitCodeOf(code, signal) {
596
677
  if (code !== null)
@@ -611,7 +692,7 @@ function holdSignals(cleanup) {
611
692
  },
612
693
  release: () => {
613
694
  for (const signal of SIGNALS)
614
- process4.off(signal, onSignal);
695
+ process5.off(signal, onSignal);
615
696
  }
616
697
  };
617
698
  function onSignal(signal) {
@@ -624,10 +705,10 @@ function holdSignals(cleanup) {
624
705
  return;
625
706
  held.release();
626
707
  cleanup(signal);
627
- process4.kill(process4.pid, signal);
708
+ process5.kill(process5.pid, signal);
628
709
  }
629
710
  for (const signal of SIGNALS)
630
- process4.on(signal, onSignal);
711
+ process5.on(signal, onSignal);
631
712
  return held;
632
713
  }
633
714
 
@@ -642,7 +723,7 @@ var RESET_STYLE = `${ESC}[0m`;
642
723
  var CTRL_C = 3;
643
724
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
644
725
  var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
645
- function liveRegion(render, stream = process5.stderr, env = process5.env) {
726
+ function liveRegion(render, stream = process6.stderr, env = process6.env) {
646
727
  if (!takesControlCodes(stream, env))
647
728
  return { redraw: () => {
648
729
  return;
@@ -683,11 +764,11 @@ function liveRegion(render, stream = process5.stderr, env = process5.env) {
683
764
  clear();
684
765
  restore();
685
766
  release();
686
- process5.off("exit", onExit);
767
+ process6.off("exit", onExit);
687
768
  signals.release();
688
769
  }
689
770
  timer.unref();
690
- process5.on("exit", onExit);
771
+ process6.on("exit", onExit);
691
772
  return {
692
773
  redraw: draw,
693
774
  print: (text) => {
@@ -726,14 +807,14 @@ function cutToWidth(line, width) {
726
807
  return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
727
808
  }
728
809
  function swallowInput() {
729
- const input = process5.stdin;
810
+ const input = process6.stdin;
730
811
  if (!input.isTTY)
731
812
  return () => {
732
813
  return;
733
814
  };
734
815
  const onData = (data) => {
735
816
  if (data.includes(CTRL_C))
736
- process5.kill(process5.pid, "SIGINT");
817
+ process6.kill(process6.pid, "SIGINT");
737
818
  };
738
819
  input.setRawMode(true);
739
820
  input.on("data", onData);
@@ -749,7 +830,7 @@ function swallowInput() {
749
830
  };
750
831
  }
751
832
  function interceptOutput(clear) {
752
- const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process5.stdout, "write"], [process5.stderr, "write"]];
833
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process6.stdout, "write"], [process6.stderr, "write"]];
753
834
  const wrapped = targets.map(([target, name]) => {
754
835
  const original = Reflect.get(target, name);
755
836
  const wrapper = (...args) => {
@@ -767,15 +848,91 @@ function interceptOutput(clear) {
767
848
  };
768
849
  }
769
850
  // ../kit/src/cli.ts
770
- import process6 from "process";
851
+ import process9 from "process";
852
+
853
+ // ../kit/src/usage.ts
854
+ import { appendFileSync, mkdirSync } from "fs";
855
+ import { homedir as homedir2 } from "os";
856
+ import { dirname, isAbsolute, join as join2 } from "path";
857
+ import process8 from "process";
858
+
859
+ // ../kit/src/logs.ts
860
+ import { lstatSync, openSync } from "fs";
861
+ import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
862
+ import { homedir, tmpdir } from "os";
863
+ import { join } from "path";
864
+ import process7 from "process";
865
+ var DAY_MS = 24 * 60 * 60 * 1000;
866
+ var CLI_FOLDER = "kaynooo-cli";
867
+ function isPrivateDirectory(path) {
868
+ try {
869
+ const info = lstatSync(path, { throwIfNoEntry: false });
870
+ return info !== undefined && info.isDirectory() && info.uid === (process7.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
871
+ } catch {
872
+ return false;
873
+ }
874
+ }
875
+ async function privateLogDirectory(name, env = process7.env) {
876
+ const runtime = env.XDG_RUNTIME_DIR;
877
+ const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
878
+ const path = join(base, name);
879
+ try {
880
+ await mkdir(path, { recursive: true, mode: 448 });
881
+ if (isPrivateDirectory(path))
882
+ return path;
883
+ } catch {}
884
+ return mkdtemp(join(tmpdir(), `${name.replaceAll("/", "-")}-`));
885
+ }
886
+
887
+ // ../kit/src/usage.ts
888
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
889
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
890
+ var LONGEST_NAME = 40;
891
+ var usageError;
892
+ function noteUsageError(message) {
893
+ usageError = message;
894
+ }
895
+ function stateHome(env = process8.env) {
896
+ const dir = env.XDG_STATE_HOME;
897
+ return dir !== undefined && isAbsolute(dir) ? dir : join2(homedir2(), ".local", "state");
898
+ }
899
+ function usagePath(env = process8.env) {
900
+ return join2(stateHome(env), CLI_FOLDER, "usage.jsonl");
901
+ }
902
+ function usageRecorded(env = process8.env) {
903
+ const off = env.KAYNOOO_CLI_NO_USAGE;
904
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
905
+ }
906
+ function flagNames(argv) {
907
+ const end = argv.indexOf("--");
908
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
909
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
910
+ }
911
+ function usageEntry(bin, command, argv, code, now = new Date) {
912
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
913
+ usageError = undefined;
914
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
915
+ }
916
+ function recordUsage(entry, env = process8.env) {
917
+ if (!usageRecorded(env))
918
+ return;
919
+ try {
920
+ const path = usagePath(env);
921
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
922
+ appendFileSync(path, `${JSON.stringify(entry)}
923
+ `, { mode: 384 });
924
+ } catch {}
925
+ }
926
+
927
+ // ../kit/src/cli.ts
771
928
  var LEVEL_OPTIONS = {
772
929
  ...OUTPUT_OPTIONS,
773
930
  help: { type: "boolean", short: "h", description: "show this help" }
774
931
  };
775
932
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
776
933
  function printError(prefix, message, hint, cause) {
777
- const colors = paint(process6.stderr);
778
- const styled = takesControlCodes(process6.stderr);
934
+ const colors = paint(process9.stderr);
935
+ const styled = takesControlCodes(process9.stderr);
779
936
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
780
937
  const under = (label, text, tint) => text === undefined ? "" : `
781
938
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -794,90 +951,102 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
794
951
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
795
952
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
796
953
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
954
+ if (error instanceof UsageError)
955
+ noteUsageError(error.message);
797
956
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
798
957
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
799
958
  return error instanceof Exit ? error.code : 1;
800
959
  }
801
960
  var COMPLETE = "__complete";
802
961
  var FILES = "__files__";
803
- async function optionsOf(run) {
962
+ async function completingOf(run) {
804
963
  completion.active = true;
805
964
  try {
806
965
  await run([]);
807
966
  } catch (error) {
808
967
  if (error instanceof Completing)
809
- return error.options;
968
+ return error;
810
969
  } finally {
811
970
  completion.active = false;
812
971
  }
813
- return {};
972
+ return new Completing({});
973
+ }
974
+ function candidateLine(candidate) {
975
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
976
+ }
977
+ function positionalBeingTyped(before, { options, positionals }) {
978
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
979
+ let index = 0;
980
+ let at = 0;
981
+ while (at < before.length) {
982
+ const word = before[at];
983
+ if (word === "--") {
984
+ index += before.length - at - 1;
985
+ break;
986
+ }
987
+ if (!word.startsWith("-"))
988
+ index++;
989
+ else if (takesValue(word))
990
+ at++;
991
+ at++;
992
+ }
993
+ const last = positionals.at(-1);
994
+ if (index < positionals.length)
995
+ return positionals[index];
996
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
814
997
  }
815
998
  async function leafCandidates(run, words) {
816
- if (!(words.at(-1) ?? "").startsWith("-"))
817
- return [FILES];
818
- return Object.entries(await optionsOf(run)).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
999
+ const completing = await completingOf(run);
1000
+ if ((words.at(-1) ?? "").startsWith("-"))
1001
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1002
+ const flag = words.at(-2);
1003
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1004
+ if (option?.type === "string") {
1005
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1006
+ return values === undefined ? [FILES] : values.map(candidateLine);
1007
+ }
1008
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
1009
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
1010
+ return values === undefined ? [FILES] : values.map(candidateLine);
819
1011
  }
820
1012
  async function printCandidates(found) {
821
1013
  for (const line of await found)
822
1014
  console.log(line);
823
1015
  return 0;
824
1016
  }
825
- async function runMain({ name, version, run, redact }, argv = process6.argv.slice(2)) {
1017
+ async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
826
1018
  if (argv[0] === COMPLETE)
827
1019
  return printCandidates(leafCandidates(run, argv.slice(1)));
828
1020
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
829
1021
  console.log(version);
830
1022
  return 0;
831
1023
  }
1024
+ let code;
832
1025
  try {
833
- return await run(argv);
1026
+ code = await run(argv);
834
1027
  } catch (error) {
835
- return reportThrown(name, error, redact, wantsJson(argv));
1028
+ code = reportThrown(name, error, redact, wantsJson(argv));
836
1029
  }
837
- }
838
- // ../kit/src/logs.ts
839
- import { lstatSync, openSync } from "fs";
840
- import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
841
- import { homedir, tmpdir } from "os";
842
- import { join } from "path";
843
- import process7 from "process";
844
- var DAY_MS = 24 * 60 * 60 * 1000;
845
- var CLI_FOLDER = "kaynooo-cli";
846
- function isPrivateDirectory(path) {
847
- try {
848
- const info = lstatSync(path, { throwIfNoEntry: false });
849
- return info !== undefined && info.isDirectory() && info.uid === (process7.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
850
- } catch {
851
- return false;
852
- }
853
- }
854
- async function privateLogDirectory(name, env = process7.env) {
855
- const runtime = env.XDG_RUNTIME_DIR;
856
- const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
857
- const path = join(base, name);
858
- try {
859
- await mkdir(path, { recursive: true, mode: 448 });
860
- if (isPrivateDirectory(path))
861
- return path;
862
- } catch {}
863
- return mkdtemp(join(tmpdir(), `${name.replaceAll("/", "-")}-`));
1030
+ if (usage !== false)
1031
+ recordUsage(usageEntry(name, undefined, argv, code));
1032
+ return code;
864
1033
  }
865
1034
  // ../kit/src/secrets.ts
866
1035
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
867
1036
  // ../kit/src/sessions.ts
868
- import { homedir as homedir2 } from "os";
869
- import { join as join2 } from "path";
870
- import process8 from "process";
1037
+ import { homedir as homedir3 } from "os";
1038
+ import { join as join3 } from "path";
1039
+ import process10 from "process";
871
1040
  var {Glob } = globalThis.Bun;
872
1041
  var SESSION_FILES = new Glob("*.json");
873
1042
  var ACCOUNT_DIRS = new Glob("*/sessions");
874
1043
  async function sessionDirs() {
875
- const home = homedir2();
876
- const dirs = new Set([join2(home, ".claude", "sessions")]);
877
- if (process8.env.CLAUDE_CONFIG_DIR !== undefined)
878
- dirs.add(join2(process8.env.CLAUDE_CONFIG_DIR, "sessions"));
1044
+ 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"));
879
1048
  try {
880
- for await (const dir of ACCOUNT_DIRS.scan({ cwd: join2(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
1049
+ for await (const dir of ACCOUNT_DIRS.scan({ cwd: join3(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
881
1050
  dirs.add(dir);
882
1051
  } catch {}
883
1052
  return [...dirs];
@@ -921,7 +1090,7 @@ async function liveSessions() {
921
1090
  }
922
1091
  async function currentSession(sessions) {
923
1092
  const byPid = new Map(sessions.map((session) => [session.pid, session]));
924
- let pid = process8.ppid;
1093
+ let pid = process10.ppid;
925
1094
  for (let depth = 0;depth < 32 && pid > 1; depth++) {
926
1095
  const session = byPid.get(pid);
927
1096
  if (session !== undefined)
@@ -934,23 +1103,23 @@ async function currentSession(sessions) {
934
1103
  return;
935
1104
  }
936
1105
  // package.json
937
- var version = "0.5.0";
1106
+ var version = "0.5.1";
938
1107
 
939
1108
  // src/slot.ts
940
- import { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync } from "fs";
1109
+ import { existsSync, mkdirSync as mkdirSync2, readdirSync, readFileSync, unlinkSync } from "fs";
941
1110
  import { availableParallelism } from "os";
942
- import { join as join3 } from "path";
943
- import process11 from "process";
1111
+ import { join as join4 } from "path";
1112
+ import process13 from "process";
944
1113
 
945
1114
  // src/flock.ts
946
1115
  import { closeSync, constants as constants2, ftruncateSync, openSync as openSync2, writeSync } from "fs";
947
- import process10 from "process";
1116
+ import process12 from "process";
948
1117
  import { dlopen, FFIType } from "bun:ffi";
949
1118
  var LOCK_EX = 2;
950
1119
  var LOCK_NB = 4;
951
1120
  var flock;
952
1121
  function native() {
953
- flock ??= dlopen(process10.platform === "darwin" ? "libSystem.B.dylib" : "libc.so.6", { flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 } }).symbols.flock;
1122
+ flock ??= dlopen(process12.platform === "darwin" ? "libSystem.B.dylib" : "libc.so.6", { flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 } }).symbols.flock;
954
1123
  return flock;
955
1124
  }
956
1125
  function tryLock(path) {
@@ -994,9 +1163,9 @@ function defaultSlots() {
994
1163
  return Math.max(1, Math.floor(availableParallelism() / 2));
995
1164
  }
996
1165
  async function stateDir() {
997
- const dir = process11.env.SLOT_DIR ?? await privateLogDirectory("slot");
1166
+ const dir = process13.env.SLOT_DIR ?? await privateLogDirectory("slot");
998
1167
  for (const sub of ["slots", "locks", "waiters"])
999
- mkdirSync(join3(dir, sub), { recursive: true, mode: 448 });
1168
+ mkdirSync2(join4(dir, sub), { recursive: true, mode: 448 });
1000
1169
  return dir;
1001
1170
  }
1002
1171
  function readHolder(path) {
@@ -1008,7 +1177,7 @@ function readHolder(path) {
1008
1177
  }
1009
1178
  }
1010
1179
  function pathOf(dir, kind, name) {
1011
- return join3(dir, kind === "slot" ? "slots" : "locks", name);
1180
+ return join4(dir, kind === "slot" ? "slots" : "locks", name);
1012
1181
  }
1013
1182
  function candidates(dir, { kind, name, count }) {
1014
1183
  if (kind === "lock")
@@ -1036,7 +1205,7 @@ function waitingLine(dir, wanted) {
1036
1205
  }
1037
1206
  async function holderOf(command) {
1038
1207
  const session = await currentSession(await liveSessions());
1039
- return { pid: process11.pid, command: command.join(" "), cwd: process11.cwd(), since: Date.now(), ...session === undefined ? {} : { session: session.name } };
1208
+ return { pid: process13.pid, command: command.join(" "), cwd: process13.cwd(), since: Date.now(), ...session === undefined ? {} : { session: session.name } };
1040
1209
  }
1041
1210
  var waiterCount = 0;
1042
1211
  async function acquire(dir, resources, holder, deadline, timeoutMs) {
@@ -1062,7 +1231,7 @@ async function acquire(dir, resources, holder, deadline, timeoutMs) {
1062
1231
  held.release();
1063
1232
  const resource = busy.kind === "lock" ? `lock ${busy.name}` : "slot";
1064
1233
  if (waiter === undefined) {
1065
- const path = join3(dir, "waiters", `${process11.pid}-${waiterCount++}`);
1234
+ const path = join4(dir, "waiters", `${process13.pid}-${waiterCount++}`);
1066
1235
  const held = tryLock(path);
1067
1236
  if (held !== undefined) {
1068
1237
  writeHeld(held, JSON.stringify({ ...holder, resource }));
@@ -1103,7 +1272,7 @@ ${RUN_USAGE}`);
1103
1272
  const count = wholeNumber(values.slots, "slots", defaultSlots());
1104
1273
  const timeoutMs = duration(values.timeout, "timeout", Number.POSITIVE_INFINITY);
1105
1274
  const deadline = Date.now() + timeoutMs;
1106
- const holding = new Set((process11.env[HOLDING] ?? "").split(",").filter((token) => token !== ""));
1275
+ const holding = new Set((process13.env[HOLDING] ?? "").split(",").filter((token) => token !== ""));
1107
1276
  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 }]];
1108
1277
  const signals = holdSignals(() => {
1109
1278
  return;
@@ -1118,7 +1287,7 @@ ${RUN_USAGE}`);
1118
1287
  const tokens = new Set([...holding, ...locks.map((name) => `lock:${name}`), ...wanted.some((resource) => resource.kind === "slot") ? ["slot"] : []]);
1119
1288
  let child;
1120
1289
  try {
1121
- child = Bun.spawn(rest, { stdio: ["inherit", "inherit", "inherit"], env: { ...process11.env, [HOLDING]: [...tokens].join(",") } });
1290
+ child = Bun.spawn(rest, { stdio: ["inherit", "inherit", "inherit"], env: { ...process13.env, [HOLDING]: [...tokens].join(",") } });
1122
1291
  } catch (error) {
1123
1292
  fail(`cannot run ${rest[0]}: ${error instanceof Error ? error.message : String(error)}`, 127);
1124
1293
  }
@@ -1132,10 +1301,10 @@ ${RUN_USAGE}`);
1132
1301
  }
1133
1302
  }
1134
1303
  function scan(dir, state, kind) {
1135
- const folder = join3(dir, kind);
1304
+ const folder = join4(dir, kind);
1136
1305
  const entries = [];
1137
1306
  for (const name of existsSync(folder) ? readdirSync(folder) : []) {
1138
- const path = join3(folder, name);
1307
+ const path = join4(folder, name);
1139
1308
  const probe = tryLock(path);
1140
1309
  if (probe !== undefined) {
1141
1310
  if (kind === "waiters")
@@ -1168,4 +1337,4 @@ async function listSlots(args) {
1168
1337
  }
1169
1338
 
1170
1339
  // src/slot-cli.ts
1171
- process12.exitCode = await runMain({ name: "slot", version, run: async (args) => args[0] === "ls" ? listSlots(args.slice(1)) : runSlotted(args) });
1340
+ process14.exitCode = await runMain({ name: "slot", version, run: async (args) => args[0] === "ls" ? listSlots(args.slice(1)) : runSlotted(args) });