@kaynooo/cli-base 0.4.0 → 0.5.0

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 (4) hide show
  1. package/README.md +5 -3
  2. package/dist/cli.js +337 -116
  3. package/dist/proof.js +367 -134
  4. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -2,16 +2,15 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process7 from "process";
6
-
5
+ import process10 from "process";
7
6
  // ../kit/src/args.ts
8
- import process2 from "process";
7
+ import process4 from "process";
9
8
  import { parseArgs } from "util";
10
9
 
11
10
  // ../kit/src/style.ts
12
- import process from "process";
11
+ import process2 from "process";
13
12
 
14
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
13
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
15
14
  function x(s) {
16
15
  let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
17
16
  if (!/^[a-f0-9]+$/.test(r))
@@ -231,7 +230,7 @@ class e {
231
230
  }
232
231
  }
233
232
 
234
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
233
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
235
234
  var r = 39;
236
235
  var o = 49;
237
236
  var f2 = "\x1B[";
@@ -273,10 +272,10 @@ function le(i = {}) {
273
272
  var t = le();
274
273
 
275
274
  // ../kit/src/style.ts
276
- function takesControlCodes(stream, env = process.env) {
275
+ function takesControlCodes(stream, env = process2.env) {
277
276
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
278
277
  }
279
- function paint(stream, env = process.env) {
278
+ function paint(stream, env = process2.env) {
280
279
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
281
280
  }
282
281
  var STATUSES = {
@@ -298,6 +297,63 @@ function printJson(value) {
298
297
  console.log(JSON.stringify(value, undefined, 2));
299
298
  }
300
299
 
300
+ // ../kit/src/help.ts
301
+ import process3 from "process";
302
+ var OPTIONAL = /\[[^\]]+\]/g;
303
+ var USAGE_PREFIX = /^usage:\s*/i;
304
+ var FULL_STOP = /\.$/;
305
+ function usageLine(usage, colors = paint(process3.stdout)) {
306
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
307
+ }
308
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces, exits = [] } = {}) {
309
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
310
+ `);
311
+ }
312
+ function exitRows(exits, colors = paint(process3.stdout)) {
313
+ if (exits.length === 0)
314
+ return [];
315
+ const width = Math.max(...exits.map(([code]) => String(code).length));
316
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
317
+ }
318
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
319
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
320
+ }
321
+ function wantsHelpJson(env = process3.env) {
322
+ return env.KIT_HELP === "json";
323
+ }
324
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
325
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
326
+ `);
327
+ const first = lines[0];
328
+ const colon = first.indexOf(": ");
329
+ const prose = lines[lines.indexOf("") + 1] ?? "";
330
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
331
+ return {
332
+ synopsis: colon === -1 ? first : first.slice(0, colon),
333
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
334
+ ...replaces === undefined ? {} : { replaces },
335
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
336
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
337
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
338
+ };
339
+ }
340
+ function exampleRows(examples, colors = paint(process3.stdout)) {
341
+ if (examples.length === 0)
342
+ return [];
343
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
344
+ }
345
+ function optionRows(options, colors = paint(process3.stdout)) {
346
+ const rows = Object.entries(options).map(([name, option]) => {
347
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
348
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
349
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
350
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
351
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
352
+ });
353
+ const width = Math.max(0, ...rows.map((row) => row.width));
354
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
355
+ }
356
+
301
357
  // ../kit/src/text.ts
