@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/cli.js CHANGED
@@ -3,10 +3,10 @@
3
3
 
4
4
  // src/cli.ts
5
5
  import { existsSync as existsSync3 } from "fs";
6
- import process11 from "process";
6
+ import process13 from "process";
7
7
 
8
8
  // ../kit/src/args.ts
9
- import process3 from "process";
9
+ import process4 from "process";
10
10
  import { parseArgs } from "util";
11
11
 
12
12
  // ../kit/src/format.ts
@@ -15,7 +15,7 @@ import process2 from "process";
15
15
  // ../kit/src/style.ts
16
16
  import process from "process";
17
17
 
18
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
19
19
  function x(s) {
20
20
  let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
21
21
  if (!/^[a-f0-9]+$/.test(r))
@@ -235,7 +235,7 @@ class e {
235
235
  }
236
236
  }
237
237
 
238
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
238
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
239
239
  var r = 39;
240
240
  var o = 49;
241
241
  var f2 = "\x1B[";
@@ -371,6 +371,55 @@ function printJson(value) {
371
371
  console.log(JSON.stringify(value, undefined, 2));
372
372
  }
373
373
 
374
+ // ../kit/src/help.ts
375
+ import process3 from "process";
376
+ var OPTIONAL = /\[[^\]]+\]/g;
377
+ var USAGE_PREFIX = /^usage:\s*/i;
378
+ var FULL_STOP = /\.$/;
379
+ function usageLine(usage, colors = paint(process3.stdout)) {
380
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
381
+ }
382
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
383
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
384
+ `);
385
+ }
386
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
387
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
388
+ }
389
+ function wantsHelpJson(env = process3.env) {
390
+ return env.KIT_HELP === "json";
391
+ }
392
+ function description(usage, { examples = [], replaces } = {}) {
393
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
394
+ `);
395
+ const first = lines[0];
396
+ const colon = first.indexOf(": ");
397
+ const prose = lines[lines.indexOf("") + 1] ?? "";
398
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
399
+ return {
400
+ synopsis: colon === -1 ? first : first.slice(0, colon),
401
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
402
+ ...replaces === undefined ? {} : { replaces },
403
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
404
+ };
405
+ }
406
+ function exampleRows(examples, colors = paint(process3.stdout)) {
407
+ if (examples.length === 0)
408
+ return [];
409
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
410
+ }
411
+ function optionRows(options, colors = paint(process3.stdout)) {
412
+ const rows = Object.entries(options).map(([name, option]) => {
413
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
414
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
415
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
416
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
417
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
418
+ });
419
+ const width = Math.max(0, ...rows.map((row) => row.width));
420
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
421
+ }
422
+
374
423
  // ../kit/src/text.ts
