@kaynooo/cli-code 0.5.0 → 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/peek.js CHANGED
@@ -3,12 +3,11 @@
3
3
 
4
4
  // src/peek.ts
5
5
  import { realpathSync } from "fs";
6
- import { isAbsolute, join as join2, relative as relative2, resolve, sep } from "path";
7
- import process7 from "process";
6
+ import { isAbsolute as isAbsolute2, join as join3, relative as relative2, resolve, sep } from "path";
7
+ import process9 from "process";
8
8
 
9
9
  // ../kit/src/args.ts
10
- import { fstatSync } from "fs";
11
- import process3 from "process";
10
+ import process4 from "process";
12
11
  import { parseArgs } from "util";
13
12
 
14
13
  // ../kit/src/format.ts
@@ -17,7 +16,7 @@ import process2 from "process";
17
16
  // ../kit/src/style.ts
18
17
  import process from "process";
19
18
 
20
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
19
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
21
20
  function x(s) {
22
21
  let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
23
22
  if (!/^[a-f0-9]+$/.test(r))
@@ -237,7 +236,7 @@ class e {
237
236
  }
238
237
  }
239
238
 
240
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
239
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
241
240
  var r = 39;
242
241
  var o = 49;
243
242
  var f2 = "\x1B[";
@@ -361,6 +360,55 @@ function printJson(value) {
361
360
  console.log(JSON.stringify(value, undefined, 2));
362
361
  }
363
362
 
363
+ // ../kit/src/help.ts
364
+ import process3 from "process";
365
+ var OPTIONAL = /\[[^\]]+\]/g;
366
+ var USAGE_PREFIX = /^usage:\s*/i;
367
+ var FULL_STOP = /\.$/;
368
+ function usageLine(usage, colors = paint(process3.stdout)) {
369
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
370
+ }
371
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
372
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
373
+ `);
374
+ }
375
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
376
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
377
+ }
378
+ function wantsHelpJson(env = process3.env) {
379
+ return env.KIT_HELP === "json";
380
+ }
381
+ function description(usage, { examples = [], replaces } = {}) {
382
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
383
+ `);
384
+ const first = lines[0];
385
+ const colon = first.indexOf(": ");
386
+ const prose = lines[lines.indexOf("") + 1] ?? "";
387
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
388
+ return {
389
+ synopsis: colon === -1 ? first : first.slice(0, colon),
390
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
391
+ ...replaces === undefined ? {} : { replaces },
392
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
393
+ };
394
+ }
395
+ function exampleRows(examples, colors = paint(process3.stdout)) {
396
+ if (examples.length === 0)
397
+ return [];
398
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
399
+ }
400
+ function optionRows(options, colors = paint(process3.stdout)) {
401
+ const rows = Object.entries(options).map(([name, option]) => {
402
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
403
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
404
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
405
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
406
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
407
+ });
408
+ const width = Math.max(0, ...rows.map((row) => row.width));
409
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
410
+ }
411
+
364
412
  // ../kit/src/text.ts