302
358
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
303
359
  function distance(a, b) {
@@ -317,8 +373,19 @@ function closest(name, names) {
317
373
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
318
374
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
319
375
  }
376
+ // ../kit/src/input.ts
377
+ var WHOLE = /^\d+$/;
378
+ function wholeNumber(value, name, fallback, min = 1) {
379
+ if (value === undefined)
380
+ return fallback;
381
+ const number = Number(value);
382
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
383
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
384
+ return number;
385
+ }
320
386
 
321
387
  // ../kit/src/args.ts
388
+ var DASHES = /^-+/;
322
389
  function jsonOption(holds) {
323
390
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
324
391
  }
@@ -353,61 +420,20 @@ class HelpShown extends Exit {
353
420
 
354
421
  class Completing {
355
422
  options;
356
- constructor(options) {
423
+ positionals;
424
+ candidates;
425
+ constructor(options, positionals = [], candidates = {}) {
357
426
  this.options = options;
427
+ this.positionals = positionals;
428
+ this.candidates = candidates;
358
429
  }
359
430
  }
360
431
  var completion = { active: false };
361
- var OPTIONAL = /\[[^\]]+\]/g;
362
- var USAGE_PREFIX = /^usage:\s*/i;
363
- var FULL_STOP = /\.$/;
364
- var DASHES = /^-+/;
365
- function usageLine(usage, colors = paint(process2.stdout)) {
366
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
367
- }
368
- function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
369
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
370
- `);
371
- }
372
- function replacesRows(replaces, colors = paint(process2.stdout)) {
373
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
374
- }
375
- function wantsHelpJson(env = process2.env) {
376
- return env.KIT_HELP === "json";
377
- }
378
- function description(usage, { examples = [], replaces } = {}) {
379
- const lines = usage.replace(USAGE_PREFIX, "").split(`
380
- `);
381
- const first = lines[0];
382
- const colon = first.indexOf(": ");
383
- const prose = lines[lines.indexOf("") + 1] ?? "";
384
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
385
- return {
386
- synopsis: colon === -1 ? first : first.slice(0, colon),
387
- summary: colon === -1 ? fallback : first.slice(colon + 2),
388
- ...replaces === undefined ? {} : { replaces },
389
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
390
- };
391
- }
392
- function exampleRows(examples, colors = paint(process2.stdout)) {
393
- if (examples.length === 0)
394
- return [];
395
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
396
- }
397
- function optionRows(options, colors = paint(process2.stdout)) {
398
- const rows = Object.entries(options).map(([name, option]) => {
399
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
400
- const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
401
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
402
- });
403
- const width = Math.max(0, ...rows.map((row) => row.width));
404
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
405
- }
406
432
  var OUTPUT_OPTIONS = {
407
433
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
408
434
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
409
435
  };
410
- function applyOutput(color, plain, env = process2.env) {
436
+ function applyOutput(color, plain, env = process4.env) {
411
437
  const when = plain === true ? "never" : color ?? "auto";
412
438
  if (when === "auto")
413
439
  return;
@@ -424,14 +450,13 @@ function applyOutput(color, plain, env = process2.env) {
424
450
  function parse(args, usage, options, settings = {}) {
425
451
  const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
426
452
  const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
453
+ const listing = listed(all, settings.allowNegative === true);
427
454
  if (completion.active)
428
- throw new Completing(all);
429
- const separator = settings.rest === true ? args.indexOf("--") : -1;
430
- const own = separator === -1 ? args : args.slice(0, separator);
431
- const rest = separator === -1 ? undefined : args.slice(separator + 1);
455
+ throw new Completing(listing, settings.positionals, settings.candidates);
456
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
432
457
  let parsed;
433
458
  try {
434
- parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
459
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
435
460
  } catch (error) {
436
461
  const message = parseError(error);
437
462
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -439,12 +464,96 @@ function parse(args, usage, options, settings = {}) {
439
464
  const values = parsed.values;
440
465
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
441
466
  if (values.help === true) {
442
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
467
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
443
468
  throw new HelpShown;
444
469
  }
470
+ checkChoices(parsed.values, all);
471
+ checkConflicts(parsed.values, all);
445
472
  if (settings.positionals !== undefined)
446
473
  checkPositionals(parsed.positionals, settings.positionals);
447
- return { ...parsed, positionals: parsed.positionals, rest };
474
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
475
+ }
476
+ function splitRest(args, passes) {
477
+ const separator = passes ? args.indexOf("--") : -1;
478
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
479
+ }
480
+ function splitTrailing(args, options, count) {
481
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
482
+ let seen = 0;
483
+ if (count === 0)
484
+ return { own: args, rest: undefined };
485
+ for (let at = 0;at < args.length; at++) {
486
+ const word = args[at];
487
+ if (word === "--")
488
+ break;
489
+ if (word.startsWith("-")) {
490
+ if (takesValue(word))
491
+ at++;
492
+ continue;
493
+ }
494
+ seen++;
495
+ if (seen === count)
496
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
497
+ }
498
+ return { own: args, rest: undefined };
499
+ }
500
+ function listed(options, allowNegative) {
501
+ if (!allowNegative)
502
+ return options;
503
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
504
+ if (option.type !== "boolean" || option.negative === undefined)
505
+ return [[name, option]];
506
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
507
+ }));
508
+ }
509
+ function withAliases(args, options) {
510
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
511
+ if (named.size === 0)
512
+ return args;
513
+ const separator = args.indexOf("--");
514
+ const own = separator === -1 ? args : args.slice(0, separator);
515
+ return [...own.map((arg) => {
516
+ const at = arg.indexOf("=");
517
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
518
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
519
+ }), ...separator === -1 ? [] : args.slice(separator)];
520
+ }
521
+ function withBare(args, options) {
522
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
523
+ if (bare.size === 0)
524
+ return args;
525
+ const separator = args.indexOf("--");
526
+ const own = separator === -1 ? args : args.slice(0, separator);
527
+ return [...own.flatMap((arg, index) => {
528
+ const optional = bare.get(arg);
529
+ const next = own[index + 1];
530
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
531
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
532
+ }), ...separator === -1 ? [] : args.slice(separator)];
533
+ }
534
+ function checkConflicts(values, options) {
535
+ const given = (name) => values[name] !== undefined && values[name] !== false;
536
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
537
+ const other = given(name) ? conflicts.find(given) : undefined;
538
+ if (other !== undefined)
539
+ badUsage(`--${name} cannot be used with --${other}`);
540
+ }
541
+ }
542
+ function checkChoices(values, options) {
543
+ for (const [name, option] of Object.entries(options)) {
544
+ if (option.choices === undefined)
545
+ continue;
546
+ const given = values[name];
547
+ for (const value of Array.isArray(given) ? given : [given]) {
548
+ if (typeof value === "string")
549
+ oneOf(value, name, option.choices);
550
+ }
551
+ }
552
+ }
553
+ function oneOf(value, name, choices) {
554
+ if (!choices.includes(value))
555
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
556
+ return value;
448
557
  }
449
558
  function checkPositionals(given, names) {
450
559
  const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
@@ -495,7 +604,7 @@ function nearestOption(message, options, allowNegative) {
495
604
  }
496
605
  // ../kit/src/process.ts
497
606
  import { constants } from "os";
498
- import process3 from "process";
607
+ import process5 from "process";
499
608
  var KILL_GRACE_MS = 2000;
500
609
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
501
610
  function exitCodeOf(code, signal) {
@@ -517,7 +626,7 @@ function holdSignals(cleanup) {
517
626
  },
518
627
  release: () => {
519
628
  for (const signal of SIGNALS)
520
- process3.off(signal, onSignal);
629
+ process5.off(signal, onSignal);
521
630
  }
522
631
  };
523
632
  function onSignal(signal) {
@@ -530,10 +639,10 @@ function holdSignals(cleanup) {
530
639
  return;
531
640
  held.release();
532
641
  cleanup(signal);
533
- process3.kill(process3.pid, signal);
642
+ process5.kill(process5.pid, signal);
534
643
  }
535
644
  for (const signal of SIGNALS)
536
- process3.on(signal, onSignal);
645
+ process5.on(signal, onSignal);
537
646
  return held;
538
647
  }
539
648
  async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
@@ -547,7 +656,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
547
656
  return;
548
657
  try {
549
658
  if (grouped)
550
- process3.kill(-proc.pid, killing);
659
+ process5.kill(-proc.pid, killing);
551
660
  else
552
661
  proc.kill(killing);
553
662
  } catch {}
@@ -621,15 +730,69 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
621
730
  var RESET_STYLE = `${ESC}[0m`;
622
731
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
623
732
  // ../kit/src/cli.ts
624
- import process4 from "process";
733
+ import { readFileSync, realpathSync } from "fs";
734
+ import { dirname as dirname2, join as join2 } from "path";
735
+ import process7 from "process";
736
+
737
+ // ../kit/src/usage.ts
738
+ import { appendFileSync, mkdirSync } from "fs";
739
+ import { homedir } from "os";
740
+ import { dirname, isAbsolute, join } from "path";
741
+ import process6 from "process";
742
+
743
+ // ../kit/src/logs.ts
744
+ var DAY_MS = 24 * 60 * 60 * 1000;
745
+ var CLI_FOLDER = "kaynooo-cli";
746
+
747
+ // ../kit/src/usage.ts
748
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
749
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
750
+ var LONGEST_NAME = 40;
751
+ var usageError;
752
+ function noteUsageError(message) {
753
+ usageError = message;
754
+ }
755
+ function stateHome(env = process6.env) {
756
+ const dir = env.XDG_STATE_HOME;
757
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
758
+ }
759
+ function usagePath(env = process6.env) {
760
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
761
+ }
762
+ function usageRecorded(env = process6.env) {
763
+ const off = env.KAYNOOO_CLI_NO_USAGE;
764
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
765
+ }
766
+ function flagNames(argv) {
767
+ const end = argv.indexOf("--");
768
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
769
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
770
+ }
771
+ function usageEntry(bin, command, argv, code, now = new Date) {
772
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
773
+ usageError = undefined;
774
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
775
+ }
776
+ function recordUsage(entry, env = process6.env) {
777
+ if (!usageRecorded(env))
778
+ return;
779
+ try {
780
+ const path = usagePath(env);
781
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
782
+ appendFileSync(path, `${JSON.stringify(entry)}
783
+ `, { mode: 384 });
784
+ } catch {}
785
+ }
786
+
787
+ // ../kit/src/cli.ts
625
788
  var LEVEL_OPTIONS = {
626
789
  ...OUTPUT_OPTIONS,
627
790
  help: { type: "boolean", short: "h", description: "show this help" }
628
791
  };
629
792
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
630
793
  function printError(prefix, message, hint, cause) {
631
- const colors = paint(process4.stderr);
632
- const styled = takesControlCodes(process4.stderr);
794
+ const colors = paint(process7.stderr);
795
+ const styled = takesControlCodes(process7.stderr);
633
796
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
634
797
  const under = (label, text, tint) => text === undefined ? "" : `
635
798
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -648,63 +811,111 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
648
811
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
649
812
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
650
813
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
814
+ if (error instanceof UsageError)
815
+ noteUsageError(error.message);
651
816
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
652
817
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
653
818
  return error instanceof Exit ? error.code : 1;
654
819
  }
655
820
  var COMPLETE = "__complete";
656
821
  var FILES = "__files__";
657
- async function optionsOf(run) {
822
+ async function completingOf(run) {
658
823
  completion.active = true;
659
824
  try {
660
825
  await run([]);
661
826
  } catch (error) {
662
827
  if (error instanceof Completing)
663
- return error.options;
828
+ return error;
664
829
  } finally {
665
830
  completion.active = false;
666
831
  }
667
- return {};
832
+ return new Completing({});
833
+ }
834
+ function candidateLine(candidate) {
835
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
836
+ }
837
+ function positionalBeingTyped(before, { options, positionals }) {
838
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
839
+ let index = 0;
840
+ let at = 0;
841
+ while (at < before.length) {
842
+ const word = before[at];
843
+ if (word === "--") {
844
+ index += before.length - at - 1;
845
+ break;
846
+ }
847
+ if (!word.startsWith("-"))
848
+ index++;
849
+ else if (takesValue(word))
850
+ at++;
851
+ at++;
852
+ }
853
+ const last = positionals.at(-1);
854
+ if (index < positionals.length)
855
+ return positionals[index];
856
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
668
857
  }
669
858
  async function leafCandidates(run, words) {
670
- if (!(words.at(-1) ?? "").startsWith("-"))
671
- return [FILES];
672
- return Object.entries(await optionsOf(run)).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
859
+ const completing = await completingOf(run);
860
+ if ((words.at(-1) ?? "").startsWith("-"))
861
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
862
+ const flag = words.at(-2);
863
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
864
+ if (option?.type === "string") {
865
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
866
+ return values === undefined ? [FILES] : values.map(candidateLine);
867
+ }
868
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
869
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
870
+ return values === undefined ? [FILES] : values.map(candidateLine);
673
871
  }
674
872
  async function printCandidates(found) {
675
873
  for (const line of await found)
676
874
  console.log(line);
677
875
  return 0;
678
876
  }
679
- async function runMain({ name, version, run, redact }, argv = process4.argv.slice(2)) {
877
+ function packageVersion(entry = Bun.main) {
878
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
879
+ try {
880
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
881
+ if (typeof version === "string")
882
+ return version;
883
+ } catch {}
884
+ if (dirname2(dir) === dir)
885
+ return "0.0.0";
886
+ }
887
+ }
888
+ async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
680
889
  if (argv[0] === COMPLETE)
681
890
  return printCandidates(leafCandidates(run, argv.slice(1)));
682
891
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
683
- console.log(version);
892
+ console.log(version ?? packageVersion());
684
893
  return 0;
685
894
  }
895
+ let code;
686
896
  try {
687
- return await run(argv);
897
+ code = await run(argv);
688
898
  } catch (error) {
689
- return reportThrown(name, error, redact, wantsJson(argv));
899
+ code = reportThrown(name, error, redact, wantsJson(argv));
690
900
  }
901
+ if (usage !== false) {
902
+ try {
903
+ recordUsage(usageEntry(name, undefined, argv, code));
904
+ } catch {}
905
+ }
906
+ return code;
691
907
  }
692
- // ../kit/src/logs.ts
693
- var DAY_MS = 24 * 60 * 60 * 1000;
694
908
  // ../kit/src/secrets.ts
695
909
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
696
910
  // ../kit/src/sessions.ts
697
911
  var {Glob } = globalThis.Bun;
698
912
  var SESSION_FILES = new Glob("*.json");
699
913
  var ACCOUNT_DIRS = new Glob("*/sessions");
700
- // package.json
701
- var version = "0.4.0";
702
-
703
914
  // src/worktree.ts
704
- import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, symlinkSync, unlinkSync } from "fs";
915
+ import { cpSync, existsSync, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync2, rmSync, symlinkSync, unlinkSync } from "fs";
705
916
  import { tmpdir } from "os";