375
424
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
376
425
  function distance(a, b) {
@@ -390,8 +439,30 @@ function closest(name, names) {
390
439
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
391
440
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
392
441
  }
442
+ // ../kit/src/input.ts
443
+ var WHOLE = /^\d+$/;
444
+ function wholeNumber(value, name, fallback, min = 1) {
445
+ if (value === undefined)
446
+ return fallback;
447
+ const number = Number(value);
448
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
449
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
450
+ return number;
451
+ }
452
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
453
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
454
+ function duration(value, name, fallback, unit = "s") {
455
+ if (value === undefined)
456
+ return fallback;
457
+ const match = DURATION.exec(value.trim());
458
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
459
+ if (ms < 1)
460
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
461
+ return ms;
462
+ }
393
463
 
394
464
  // ../kit/src/args.ts
465
+ var DASHES = /^-+/;
395
466
  function jsonOption(holds) {
396
467
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
397
468
  }
@@ -426,61 +497,20 @@ class HelpShown extends Exit {
426
497
 
427
498
  class Completing {
428
499
  options;
429
- constructor(options) {
500
+ positionals;
501
+ candidates;
502
+ constructor(options, positionals = [], candidates = {}) {
430
503
  this.options = options;
504
+ this.positionals = positionals;
505
+ this.candidates = candidates;
431
506
  }
432
507
  }
433
508
  var completion = { active: false };
434
- var OPTIONAL = /\[[^\]]+\]/g;
435
- var USAGE_PREFIX = /^usage:\s*/i;
436
- var FULL_STOP = /\.$/;
437
- var DASHES = /^-+/;
438
- function usageLine(usage, colors = paint(process3.stdout)) {
439
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
440
- }
441
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
442
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
443
- `);
444
- }
445
- function replacesRows(replaces, colors = paint(process3.stdout)) {
446
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
447
- }
448
- function wantsHelpJson(env = process3.env) {
449
- return env.KIT_HELP === "json";
450
- }
451
- function description(usage, { examples = [], replaces } = {}) {
452
- const lines = usage.replace(USAGE_PREFIX, "").split(`
453
- `);
454
- const first = lines[0];
455
- const colon = first.indexOf(": ");
456
- const prose = lines[lines.indexOf("") + 1] ?? "";
457
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
458
- return {
459
- synopsis: colon === -1 ? first : first.slice(0, colon),
460
- summary: colon === -1 ? fallback : first.slice(colon + 2),
461
- ...replaces === undefined ? {} : { replaces },
462
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
463
- };
464
- }
465
- function exampleRows(examples, colors = paint(process3.stdout)) {
466
- if (examples.length === 0)
467
- return [];
468
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
469
- }
470
- function optionRows(options, colors = paint(process3.stdout)) {
471
- const rows = Object.entries(options).map(([name, option]) => {
472
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
473
- const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
474
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
475
- });
476
- const width = Math.max(0, ...rows.map((row) => row.width));
477
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
478
- }
479
509
  var OUTPUT_OPTIONS = {
480
510
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
481
511
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
482
512
  };
483
- function applyOutput(color, plain, env = process3.env) {
513
+ function applyOutput(color, plain, env = process4.env) {
484
514
  const when = plain === true ? "never" : color ?? "auto";
485
515
  if (when === "auto")
486
516
  return;
@@ -497,14 +527,13 @@ function applyOutput(color, plain, env = process3.env) {
497
527
  function parse(args, usage, options, settings = {}) {
498
528
  const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
499
529
  const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
530
+ const listing = listed(all, settings.allowNegative === true);
500
531
  if (completion.active)
501
- throw new Completing(all);
502
- const separator = settings.rest === true ? args.indexOf("--") : -1;
503
- const own = separator === -1 ? args : args.slice(0, separator);
504
- const rest = separator === -1 ? undefined : args.slice(separator + 1);
532
+ throw new Completing(listing, settings.positionals, settings.candidates);
533
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
505
534
  let parsed;
506
535
  try {
507
- parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
536
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
508
537
  } catch (error) {
509
538
  const message = parseError(error);
510
539
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -512,12 +541,84 @@ function parse(args, usage, options, settings = {}) {
512
541
  const values = parsed.values;
513
542
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
514
543
  if (values.help === true) {
515
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
544
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
516
545
  throw new HelpShown;
517
546
  }
547
+ checkChoices(parsed.values, all);
548
+ checkConflicts(parsed.values, all);
518
549
  if (settings.positionals !== undefined)
519
550
  checkPositionals(parsed.positionals, settings.positionals);
520
- return { ...parsed, positionals: parsed.positionals, rest };
551
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
552
+ }
553
+ function splitRest(args, passes) {
554
+ const separator = passes ? args.indexOf("--") : -1;
555
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
556
+ }
557
+ function splitTrailing(args, options, count) {
558
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
559
+ let seen = 0;
560
+ if (count === 0)
561
+ return { own: args, rest: undefined };
562
+ for (let at = 0;at < args.length; at++) {
563
+ const word = args[at];
564
+ if (word === "--")
565
+ break;
566
+ if (word.startsWith("-")) {
567
+ if (takesValue(word))
568
+ at++;
569
+ continue;
570
+ }
571
+ seen++;
572
+ if (seen === count)
573
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
574
+ }
575
+ return { own: args, rest: undefined };
576
+ }
577
+ function listed(options, allowNegative) {
578
+ if (!allowNegative)
579
+ return options;
580
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
581
+ if (option.type !== "boolean" || option.negative === undefined)
582
+ return [[name, option]];
583
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
584
+ }));
585
+ }
586
+ function withBare(args, options) {
587
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
588
+ if (bare.size === 0)
589
+ return args;
590
+ const separator = args.indexOf("--");
591
+ const own = separator === -1 ? args : args.slice(0, separator);
592
+ return [...own.flatMap((arg, index) => {
593
+ const optional = bare.get(arg);
594
+ const next = own[index + 1];
595
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
596
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
597
+ }), ...separator === -1 ? [] : args.slice(separator)];
598
+ }
599
+ function checkConflicts(values, options) {
600
+ const given = (name) => values[name] !== undefined && values[name] !== false;
601
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
602
+ const other = given(name) ? conflicts.find(given) : undefined;
603
+ if (other !== undefined)
604
+ badUsage(`--${name} cannot be used with --${other}`);
605
+ }
606
+ }
607
+ function checkChoices(values, options) {
608
+ for (const [name, option] of Object.entries(options)) {
609
+ if (option.choices === undefined)
610
+ continue;
611
+ const given = values[name];
612
+ for (const value of Array.isArray(given) ? given : [given]) {
613
+ if (typeof value === "string")
614
+ oneOf(value, name, option.choices);
615
+ }
616
+ }
617
+ }
618
+ function oneOf(value, name, choices) {
619
+ if (!choices.includes(value))
620
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
621
+ return value;
521
622
  }
522
623
  function checkPositionals(given, names) {
523
624
  const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
@@ -566,32 +667,12 @@ function nearestOption(message, options, allowNegative) {
566
667
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
567
668
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
568
669
  }
569
- var WHOLE = /^\d+$/;
570
- function wholeNumber(value, name, fallback, min = 1) {
571
- if (value === undefined)
572
- return fallback;
573
- const number = Number(value);
574
- if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
575
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
576
- return number;
577
- }
578
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
579
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
580
- function duration(value, name, fallback, unit = "s") {
581
- if (value === undefined)
582
- return fallback;
583
- const match = DURATION.exec(value.trim());
584
- const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
585
- if (ms < 1)
586
- badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
587
- return ms;
588
- }
589
670
  // ../kit/src/progress.ts
590
- import process5 from "process";
671
+ import process6 from "process";
591
672
 
592
673
  // ../kit/src/process.ts
593
674
  import { constants } from "os";
594
- import process4 from "process";
675
+ import process5 from "process";
595
676
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
596
677
  function exitCodeOf(code, signal) {
597
678
  if (code !== null)
@@ -612,7 +693,7 @@ function holdSignals(cleanup) {
612
693
  },
613
694
  release: () => {
614
695
  for (const signal of SIGNALS)
615
- process4.off(signal, onSignal);
696
+ process5.off(signal, onSignal);
616
697
  }
617
698
  };
618
699
  function onSignal(signal) {
@@ -625,10 +706,10 @@ function holdSignals(cleanup) {
625
706
  return;
626
707
  held.release();
627
708
  cleanup(signal);
628
- process4.kill(process4.pid, signal);
709
+ process5.kill(process5.pid, signal);
629
710
  }
630
711
  for (const signal of SIGNALS)
631
- process4.on(signal, onSignal);
712
+ process5.on(signal, onSignal);
632
713
  return held;
633
714
  }
634
715
 
@@ -643,7 +724,7 @@ var RESET_STYLE = `${ESC}[0m`;
643
724
  var CTRL_C = 3;
644
725
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
645
726
  var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
646
- function liveRegion(render, stream = process5.stderr, env = process5.env) {
727
+ function liveRegion(render, stream = process6.stderr, env = process6.env) {
647
728
  if (!takesControlCodes(stream, env))
648
729
  return { redraw: () => {
649
730
  return;
@@ -684,11 +765,11 @@ function liveRegion(render, stream = process5.stderr, env = process5.env) {
684
765
  clear();
685
766
  restore();
686
767
  release();
687
- process5.off("exit", onExit);
768
+ process6.off("exit", onExit);
688
769
  signals.release();
689
770
  }
690
771
  timer.unref();
691
- process5.on("exit", onExit);
772
+ process6.on("exit", onExit);
692
773
  return {
693
774
  redraw: draw,
694
775
  print: (text) => {
@@ -727,14 +808,14 @@ function cutToWidth(line, width) {
727
808
  return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
728
809
  }
729
810
  function swallowInput() {
730
- const input = process5.stdin;
811
+ const input = process6.stdin;
731
812
  if (!input.isTTY)
732
813
  return () => {
733
814
  return;
734
815
  };
735
816
  const onData = (data) => {
736
817
  if (data.includes(CTRL_C))
737
- process5.kill(process5.pid, "SIGINT");
818
+ process6.kill(process6.pid, "SIGINT");
738
819
  };
739
820
  input.setRawMode(true);
740
821
  input.on("data", onData);
@@ -750,7 +831,7 @@ function swallowInput() {
750
831
  };
751
832
  }
752
833
  function interceptOutput(clear) {
753
- const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process5.stdout, "write"], [process5.stderr, "write"]];
834
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process6.stdout, "write"], [process6.stderr, "write"]];
754
835
  const wrapped = targets.map(([target, name]) => {
755
836
  const original = Reflect.get(target, name);
756
837
  const wrapper = (...args) => {
@@ -768,15 +849,91 @@ function interceptOutput(clear) {
768
849
  };
769
850
  }
770
851
  // ../kit/src/cli.ts
771
- import process6 from "process";
852
+ import process9 from "process";
853
+
854
+ // ../kit/src/usage.ts
855
+ import { appendFileSync, mkdirSync } from "fs";
856
+ import { homedir as homedir2 } from "os";
857
+ import { dirname, isAbsolute, join as join2 } from "path";
858
+ import process8 from "process";
859
+
860
+ // ../kit/src/logs.ts
861
+ import { lstatSync, openSync } from "fs";
862
+ import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
863
+ import { homedir, tmpdir } from "os";
864
+ import { join } from "path";
865
+ import process7 from "process";
866
+ var DAY_MS = 24 * 60 * 60 * 1000;
867
+ var CLI_FOLDER = "kaynooo-cli";
868
+ function isPrivateDirectory(path) {
869
+ try {
870
+ const info = lstatSync(path, { throwIfNoEntry: false });
871
+ return info !== undefined && info.isDirectory() && info.uid === (process7.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
872
+ } catch {
873
+ return false;
874
+ }
875
+ }
876
+ async function privateLogDirectory(name, env = process7.env) {
877
+ const runtime = env.XDG_RUNTIME_DIR;
878
+ const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
879
+ const path = join(base, name);
880
+ try {
881
+ await mkdir(path, { recursive: true, mode: 448 });
882
+ if (isPrivateDirectory(path))
883
+ return path;
884
+ } catch {}
885
+ return mkdtemp(join(tmpdir(), `${name.replaceAll("/", "-")}-`));
886
+ }
887
+
888
+ // ../kit/src/usage.ts
889
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
890
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
891
+ var LONGEST_NAME = 40;
892
+ var usageError;
893
+ function noteUsageError(message) {
894
+ usageError = message;
895
+ }
896
+ function stateHome(env = process8.env) {
897
+ const dir = env.XDG_STATE_HOME;
898
+ return dir !== undefined && isAbsolute(dir) ? dir : join2(homedir2(), ".local", "state");
899
+ }
900
+ function usagePath(env = process8.env) {
901
+ return join2(stateHome(env), CLI_FOLDER, "usage.jsonl");
902
+ }
903
+ function usageRecorded(env = process8.env) {
904
+ const off = env.KAYNOOO_CLI_NO_USAGE;
905
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
906
+ }
907
+ function flagNames(argv) {
908
+ const end = argv.indexOf("--");
909
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
910
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
911
+ }
912
+ function usageEntry(bin, command, argv, code, now = new Date) {
913
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
914
+ usageError = undefined;
915
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
916
+ }
917
+ function recordUsage(entry, env = process8.env) {
918
+ if (!usageRecorded(env))
919
+ return;
920
+ try {
921
+ const path = usagePath(env);
922
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
923
+ appendFileSync(path, `${JSON.stringify(entry)}
924
+ `, { mode: 384 });
925
+ } catch {}
926
+ }
927
+
928
+ // ../kit/src/cli.ts
772
929
  var LEVEL_OPTIONS = {
773
930
  ...OUTPUT_OPTIONS,
774
931
  help: { type: "boolean", short: "h", description: "show this help" }
775
932
  };
776
933
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
777
934
  function printError(prefix, message, hint, cause) {
778
- const colors = paint(process6.stderr);
779
- const styled = takesControlCodes(process6.stderr);
935
+ const colors = paint(process9.stderr);
936
+ const styled = takesControlCodes(process9.stderr);
780
937
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
781
938
  const under = (label, text, tint) => text === undefined ? "" : `
782
939
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -795,90 +952,102 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
795
952
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
796
953
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
797
954
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
955
+ if (error instanceof UsageError)
956
+ noteUsageError(error.message);
798
957
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
799
958
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
800
959
  return error instanceof Exit ? error.code : 1;
801
960
  }
802
961
  var COMPLETE = "__complete";
803
962
  var FILES = "__files__";
804
- async function optionsOf(run) {
963
+ async function completingOf(run) {
805
964
  completion.active = true;
806
965
  try {
807
966
  await run([]);
808
967
  } catch (error) {
809
968
  if (error instanceof Completing)
810
- return error.options;
969
+ return error;
811
970
  } finally {
812
971
  completion.active = false;
813
972
  }
814
- return {};
973
+ return new Completing({});
974
+ }
975
+ function candidateLine(candidate) {
976
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
977
+ }
978
+ function positionalBeingTyped(before, { options, positionals }) {
979
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
980
+ let index = 0;
981
+ let at = 0;
982
+ while (at < before.length) {
983
+ const word = before[at];
984
+ if (word === "--") {
985
+ index += before.length - at - 1;
986
+ break;
987
+ }
988
+ if (!word.startsWith("-"))
989
+ index++;
990
+ else if (takesValue(word))
991
+ at++;
992
+ at++;
993
+ }
994
+ const last = positionals.at(-1);
995
+ if (index < positionals.length)
996
+ return positionals[index];
997
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
815
998
  }
816
999
  async function leafCandidates(run, words) {
817
- if (!(words.at(-1) ?? "").startsWith("-"))
818
- return [FILES];
819
- return Object.entries(await optionsOf(run)).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1000
+ const completing = await completingOf(run);
1001
+ if ((words.at(-1) ?? "").startsWith("-"))
1002
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1003
+ const flag = words.at(-2);
1004
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1005
+ if (option?.type === "string") {
1006
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1007
+ return values === undefined ? [FILES] : values.map(candidateLine);
1008
+ }
1009
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
1010
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
1011
+ return values === undefined ? [FILES] : values.map(candidateLine);
820
1012
  }
821
1013
  async function printCandidates(found) {
822
1014
  for (const line of await found)
823
1015
  console.log(line);
824
1016
  return 0;
825
1017
  }
826
- async function runMain({ name, version, run, redact }, argv = process6.argv.slice(2)) {
1018
+ async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
827
1019
  if (argv[0] === COMPLETE)
828
1020
  return printCandidates(leafCandidates(run, argv.slice(1)));
829
1021
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
830
1022
  console.log(version);
831
1023
  return 0;
832
1024
  }
1025
+ let code;
833
1026
  try {
834
- return await run(argv);
1027
+ code = await run(argv);
835
1028
  } catch (error) {
836
- return reportThrown(name, error, redact, wantsJson(argv));
1029
+ code = reportThrown(name, error, redact, wantsJson(argv));
837
1030
  }
838
- }
839
- // ../kit/src/logs.ts
840
- import { lstatSync, openSync } from "fs";
841
- import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
842
- import { homedir, tmpdir } from "os";
843
- import { join } from "path";
844
- import process7 from "process";
845
- var DAY_MS = 24 * 60 * 60 * 1000;
846
- var CLI_FOLDER = "kaynooo-cli";
847
- function isPrivateDirectory(path) {
848
- try {
849
- const info = lstatSync(path, { throwIfNoEntry: false });
850
- return info !== undefined && info.isDirectory() && info.uid === (process7.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
851
- } catch {
852
- return false;
853
- }
854
- }
855
- async function privateLogDirectory(name, env = process7.env) {
856
- const runtime = env.XDG_RUNTIME_DIR;
857
- const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
858
- const path = join(base, name);
859
- try {
860
- await mkdir(path, { recursive: true, mode: 448 });
861
- if (isPrivateDirectory(path))
862
- return path;
863
- } catch {}
864
- return mkdtemp(join(tmpdir(), `${name.replaceAll("/", "-")}-`));
1031
+ if (usage !== false)
1032
+ recordUsage(usageEntry(name, undefined, argv, code));
1033
+ return code;
865
1034
  }
866
1035
  // ../kit/src/secrets.ts
867
1036
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
868
1037
  // ../kit/src/sessions.ts
869
- import { homedir as homedir2 } from "os";
870
- import { join as join2 } from "path";
871
- import process8 from "process";
1038
+ import { homedir as homedir3 } from "os";
1039
+ import { join as join3 } from "path";
1040
+ import process10 from "process";
872
1041
  var {Glob } = globalThis.Bun;
873
1042
  var SESSION_FILES = new Glob("*.json");
874
1043
  var ACCOUNT_DIRS = new Glob("*/sessions");
875
1044
  async function sessionDirs() {
876
- const home = homedir2();
877
- const dirs = new Set([join2(home, ".claude", "sessions")]);
878
- if (process8.env.CLAUDE_CONFIG_DIR !== undefined)
879
- dirs.add(join2(process8.env.CLAUDE_CONFIG_DIR, "sessions"));
1045
+ const home = homedir3();
1046
+ const dirs = new Set([join3(home, ".claude", "sessions")]);
1047
+ if (process10.env.CLAUDE_CONFIG_DIR !== undefined)
1048
+ dirs.add(join3(process10.env.CLAUDE_CONFIG_DIR, "sessions"));
880
1049
  try {
881
- for await (const dir of ACCOUNT_DIRS.scan({ cwd: join2(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
1050
+ for await (const dir of ACCOUNT_DIRS.scan({ cwd: join3(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
882
1051
  dirs.add(dir);
883
1052
  } catch {}
884
1053
  return [...dirs];
@@ -922,7 +1091,7 @@ async function liveSessions() {
922
1091
  }
923
1092
  async function currentSession(sessions) {
924
1093
  const byPid = new Map(sessions.map((session) => [session.pid, session]));
925
- let pid = process8.ppid;
1094
+ let pid = process10.ppid;
926
1095
  for (let depth = 0;depth < 32 && pid > 1; depth++) {
927
1096
  const session = byPid.get(pid);
928
1097
  if (session !== undefined)
@@ -935,7 +1104,7 @@ async function currentSession(sessions) {
935
1104
  return;
936
1105
  }
937
1106
  // package.json
938
- var version = "0.5.0";
1107
+ var version = "0.5.1";
939
1108
 
940
1109
  // src/conditions.ts
941
1110
  import { existsSync, statSync } from "fs";
@@ -1063,8 +1232,8 @@ async function urlCheck(url, timeout) {
1063
1232
 
1064
1233
  // src/task.ts
1065
1234
  import { existsSync as existsSync2, lstatSync as lstatSync2, readFileSync, statSync as statSync2 } from "fs";
1066
- import { join as join3 } from "path";
1067
- import process10 from "process";
1235
+ import { join as join4 } from "path";
1236
+ import process12 from "process";
1068
1237
  var EXITED = /(?:^|\n)\[exited with code (-?\d+)\]\n*$/;
1069
1238
  var FAILURE = /\(fail\)|\berror:/i;
1070
1239
  var TASK_ID = /^[\w-]+$/;
@@ -1072,16 +1241,16 @@ var TAIL_BYTES = 256;
1072
1241
  var LONGEST_FAILURES = 30;
1073
1242
  var CARRIAGE_RETURN2 = /\r$/;
1074
1243
  function tasksRoot(env) {
1075
- return join3(env.CLAUDE_CODE_TMPDIR ?? env.TMPDIR ?? "/tmp", `claude-${process10.getuid?.() ?? 0}`);
1244
+ return join4(env.CLAUDE_CODE_TMPDIR ?? env.TMPDIR ?? "/tmp", `claude-${process12.getuid?.() ?? 0}`);
1076
1245
  }
1077
- function taskFile(task, env = process10.env) {
1246
+ function taskFile(task, env = process12.env) {
1078
1247
  if (task.includes("/") || task.endsWith(".output"))
1079
1248
  return task;
1080
1249
  if (!TASK_ID.test(task))
1081
1250
  return;
1082
1251
  const root = tasksRoot(env);
1083
1252
  const found = existsSync2(root) ? [...new Bun.Glob(`*/*/tasks/${task}.output`).scanSync({ cwd: root, onlyFiles: false })] : [];
1084
- return found.length === 0 ? undefined : join3(root, found[0] ?? "");
1253
+ return found.length === 0 ? undefined : join4(root, found[0] ?? "");
1085
1254
  }
1086
1255
  function isTranscript(path) {
1087
1256
  return existsSync2(path) && lstatSync2(path).isSymbolicLink() && path.endsWith(".output");
@@ -1107,7 +1276,7 @@ async function taskEnd(path, lines) {
1107
1276
  }
1108
1277
  function pidAlive(pid) {
1109
1278
  try {
1110
- process10.kill(pid, 0);
1279
+ process12.kill(pid, 0);
1111
1280
  } catch (error) {
1112
1281
  return error.code === "EPERM";
1113
1282
  }
@@ -1178,7 +1347,7 @@ async function waitTask(args) {
1178
1347
  const lines = wholeNumber(values.lines, "lines", 20);
1179
1348
  const timeout = duration(values.timeout, "timeout", 5 * 60000);
1180
1349
  const started = Date.now();
1181
- const { dim } = paint(process11.stderr);
1350
+ const { dim } = paint(process13.stderr);
1182
1351
  const region = liveRegion((spinner) => [`${spinner} task ${task}: still running ${dim(formatElapsed(Date.now() - started))}`]);
1183
1352
  let code;
1184
1353
  try {
@@ -1237,7 +1406,7 @@ ${USAGE}`);
1237
1406
  let portLeft = port === undefined ? undefined : "not checked yet";
1238
1407
  let urlLeft = values.url === undefined ? undefined : "not checked yet";
1239
1408
  let isPidLeft = pid !== undefined;
1240
- const { dim } = paint(process11.stderr);
1409
+ const { dim } = paint(process13.stderr);
1241
1410
  const region = liveRegion((spinner) => {
1242
1411
  const waited = dim(formatElapsed(Date.now() - started));
1243
1412
  const left = [
@@ -1303,4 +1472,4 @@ ${numbered(event.excerpt, event.line)}`);
1303
1472
  last lines of ${watch?.path}:
1304
1473
  ${numbered(lines)}`}`);
1305
1474
  }
1306
- process11.exitCode = await runMain({ name: "waitfor", version, run: main });
1475
+ process13.exitCode = await runMain({ name: "waitfor", version, run: main });