365
413
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
366
414
  function distance(a, b) {
@@ -380,8 +428,24 @@ function closest(name, names) {
380
428
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
381
429
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
382
430
  }
431
+ // ../kit/src/input.ts
432
+ import { fstatSync } from "fs";
433
+ var WHOLE = /^\d+$/;
434
+ function wholeNumber(value, name, fallback, min = 1) {
435
+ if (value === undefined)
436
+ return fallback;
437
+ const number = Number(value);
438
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
439
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
440
+ return number;
441
+ }
442
+ function isStdinPiped() {
443
+ const stat = fstatSync(0);
444
+ return stat.isFIFO() || stat.isFile();
445
+ }
383
446
 
384
447
  // ../kit/src/args.ts
448
+ var DASHES = /^-+/;
385
449
  function jsonOption(holds) {
386
450
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
387
451
  }
@@ -416,61 +480,20 @@ class HelpShown extends Exit {
416
480
 
417
481
  class Completing {
418
482
  options;
419
- constructor(options) {
483
+ positionals;
484
+ candidates;
485
+ constructor(options, positionals = [], candidates = {}) {
420
486
  this.options = options;
487
+ this.positionals = positionals;
488
+ this.candidates = candidates;
421
489
  }
422
490
  }
423
491
  var completion = { active: false };
424
- var OPTIONAL = /\[[^\]]+\]/g;
425
- var USAGE_PREFIX = /^usage:\s*/i;
426
- var FULL_STOP = /\.$/;
427
- var DASHES = /^-+/;
428
- function usageLine(usage, colors = paint(process3.stdout)) {
429
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
430
- }
431
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
432
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
433
- `);
434
- }
435
- function replacesRows(replaces, colors = paint(process3.stdout)) {
436
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
437
- }
438
- function wantsHelpJson(env = process3.env) {
439
- return env.KIT_HELP === "json";
440
- }
441
- function description(usage, { examples = [], replaces } = {}) {
442
- const lines = usage.replace(USAGE_PREFIX, "").split(`
443
- `);
444
- const first = lines[0];
445
- const colon = first.indexOf(": ");
446
- const prose = lines[lines.indexOf("") + 1] ?? "";
447
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
448
- return {
449
- synopsis: colon === -1 ? first : first.slice(0, colon),
450
- summary: colon === -1 ? fallback : first.slice(colon + 2),
451
- ...replaces === undefined ? {} : { replaces },
452
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
453
- };
454
- }
455
- function exampleRows(examples, colors = paint(process3.stdout)) {
456
- if (examples.length === 0)
457
- return [];
458
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
459
- }
460
- function optionRows(options, colors = paint(process3.stdout)) {
461
- const rows = Object.entries(options).map(([name, option]) => {
462
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
463
- const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
464
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
465
- });
466
- const width = Math.max(0, ...rows.map((row) => row.width));
467
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
468
- }
469
492
  var OUTPUT_OPTIONS = {
470
493
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
471
494
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
472
495
  };
473
- function applyOutput(color, plain, env = process3.env) {
496
+ function applyOutput(color, plain, env = process4.env) {
474
497
  const when = plain === true ? "never" : color ?? "auto";
475
498
  if (when === "auto")
476
499
  return;
@@ -487,14 +510,13 @@ function applyOutput(color, plain, env = process3.env) {
487
510
  function parse(args, usage, options, settings = {}) {
488
511
  const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
489
512
  const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
513
+ const listing = listed(all, settings.allowNegative === true);
490
514
  if (completion.active)
491
- throw new Completing(all);
492
- const separator = settings.rest === true ? args.indexOf("--") : -1;
493
- const own = separator === -1 ? args : args.slice(0, separator);
494
- const rest = separator === -1 ? undefined : args.slice(separator + 1);
515
+ throw new Completing(listing, settings.positionals, settings.candidates);
516
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
495
517
  let parsed;
496
518
  try {
497
- parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
519
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
498
520
  } catch (error) {
499
521
  const message = parseError(error);
500
522
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -502,12 +524,84 @@ function parse(args, usage, options, settings = {}) {
502
524
  const values = parsed.values;
503
525
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
504
526
  if (values.help === true) {
505
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
527
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
506
528
  throw new HelpShown;
507
529
  }
530
+ checkChoices(parsed.values, all);
531
+ checkConflicts(parsed.values, all);
508
532
  if (settings.positionals !== undefined)
509
533
  checkPositionals(parsed.positionals, settings.positionals);
510
- return { ...parsed, positionals: parsed.positionals, rest };
534
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
535
+ }
536
+ function splitRest(args, passes) {
537
+ const separator = passes ? args.indexOf("--") : -1;
538
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
539
+ }
540
+ function splitTrailing(args, options, count) {
541
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
542
+ let seen = 0;
543
+ if (count === 0)
544
+ return { own: args, rest: undefined };
545
+ for (let at = 0;at < args.length; at++) {
546
+ const word = args[at];
547
+ if (word === "--")
548
+ break;
549
+ if (word.startsWith("-")) {
550
+ if (takesValue(word))
551
+ at++;
552
+ continue;
553
+ }
554
+ seen++;
555
+ if (seen === count)
556
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
557
+ }
558
+ return { own: args, rest: undefined };
559
+ }
560
+ function listed(options, allowNegative) {
561
+ if (!allowNegative)
562
+ return options;
563
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
564
+ if (option.type !== "boolean" || option.negative === undefined)
565
+ return [[name, option]];
566
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
567
+ }));
568
+ }
569
+ function withBare(args, options) {
570
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
571
+ if (bare.size === 0)
572
+ return args;
573
+ const separator = args.indexOf("--");
574
+ const own = separator === -1 ? args : args.slice(0, separator);
575
+ return [...own.flatMap((arg, index) => {
576
+ const optional = bare.get(arg);
577
+ const next = own[index + 1];
578
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
579
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
580
+ }), ...separator === -1 ? [] : args.slice(separator)];
581
+ }
582
+ function checkConflicts(values, options) {
583
+ const given = (name) => values[name] !== undefined && values[name] !== false;
584
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
585
+ const other = given(name) ? conflicts.find(given) : undefined;
586
+ if (other !== undefined)
587
+ badUsage(`--${name} cannot be used with --${other}`);
588
+ }
589
+ }
590
+ function checkChoices(values, options) {
591
+ for (const [name, option] of Object.entries(options)) {
592
+ if (option.choices === undefined)
593
+ continue;
594
+ const given = values[name];
595
+ for (const value of Array.isArray(given) ? given : [given]) {
596
+ if (typeof value === "string")
597
+ oneOf(value, name, option.choices);
598
+ }
599
+ }
600
+ }
601
+ function oneOf(value, name, choices) {
602
+ if (!choices.includes(value))
603
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
604
+ return value;
511
605
  }
512
606
  function checkPositionals(given, names) {
513
607
  const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
@@ -556,22 +650,9 @@ function nearestOption(message, options, allowNegative) {
556
650
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
557
651
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
558
652
  }
559
- var WHOLE = /^\d+$/;
560
- function wholeNumber(value, name, fallback, min = 1) {
561
- if (value === undefined)
562
- return fallback;
563
- const number = Number(value);
564
- if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
565
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
566
- return number;
567
- }
568
- function isStdinPiped() {
569
- const stat = fstatSync(0);
570
- return stat.isFIFO() || stat.isFile();
571
- }
572
653
  // ../kit/src/process.ts
573
654
  import { constants } from "os";
574
- import process4 from "process";
655
+ import process5 from "process";
575
656
  var KILL_GRACE_MS = 2000;
576
657
  function exitCodeOf(code, signal) {
577
658
  if (code !== null)
@@ -591,7 +672,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
591
672
  return;
592
673
  try {
593
674
  if (grouped)
594
- process4.kill(-proc.pid, killing);
675
+ process5.kill(-proc.pid, killing);
595
676
  else
596
677
  proc.kill(killing);
597
678
  } catch {}
@@ -665,15 +746,67 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
665
746
  var RESET_STYLE = `${ESC}[0m`;
666
747
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
667
748
  // ../kit/src/cli.ts
668
- import process5 from "process";
749
+ import process7 from "process";
750
+
751
+ // ../kit/src/usage.ts
752
+ import { appendFileSync, mkdirSync } from "fs";
753
+ import { homedir } from "os";
754
+ import { dirname, isAbsolute, join } from "path";
755
+ import process6 from "process";
756
+
757
+ // ../kit/src/logs.ts
758
+ var DAY_MS = 24 * 60 * 60 * 1000;
759
+ var CLI_FOLDER = "kaynooo-cli";
760
+
761
+ // ../kit/src/usage.ts
762
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
763
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
764
+ var LONGEST_NAME = 40;
765
+ var usageError;
766
+ function noteUsageError(message) {
767
+ usageError = message;
768
+ }
769
+ function stateHome(env = process6.env) {
770
+ const dir = env.XDG_STATE_HOME;
771
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
772
+ }
773
+ function usagePath(env = process6.env) {
774
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
775
+ }
776
+ function usageRecorded(env = process6.env) {
777
+ const off = env.KAYNOOO_CLI_NO_USAGE;
778
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
779
+ }
780
+ function flagNames(argv) {
781
+ const end = argv.indexOf("--");
782
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
783
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
784
+ }
785
+ function usageEntry(bin, command, argv, code, now = new Date) {
786
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
787
+ usageError = undefined;
788
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
789
+ }
790
+ function recordUsage(entry, env = process6.env) {
791
+ if (!usageRecorded(env))
792
+ return;
793
+ try {
794
+ const path = usagePath(env);
795
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
796
+ appendFileSync(path, `${JSON.stringify(entry)}
797
+ `, { mode: 384 });
798
+ } catch {}
799
+ }
800
+
801
+ // ../kit/src/cli.ts
669
802
  var LEVEL_OPTIONS = {
670
803
  ...OUTPUT_OPTIONS,
671
804
  help: { type: "boolean", short: "h", description: "show this help" }
672
805
  };
673
806
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
674
807
  function printError(prefix, message, hint, cause) {
675
- const colors = paint(process5.stderr);
676
- const styled = takesControlCodes(process5.stderr);
808
+ const colors = paint(process7.stderr);
809
+ const styled = takesControlCodes(process7.stderr);
677
810
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
678
811
  const under = (label, text, tint) => text === undefined ? "" : `
679
812
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -692,51 +825,90 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
692
825
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
693
826
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
694
827
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
828
+ if (error instanceof UsageError)
829
+ noteUsageError(error.message);
695
830
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
696
831
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
697
832
  return error instanceof Exit ? error.code : 1;
698
833
  }
699
834
  var COMPLETE = "__complete";
700
835
  var FILES = "__files__";
701
- async function optionsOf(run) {
836
+ async function completingOf(run) {
702
837
  completion.active = true;
703
838
  try {
704
839
  await run([]);
705
840
  } catch (error) {
706
841
  if (error instanceof Completing)
707
- return error.options;
842
+ return error;
708
843
  } finally {
709
844
  completion.active = false;
710
845
  }
711
- return {};
846
+ return new Completing({});
847
+ }
848
+ function candidateLine(candidate) {
849
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
850
+ }
851
+ function positionalBeingTyped(before, { options, positionals }) {
852
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
853
+ let index = 0;
854
+ let at = 0;
855
+ while (at < before.length) {
856
+ const word = before[at];
857
+ if (word === "--") {
858
+ index += before.length - at - 1;
859
+ break;
860
+ }
861
+ if (!word.startsWith("-"))
862
+ index++;
863
+ else if (takesValue(word))
864
+ at++;
865
+ at++;
866
+ }
867
+ const last = positionals.at(-1);
868
+ if (index < positionals.length)
869
+ return positionals[index];
870
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
712
871
  }
713
872
  async function leafCandidates(run, words) {
714
- if (!(words.at(-1) ?? "").startsWith("-"))
715
- return [FILES];
716
- return Object.entries(await optionsOf(run)).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
873
+ const completing = await completingOf(run);
874
+ if ((words.at(-1) ?? "").startsWith("-"))
875
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
876
+ const flag = words.at(-2);
877
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
878
+ if (option?.type === "string") {
879
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
880
+ return values === undefined ? [FILES] : values.map(candidateLine);
881
+ }
882
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
883
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
884
+ return values === undefined ? [FILES] : values.map(candidateLine);
717
885
  }
718
886
  async function printCandidates(found) {
719
887
  for (const line of await found)
720
888
  console.log(line);
721
889
  return 0;
722
890
  }
723
- async function runMain({ name, version, run, redact }, argv = process5.argv.slice(2)) {
891
+ async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
724
892
  if (argv[0] === COMPLETE)
725
893
  return printCandidates(leafCandidates(run, argv.slice(1)));
726
894
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
727
895
  console.log(version);
728
896
  return 0;
729
897
  }
898
+ let code;
730
899
  try {
731
- return await run(argv);
900
+ code = await run(argv);
732
901
  } catch (error) {
733
- return reportThrown(name, error, redact, wantsJson(argv));
902
+ code = reportThrown(name, error, redact, wantsJson(argv));
734
903
  }
904
+ if (usage !== false)
905
+ recordUsage(usageEntry(name, undefined, argv, code));
906
+ return code;
735
907
  }
736
908
  // ../kit/src/limit.ts
737
909
  function limitOptions(fallback) {
738
910
  return {
739
- limit: { type: "string", description: `show at most this many rows, the rest counted (${fallback})` },
911
+ limit: { type: "string", short: "n", description: `show at most this many rows, the rest counted (${fallback})` },
740
912
  full: { type: "boolean", description: "show every row" }
741
913
  };
742
914
  }
@@ -754,8 +926,6 @@ function capped(rows, limit) {
754
926
  const more = rows.length - limit;
755
927
  return more > 0 ? { shown: rows.slice(0, limit), footer: moreFooter(more) } : { shown: [...rows], footer: undefined };
756
928
  }
757
- // ../kit/src/logs.ts
758
- var DAY_MS = 24 * 60 * 60 * 1000;
759
929
  // ../kit/src/secrets.ts
760
930
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
761
931
  // ../kit/src/sessions.ts
@@ -763,11 +933,11 @@ var {Glob } = globalThis.Bun;
763
933
  var SESSION_FILES = new Glob("*.json");
764
934
  var ACCOUNT_DIRS = new Glob("*/sessions");
765
935
  // package.json
766
- var version = "0.5.0";
936
+ var version = "0.6.1";
767
937
 
768
938
  // src/files.ts
769
939
  import { existsSync, readdirSync, statSync } from "fs";
770
- import { join, relative } from "path";
940
+ import { join as join2, relative } from "path";
771
941
  var MAX_BYTES = 2000000;
772
942
  var SNIFF_BYTES = 8000;
773
943
  var SKIPPED = new Set(["node_modules", "dist", "build", "vendor", "target", "coverage"]);
@@ -782,17 +952,17 @@ function walk(dir, found) {
782
952
  if (entry.name.startsWith(".") || SKIPPED.has(entry.name))
783
953
  continue;
784
954
  if (entry.isDirectory())
785
- walk(join(dir, entry.name), found);
955
+ walk(join2(dir, entry.name), found);
786
956
  else if (entry.isFile())
787
- found.push(join(dir, entry.name));
957
+ found.push(join2(dir, entry.name));
788
958
  }
789
959
  return found;
790
960
  }
791
961
  async function listFiles(paths, cwd) {
792
962
  const listed = await runCommand(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...paths], { cwd });
793
963
  if (listed.code === 0)
794
- return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync(join(cwd, path))).sort();
795
- const roots = paths.length === 0 ? [cwd] : paths.map((path) => join(cwd, path));
964
+ return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync(join2(cwd, path))).sort();
965
+ const roots = paths.length === 0 ? [cwd] : paths.map((path) => join2(cwd, path));
796
966
  return roots.flatMap((root) => statSync(root, { throwIfNoEntry: false })?.isFile() === true ? [root] : walk(root, [])).map((path) => relative(cwd, path)).sort();