706
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "path";
707
- import process6 from "process";
917
+ import { basename, dirname as dirname3, isAbsolute as isAbsolute2, join as join3, relative, resolve, sep } from "path";
918
+ import process9 from "process";
708
919
  var WHITESPACE = /\s/;
709
920
  var ENV_FILE = /^\.env(?:\..+)?$/;
710
921
  var DEPENDENCIES = new Set(["node_modules", "vendor", ".venv"]);
@@ -735,12 +946,22 @@ async function resolveRef(root, ref) {
735
946
  fail(`no commit ${ref} in this repository`);
736
947
  return stdoutOf(ran);
737
948
  }
949
+ async function defaultProofRef(root) {
950
+ const branch = await git2(["symbolic-ref", "--quiet", "--short", "HEAD"], root);
951
+ if (branch.code !== 0 || stdoutOf(branch) === "main")
952
+ return "HEAD";
953
+ const base = await git2(["merge-base", "HEAD", "origin/main"], root);
954
+ const head = await git2(["rev-parse", "HEAD"], root);
955
+ return base.code === 0 && stdoutOf(base) !== stdoutOf(head) ? stdoutOf(base) : "HEAD";
956
+ }
738
957
  function keptPaths(root, cwd, paths) {
739
- const realRoot = realpathSync(root);
958
+ const realRoot = realpathSync2(root);
740
959
  return paths.map((path) => {
741
960
  const absolute = resolve(cwd, path);
742
- const inRepo = relative(realRoot, join(realpathSync(dirname(absolute)), basename(absolute)));
743
- if (inRepo === "" || inRepo === ".." || inRepo.startsWith(PARENT) || isAbsolute(inRepo))
961
+ if (!existsSync(dirname3(absolute)))
962
+ fail(`--keep ${path}: no such file`);
963
+ const inRepo = relative(realRoot, join3(realpathSync2(dirname3(absolute)), basename(absolute)));
964
+ if (inRepo === "" || inRepo === ".." || inRepo.startsWith(PARENT) || isAbsolute2(inRepo))
744
965
  fail(`--keep ${path} is outside the repository`);
745
966
  if (!existsSync(absolute))
746
967
  fail(`--keep ${path}: no such file`);
@@ -749,8 +970,8 @@ function keptPaths(root, cwd, paths) {
749
970
  }
750
971
  function checkNoSymlink(dir, path) {
751
972
  let current = dir;
752
- for (const part of dirname(path).split(sep)) {
753
- current = join(current, part);
973
+ for (const part of dirname3(path).split(sep)) {
974
+ current = join3(current, part);
754
975
  if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink() === true)
755
976
  fail(`--keep ${path} goes through the symlink ${relative(dir, current)} of the ref, which would write outside the worktree`);
756
977
  }
@@ -766,10 +987,10 @@ async function linkedEntries(root) {
766
987
  }).map((entry) => entry.replace(TRAILING_SLASH, ""));
767
988
  }
768
989
  async function addWorktree(root, sha) {
769
- const dir = join(mkdtempSync(join(tmpdir(), "base-")), basename(root));
990
+ const dir = join3(mkdtempSync(join3(tmpdir(), "base-")), basename(root));
770
991
  const ran = await git2(["worktree", "add", "--detach", dir, sha], root);
771
992
  if (ran.code !== 0) {
772
- rmSync(dirname(dir), { recursive: true, force: true });
993
+ rmSync(dirname3(dir), { recursive: true, force: true });
773
994
  fail(`git worktree add failed:
774
995
  ${ran.text.trim()}`);
775
996
  }
@@ -778,41 +999,41 @@ ${ran.text.trim()}`);
778
999
  function copyKept(root, dir, paths) {
779
1000
  for (const path of paths) {
780
1001
  checkNoSymlink(dir, path);
781
- const target = join(dir, path);
1002
+ const target = join3(dir, path);
782
1003
  rmSync(target, { recursive: true, force: true });
783
- mkdirSync(dirname(target), { recursive: true });
784
- cpSync(join(root, path), target, { recursive: true });
1004
+ mkdirSync2(dirname3(target), { recursive: true });
1005
+ cpSync(join3(root, path), target, { recursive: true });
785
1006
  }
786
1007
  }
787
1008
  function linkEntries(root, dir, entries) {
788
1009
  const links = [];
789
1010
  for (const entry of entries) {
790
- const link = join(dir, entry);
1011
+ const link = join3(dir, entry);
791
1012
  if (existsSync(link))
792
1013
  continue;
793
- mkdirSync(dirname(link), { recursive: true });
1014
+ mkdirSync2(dirname3(link), { recursive: true });
794
1015
  if (basename(entry) === "node_modules" && hasWorkspaceLinks(root, entry)) {
795
1016
  links.push(...linkModules(root, dir, entry));
796
1017
  continue;
797
1018
  }
798
- symlinkSync(join(root, entry), link);
1019
+ symlinkSync(join3(root, entry), link);
799
1020
  links.push(link);
800
1021
  }
801
1022
  return links;
802
1023
  }
803
1024
  function moduleLinks(root, folder) {
804
1025
  const found = [];
805
- for (const entry of readdirSync(join(root, folder), { withFileTypes: true })) {
1026
+ for (const entry of readdirSync(join3(root, folder), { withFileTypes: true })) {
806
1027
  if (entry.isSymbolicLink())
807
- found.push({ path: join(folder, entry.name), name: entry.name });
1028
+ found.push({ path: join3(folder, entry.name), name: entry.name });
808
1029
  else if (entry.isDirectory() && entry.name.startsWith("@"))
809
- found.push(...moduleLinks(root, join(folder, entry.name)));
1030
+ found.push(...moduleLinks(root, join3(folder, entry.name)));
810
1031
  }
811
1032
  return found;
812
1033
  }
813
1034
  function workspaceTarget(root, path) {
814
1035
  try {
815
- const inRepo = relative(realpathSync(root), realpathSync(join(root, path)));
1036
+ const inRepo = relative(realpathSync2(root), realpathSync2(join3(root, path)));
816
1037
  return inRepo === "" || inRepo.startsWith(PARENT) || inRepo.split(sep).includes("node_modules") ? undefined : inRepo;
817
1038
  } catch {
818
1039
  return;
@@ -823,16 +1044,16 @@ function hasWorkspaceLinks(root, folder) {
823
1044
  }
824
1045
  function linkModules(root, dir, folder) {
825
1046
  const links = [];
826
- mkdirSync(join(dir, folder), { recursive: true });
827
- for (const entry of readdirSync(join(root, folder), { withFileTypes: true })) {
828
- const path = join(folder, entry.name);
829
- const link = join(dir, path);
1047
+ mkdirSync2(join3(dir, folder), { recursive: true });
1048
+ for (const entry of readdirSync(join3(root, folder), { withFileTypes: true })) {
1049
+ const path = join3(folder, entry.name);
1050
+ const link = join3(dir, path);
830
1051
  if (entry.isDirectory() && entry.name.startsWith("@")) {
831
1052
  links.push(...linkModules(root, dir, path));
832
1053
  continue;
833
1054
  }
834
1055
  const workspace = entry.isSymbolicLink() ? workspaceTarget(root, path) : undefined;
835
- symlinkSync(workspace === undefined ? join(root, path) : join(dir, workspace), link);
1056
+ symlinkSync(workspace === undefined ? join3(root, path) : join3(dir, workspace), link);
836
1057
  links.push(link);
837
1058
  }
838
1059
  return links;
@@ -842,9 +1063,9 @@ async function sweepStale(root) {
842
1063
  for (const name of readdirSync(tmpdir())) {
843
1064
  if (!BASE_DIR.test(name))
844
1065
  continue;
845
- const path = join(tmpdir(), name);
1066
+ const path = join3(tmpdir(), name);
846
1067
  const stat = lstatSync(path, { throwIfNoEntry: false });
847
- if (stat?.isDirectory() === true && stat.uid === process6.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1068
+ if (stat?.isDirectory() === true && stat.uid === process9.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
848
1069
  rmSync(path, { recursive: true, force: true });
849
1070
  }
850
1071
  await git2(["worktree", "prune"], root);
@@ -855,7 +1076,7 @@ async function removeWorktree(root, dir, links) {
855
1076
  unlinkSync(link);
856
1077
  }
857
1078
  await git2(["worktree", "remove", "--force", dir], root);
858
- rmSync(dirname(dir), { recursive: true, force: true });
1079
+ rmSync(dirname3(dir), { recursive: true, force: true });
859
1080
  await git2(["worktree", "prune"], root);
860
1081
  }
861
1082
  function shellCommand(given) {
@@ -903,7 +1124,7 @@ async function inWorktree(options, body) {
903
1124
  try {
904
1125
  copyKept(root, dir, kept);
905
1126
  links = link ? linkEntries(root, dir, await linkedEntries(root)) : [];
906
- const runDir = join(dir, prefix);
1127
+ const runDir = join3(dir, prefix);
907
1128
  if (!existsSync(runDir))
908
1129
  fail(`${prefix} does not exist at ${ref}`);
909
1130
  return await body(runDir, signals);
@@ -934,7 +1155,7 @@ ${USAGE}`);
934
1155
  if (runsInContainer(given))
935
1156
  fail("a container of the compose project mounts the main checkout, not the temporary worktree, so the command would not run at the ref: run the tool on the host, or check the ref out by hand");
936
1157
  const command = shellCommand(given);
937
- const cwd = process7.cwd();
1158
+ const cwd = process10.cwd();
938
1159
  const { root, prefix } = await checkout(cwd);
939
1160
  const ref = parsed.values.ref ?? "HEAD";
940
1161
  const sha = await resolveRef(root, ref);
@@ -945,4 +1166,4 @@ ${USAGE}`);
945
1166
  console.error(`base: ran at ${ref} (${sha.slice(0, 7)}), exit ${ran.code}`);
946
1167
  return ran.code;
947
1168
  }
948
- process7.exitCode = await runMain({ name: "base", version, run: main });
1169
+ process10.exitCode = await runMain({ name: "base", run: main });