@kaynooo/cli-guard 0.7.0 → 0.7.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 (2) hide show
  1. package/dist/cli.js +168 -32
  2. package/package.json +6 -6
package/dist/cli.js CHANGED
@@ -14,7 +14,7 @@ import { parseArgs } from "util";
14
14
  // ../kit/src/style.ts
15
15
  import process2 from "process";
16
16
 
17
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
17
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
18
  function x(s) {
19
19
  let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
20
20
  if (!/^[a-f0-9]+$/.test(r))
@@ -234,7 +234,7 @@ class e {
234
234
  }
235
235
  }
236
236
 
237
- // ../../node_modules/.bun/@kaynooo+utils@2.31.0+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
237
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
238
238
  var r = 39;
239
239
  var o = 49;
240
240
  var f2 = "\x1B[";
@@ -353,8 +353,12 @@ class HelpShown extends Exit {
353
353
 
354
354
  class Completing {
355
355
  options;
356
- constructor(options) {
356
+ positionals;
357
+ candidates;
358
+ constructor(options, positionals = [], candidates = {}) {
357
359
  this.options = options;
360
+ this.positionals = positionals;
361
+ this.candidates = candidates;
358
362
  }
359
363
  }
360
364
  var completion = { active: false };
@@ -397,8 +401,10 @@ function exampleRows(examples, colors = paint(process3.stdout)) {
397
401
  function optionRows(options, colors = paint(process3.stdout)) {
398
402
  const rows = Object.entries(options).map(([name, option]) => {
399
403
  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 ?? "" };
404
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
405
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
406
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
407
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
402
408
  });
403
409
  const width = Math.max(0, ...rows.map((row) => row.width));
404
410
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
@@ -424,14 +430,13 @@ function applyOutput(color, plain, env = process3.env) {
424
430
  function parse(args, usage, options, settings = {}) {
425
431
  const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
426
432
  const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
433
+ const listing = listed(all, settings.allowNegative === true);
427
434
  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);
435
+ throw new Completing(listing, settings.positionals, settings.candidates);
436
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
432
437
  let parsed;
433
438
  try {
434
- parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
439
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
435
440
  } catch (error) {
436
441
  const message = parseError(error);
437
442
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -439,12 +444,84 @@ function parse(args, usage, options, settings = {}) {
439
444
  const values = parsed.values;
440
445
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
441
446
  if (values.help === true) {
442
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
447
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
443
448
  throw new HelpShown;
444
449
  }
450
+ checkChoices(parsed.values, all);
451
+ checkConflicts(parsed.values, all);
445
452
  if (settings.positionals !== undefined)
446
453
  checkPositionals(parsed.positionals, settings.positionals);
447
- return { ...parsed, positionals: parsed.positionals, rest };
454
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
455
+ }
456
+ function splitRest(args, passes) {
457
+ const separator = passes ? args.indexOf("--") : -1;
458
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
459
+ }
460
+ function splitTrailing(args, options, count) {
461
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
462
+ let seen = 0;
463
+ if (count === 0)
464
+ return { own: args, rest: undefined };
465
+ for (let at = 0;at < args.length; at++) {
466
+ const word = args[at];
467
+ if (word === "--")
468
+ break;
469
+ if (word.startsWith("-")) {
470
+ if (takesValue(word))
471
+ at++;
472
+ continue;
473
+ }
474
+ seen++;
475
+ if (seen === count)
476
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
477
+ }
478
+ return { own: args, rest: undefined };
479
+ }
480
+ function listed(options, allowNegative) {
481
+ if (!allowNegative)
482
+ return options;
483
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
484
+ if (option.type !== "boolean" || option.negative === undefined)
485
+ return [[name, option]];
486
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
487
+ }));
488
+ }
489
+ function withBare(args, options) {
490
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
491
+ if (bare.size === 0)
492
+ return args;
493
+ const separator = args.indexOf("--");
494
+ const own = separator === -1 ? args : args.slice(0, separator);
495
+ return [...own.flatMap((arg, index) => {
496
+ const optional = bare.get(arg);
497
+ const next = own[index + 1];
498
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
499
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
500
+ }), ...separator === -1 ? [] : args.slice(separator)];
501
+ }
502
+ function checkConflicts(values, options) {
503
+ const given = (name) => values[name] !== undefined && values[name] !== false;
504
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
505
+ const other = given(name) ? conflicts.find(given) : undefined;
506
+ if (other !== undefined)
507
+ badUsage(`--${name} cannot be used with --${other}`);
508
+ }
509
+ }
510
+ function checkChoices(values, options) {
511
+ for (const [name, option] of Object.entries(options)) {
512
+ if (option.choices === undefined)
513
+ continue;
514
+ const given = values[name];
515
+ for (const value of Array.isArray(given) ? given : [given]) {
516
+ if (typeof value === "string")
517
+ oneOf(value, name, option.choices);
518
+ }
519
+ }
520
+ }
521
+ function oneOf(value, name, choices) {
522
+ if (!choices.includes(value))
523
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
524
+ return value;
448
525
  }
449
526
  function checkPositionals(given, names) {
450
527
  const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
@@ -606,8 +683,9 @@ var LEVEL_OPTIONS = {
606
683
  help: { type: "boolean", short: "h", description: "show this help" }
607
684
  };
608
685
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
609
- async function commandRows(commands, colors) {
610
- const width = Math.max(...Object.keys(commands).map((name) => name.length));
686
+ async function commandRows(all, colors) {
687
+ const commands = shown(all);
688
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
611
689
  const groups = new Map([["Commands:", []]]);
612
690
  const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
613
691
  for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
@@ -618,6 +696,9 @@ async function commandRows(commands, colors) {
618
696
  }
619
697
  return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
620
698
  }
699
+ function shown(commands) {
700
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
701
+ }
621
702
  function takeOutputFlags(argv) {
622
703
  let index = 0;
623
704
  for (;index < argv.length; index++) {
@@ -709,6 +790,14 @@ async function dispatch(level, typed, { version, redact }) {
709
790
  return reportThrown(prefix, error);
710
791
  }
711
792
  const [name, ...args] = argv;
793
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
794
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
795
+ try {
796
+ return await fallback.run([]);
797
+ } catch (error) {
798
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
799
+ }
800
+ }
712
801
  if (name === undefined && level.path.length > 1) {
713
802
  console.error(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stderr));
714
803
  return 2;
@@ -723,6 +812,7 @@ async function dispatch(level, typed, { version, redact }) {
723
812
  }
724
813
  let command = level.commands[level.aliases?.[name] ?? name];
725
814
  let rest = args;
815
+ let ran = name;
726
816
  if (command === undefined && level.lazy.length > 0) {
727
817
  level = await expand(level, [...level.path.slice(1), ...argv]);
728
818
  command = level.commands[level.aliases?.[name] ?? name];
@@ -730,40 +820,77 @@ async function dispatch(level, typed, { version, redact }) {
730
820
  if (command === undefined && level.defaultCommand !== undefined) {
731
821
  command = level.commands[level.defaultCommand];
732
822
  rest = argv;
823
+ ran = level.defaultCommand;
733
824
  }
734
825
  if (command === undefined) {
735
- const meant = closest(name, Object.keys(level.commands));
826
+ const meant = closest(name, Object.keys(shown(level.commands)));
736
827
  printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
737
828
  return 2;
738
829
  }
739
830
  if ("commands" in command) {
740
831
  const { summary } = command;
741
- return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, examples: command.examples, replaces: undefined }, rest, { version, redact });
832
+ return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
742
833
  }
743
834
  try {
744
835
  return await command.run(rest);
745
836
  } catch (error) {
746
- return reportThrown(`${prefix} ${name}`, error, redact, wantsJson(rest));
837
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
747
838
  }
748
839
  }
749
840
  var COMPLETE = "__complete";
750
841
  var FILES = "__files__";
751
- async function optionsOf(run) {
842
+ async function completingOf(run) {
752
843
  completion.active = true;
753
844
  try {
754
845
  await run([]);
755
846
  } catch (error) {
756
847
  if (error instanceof Completing)
757
- return error.options;
848
+ return error;
758
849
  } finally {
759
850
  completion.active = false;
760
851
  }
761
- return {};
852
+ return new Completing({});
853
+ }
854
+ async function optionsOf(run) {
855
+ return (await completingOf(run)).options;
856
+ }
857
+ function candidateLine(candidate) {
858
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
859
+ }
860
+ function positionalBeingTyped(before, { options, positionals }) {
861
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
862
+ let index = 0;
863
+ let at = 0;
864
+ while (at < before.length) {
865
+ const word = before[at];
866
+ if (word === "--") {
867
+ index += before.length - at - 1;
868
+ break;
869
+ }
870
+ if (!word.startsWith("-"))
871
+ index++;
872
+ else if (takesValue(word))
873
+ at++;
874
+ at++;
875
+ }
876
+ const last = positionals.at(-1);
877
+ if (index < positionals.length)
878
+ return positionals[index];
879
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
762
880
  }
763
881
  async function leafCandidates(run, words) {
764
- if (!(words.at(-1) ?? "").startsWith("-"))
765
- return [FILES];
766
- return Object.entries(await optionsOf(run)).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
882
+ const completing = await completingOf(run);
883
+ if ((words.at(-1) ?? "").startsWith("-"))
884
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
885
+ const flag = words.at(-2);
886
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
887
+ if (option?.type === "string") {
888
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
889
+ return values === undefined ? [FILES] : values.map(candidateLine);
890
+ }
891
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
892
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
893
+ return values === undefined ? [FILES] : values.map(candidateLine);
767
894
  }
768
895
  async function candidates(scope, defaultCommand, words, before = []) {
769
896
  const [word = "", ...rest] = words;
@@ -774,8 +901,13 @@ async function candidates(scope, defaultCommand, words, before = []) {
774
901
  ({ commands, aliases } = await expand(scope, [...before, ...words]));
775
902
  command = commands[aliases?.[word] ?? word];
776
903
  }
777
- if (listing)
778
- return Promise.all(Object.entries(commands).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
904
+ if (listing) {
905
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
906
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
907
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
908
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
909
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
910
+ }
779
911
  if (command === undefined) {
780
912
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
781
913
  return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
@@ -790,7 +922,7 @@ async function printCandidates(found) {
790
922
  async function runCli(cli, argv = process5.argv.slice(2)) {
791
923
  if (argv[0] === COMPLETE)
792
924
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
793
- return dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, examples: cli.examples, replaces: cli.replaces }, argv, { version: cli.version, redact: cli.redact });
925
+ return dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version: cli.version, redact: cli.redact });
794
926
  }
795
927
  // ../kit/src/logs.ts
796
928
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -801,7 +933,7 @@ var {Glob } = globalThis.Bun;
801
933
  var SESSION_FILES = new Glob("*.json");
802
934
  var ACCOUNT_DIRS = new Glob("*/sessions");
803
935
  // package.json
804
- var version = "0.7.0";
936
+ var version = "0.7.1";
805
937
 
806
938
  // ../kit/src/shell.ts
807
939
  var SEPARATORS = new Set([`
@@ -927,6 +1059,10 @@ function splitCommand(command) {
927
1059
  quote = char;
928
1060
  continue;
929
1061
  }
1062
+ if (char === "`") {
1063
+ i = closingBackquote(command, i);
1064
+ continue;
1065
+ }
930
1066
  if (char === "#" && startsComment(command, i)) {
931
1067
  const newline = command.indexOf(`
932
1068
  `, i);
@@ -2187,7 +2323,7 @@ var RULES = {
2187
2323
  pest: always,
2188
2324
  "php-cs-fixer": always,
2189
2325
  rector: always,
2190
- php: (args) => listed(afterOptions(args, PHP_VALUE_OPTIONS)),
2326
+ php: (args) => listed2(afterOptions(args, PHP_VALUE_OPTIONS)),
2191
2327
  make: ([first]) => first === undefined || !LONG_RUNNING.test(first),
2192
2328
  check: always,
2193
2329
  just: ([first]) => first !== undefined && !first.startsWith("-") && !LONG_RUNNING.test(first),
@@ -2199,12 +2335,12 @@ var RULES = {
2199
2335
  if (args[0] === "build")
2200
2336
  return true;
2201
2337
  if (args[0] === "exec")
2202
- return listed(afterOptions(args.slice(1), EXEC_VALUE_OPTIONS2).slice(1));
2338
+ return listed2(afterOptions(args.slice(1), EXEC_VALUE_OPTIONS2).slice(1));
2203
2339
  if (args[0] !== "compose")
2204
2340
  return false;
2205
2341
  const [sub, ...rest] = afterOptions(args.slice(1), COMPOSE_VALUE_OPTIONS);
2206
2342
  if (sub === "exec" || sub === "run")
2207
- return listed(afterOptions(rest, EXEC_VALUE_OPTIONS2).slice(1));
2343
+ return listed2(afterOptions(rest, EXEC_VALUE_OPTIONS2).slice(1));
2208
2344
  return sub === "build" || sub === "pull";
2209
2345
  }
2210
2346
  };
@@ -2249,7 +2385,7 @@ function withoutFilters(command) {
2249
2385
  }
2250
2386
  return { rest, stages };
2251
2387
  }
2252
- function listed(words) {
2388
+ function listed2(words) {
2253
2389
  const start = words.findIndex((word) => !ASSIGNMENT3.test(word));
2254
2390
  const path = words[start];
2255
2391
  if (path === undefined)
@@ -2257,7 +2393,7 @@ function listed(words) {
2257
2393
  return RULES[path.slice(path.lastIndexOf("/") + 1)]?.(words.slice(start + 1)) ?? false;
2258
2394
  }
2259
2395
  function listedSegment(segment) {
2260
- return !EXCLUDED.test(segment) && !SHORT_WATCH.test(segment) && listed(tokenize(segment));
2396
+ return !EXCLUDED.test(segment) && !SHORT_WATCH.test(segment) && listed2(tokenize(segment));
2261
2397
  }
2262
2398
  function isCd(segment) {
2263
2399
  return segment === "cd" || segment.startsWith("cd ");
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-guard",
3
3
  "type": "module",
4
- "version": "0.7.0",
4
+ "version": "0.7.1",
5
5
  "description": "guard: the safety rules a Claude Code Bash call is held to (git, remote machines, SQL writes, env files, package managers, commit messages), each refusal naming the route.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -36,12 +36,12 @@
36
36
  "guard": "$npm_execpath src/cli.ts"
37
37
  },
38
38
  "devDependencies": {
39
- "@kaynooo/cli-db": "0.8.0",
39
+ "@kaynooo/cli-db": "0.9.0",
40
40
  "@kaynooo/cli-edit": "0.4.0",
41
41
  "@kaynooo/cli-env": "0.8.0",
42
- "@kaynooo/cli-git": "0.5.0",
43
- "@kaynooo/cli-kit": "0.15.0",
44
- "@kaynooo/cli-out": "0.5.0",
45
- "@kaynooo/cli-pkg": "0.6.0"
42
+ "@kaynooo/cli-git": "0.5.1",
43
+ "@kaynooo/cli-kit": "0.19.0",
44
+ "@kaynooo/cli-out": "0.7.0",
45
+ "@kaynooo/cli-pkg": "0.7.0"
46
46
  }
47
47
  }