797
967
  }
798
968
  async function readText(path) {
@@ -1010,18 +1180,18 @@ function cut(text) {
1010
1180
  return text.length > LONGEST_LINE ? `${text.slice(0, LONGEST_LINE - 1)}\u2026` : text;
1011
1181
  }
1012
1182
  async function readableRoot() {
1013
- const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process7.cwd() });
1014
- return realpathSync(ran.code === 0 ? ran.text.trim() : process7.cwd());
1183
+ const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process9.cwd() });
1184
+ return realpathSync(ran.code === 0 ? ran.text.trim() : process9.cwd());
1015
1185
  }
1016
1186
  async function isOutside(path) {
1017
1187
  let real;
1018
1188
  try {
1019
- real = realpathSync(resolve(process7.cwd(), path));
1189
+ real = realpathSync(resolve(process9.cwd(), path));
1020
1190
  } catch {
1021
1191
  return false;
1022
1192
  }
1023
1193
  const inRoot = relative2(await readableRoot(), real);
1024
- return inRoot === ".." || inRoot.startsWith(PARENT) || isAbsolute(inRoot);
1194
+ return inRoot === ".." || inRoot.startsWith(PARENT) || isAbsolute2(inRoot);
1025
1195
  }
1026
1196
  async function checkInside(path) {
1027
1197
  if (await isOutside(path))
@@ -1030,7 +1200,7 @@ async function checkInside(path) {
1030
1200
  async function pipedSpans(text, context) {
1031
1201
  const spans = [];
1032
1202
  for (const [path, numbers] of locations(text)) {
1033
- const source = await isOutside(path) ? undefined : await readText(resolve(process7.cwd(), path));
1203
+ const source = await isOutside(path) ? undefined : await readText(resolve(process9.cwd(), path));
1034
1204
  if (source !== undefined)
1035
1205
  spans.push(...spansAround(path, source.replace(TRAILING_NEWLINE2, "").split(`
1036
1206
  `).length, numbers, context));
@@ -1039,7 +1209,7 @@ async function pipedSpans(text, context) {
1039
1209
  }
1040
1210
  async function textOf(path) {
1041
1211
  await checkInside(path);
1042
- const text = await readText(resolve(process7.cwd(), path));
1212
+ const text = await readText(resolve(process9.cwd(), path));
1043
1213
  if (text === undefined)
1044
1214
  fail(`cannot read ${path} (missing, binary or too large)`, 1);
1045
1215
  return text;
@@ -1088,8 +1258,8 @@ async function spanOf(target) {
1088
1258
  async function* sources(paths) {
1089
1259
  for (const path of paths)
1090
1260
  await checkInside(path);
1091
- for (const path of await listFiles(paths, process7.cwd())) {
1092
- const text = await readText(join2(process7.cwd(), path));
1261
+ for (const path of await listFiles(paths, process9.cwd())) {
1262
+ const text = await readText(join3(process9.cwd(), path));
1093
1263
  if (text !== undefined)
1094
1264
  yield { path, text };
1095
1265
  }
@@ -1173,4 +1343,4 @@ async function main(args) {
1173
1343
  await printSpans(await Promise.all(positionals.map(spanOf)), json);
1174
1344
  return 0;
1175
1345
  }
1176
- process7.exitCode = await runMain({ name: "peek", version, run: main });
1346
+ process9.exitCode = await runMain({ name: "peek", version, run: main });