@kaynooo/cli-guard 0.7.2 → 0.9.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 (3) hide show
  1. package/README.md +3 -0
  2. package/dist/cli.js +741 -317
  3. package/package.json +8 -8
package/dist/cli.js CHANGED
@@ -2,13 +2,12 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "fs";
6
- import { homedir } from "os";
7
- import { dirname } from "path";
8
- import process7 from "process";
9
-
5
+ import { appendFileSync as appendFileSync2, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, rmSync, statSync, writeFileSync } from "fs";
6
+ import { homedir as homedir2 } from "os";
7
+ import { dirname as dirname4 } from "path";
8
+ import process11 from "process";
10
9
  // ../kit/src/args.ts
11
- import process3 from "process";
10
+ import process5 from "process";
12
11
  import { parseArgs } from "util";
13
12
 
14
13
  // ../kit/src/style.ts
@@ -298,6 +297,63 @@ function upTo(text, separator) {
298
297
  }
299
298
  var ESCAPE = String.fromCharCode(27);
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,22 @@ 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
+ import process4 from "process";
378
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
379
+ if (path === "-") {
380
+ if (process4.stdin.isTTY)
381
+ fail(noStdin);
382
+ return Bun.stdin.text();
383
+ }
384
+ const file = Bun.file(path);
385
+ if (!await file.exists())
386
+ fail(`no file ${path}`);
387
+ return file.text();
388
+ }
320
389
 
321
390
  // ../kit/src/args.ts
391
+ var DASHES = /^-+/;
322
392
  function jsonOption(holds) {
323
393
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
324
394
  }
@@ -362,58 +432,11 @@ class Completing {
362
432
  }
363
433
  }
364
434
  var completion = { active: false };
365
- var OPTIONAL = /\[[^\]]+\]/g;
366
- var USAGE_PREFIX = /^usage:\s*/i;
367
- var FULL_STOP = /\.$/;
368
- var DASHES = /^-+/;
369
- function usageLine(usage, colors = paint(process3.stdout)) {
370
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
371
- }
372
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
373
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
374
- `);
375
- }
376
- function replacesRows(replaces, colors = paint(process3.stdout)) {
377
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
378
- }
379
- function wantsHelpJson(env = process3.env) {
380
- return env.KIT_HELP === "json";
381
- }
382
- function description(usage, { examples = [], replaces } = {}) {
383
- const lines = usage.replace(USAGE_PREFIX, "").split(`
384
- `);
385
- const first = lines[0];
386
- const colon = first.indexOf(": ");
387
- const prose = lines[lines.indexOf("") + 1] ?? "";
388
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
389
- return {
390
- synopsis: colon === -1 ? first : first.slice(0, colon),
391
- summary: colon === -1 ? fallback : first.slice(colon + 2),
392
- ...replaces === undefined ? {} : { replaces },
393
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
394
- };
395
- }
396
- function exampleRows(examples, colors = paint(process3.stdout)) {
397
- if (examples.length === 0)
398
- return [];
399
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
400
- }
401
- function optionRows(options, colors = paint(process3.stdout)) {
402
- const rows = Object.entries(options).map(([name, option]) => {
403
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
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 ?? "" };
408
- });
409
- const width = Math.max(0, ...rows.map((row) => row.width));
410
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
411
- }
412
435
  var OUTPUT_OPTIONS = {
413
436
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
414
437
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
415
438
  };
416
- function applyOutput(color, plain, env = process3.env) {
439
+ function applyOutput(color, plain, env = process5.env) {
417
440
  const when = plain === true ? "never" : color ?? "auto";
418
441
  if (when === "auto")
419
442
  return;
@@ -436,7 +459,7 @@ function parse(args, usage, options, settings = {}) {
436
459
  const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
437
460
  let parsed;
438
461
  try {
439
- parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
462
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
440
463
  } catch (error) {
441
464
  const message = parseError(error);
442
465
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -444,7 +467,7 @@ function parse(args, usage, options, settings = {}) {
444
467
  const values = parsed.values;
445
468
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
446
469
  if (values.help === true) {
447
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
470
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
448
471
  throw new HelpShown;
449
472
  }
450
473
  checkChoices(parsed.values, all);
@@ -486,6 +509,18 @@ function listed(options, allowNegative) {
486
509
  return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
487
510
  }));
488
511
  }
512
+ function withAliases(args, options) {
513
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
514
+ if (named.size === 0)
515
+ return args;
516
+ const separator = args.indexOf("--");
517
+ const own = separator === -1 ? args : args.slice(0, separator);
518
+ return [...own.map((arg) => {
519
+ const at = arg.indexOf("=");
520
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
521
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
522
+ }), ...separator === -1 ? [] : args.slice(separator)];
523
+ }
489
524
  function withBare(args, options) {
490
525
  const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
491
526
  if (bare.size === 0)
@@ -570,20 +605,9 @@ function nearestOption(message, options, allowNegative) {
570
605
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
571
606
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
572
607
  }
573
- async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
574
- if (path === "-") {
575
- if (process3.stdin.isTTY)
576
- fail(noStdin);
577
- return Bun.stdin.text();
578
- }
579
- const file = Bun.file(path);
580
- if (!await file.exists())
581
- fail(`no file ${path}`);
582
- return file.text();
583
- }
584
608
  // ../kit/src/process.ts
585
609
  import { constants } from "os";
586
- import process4 from "process";
610
+ import process6 from "process";
587
611
  var KILL_GRACE_MS = 2000;
588
612
  function exitCodeOf(code, signal) {
589
613
  if (code !== null)
@@ -603,7 +627,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
603
627
  return;
604
628
  try {
605
629
  if (grouped)
606
- process4.kill(-proc.pid, killing);
630
+ process6.kill(-proc.pid, killing);
607
631
  else
608
632
  proc.kill(killing);
609
633
  } catch {}
@@ -677,7 +701,61 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
677
701
  var RESET_STYLE = `${ESC}[0m`;
678
702
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
679
703
  // ../kit/src/cli.ts
680
- import process5 from "process";
704
+ import { readFileSync, realpathSync } from "fs";
705
+ import { dirname as dirname2, join as join2 } from "path";
706
+ import process8 from "process";
707
+
708
+ // ../kit/src/usage.ts
709
+ import { appendFileSync, mkdirSync } from "fs";
710
+ import { homedir } from "os";
711
+ import { dirname, isAbsolute, join } from "path";
712
+ import process7 from "process";
713
+
714
+ // ../kit/src/logs.ts
715
+ var DAY_MS = 24 * 60 * 60 * 1000;
716
+ var CLI_FOLDER = "kaynooo-cli";
717
+
718
+ // ../kit/src/usage.ts
719
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
720
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
721
+ var LONGEST_NAME = 40;
722
+ var usageError;
723
+ function noteUsageError(message) {
724
+ usageError = message;
725
+ }
726
+ function stateHome(env = process7.env) {
727
+ const dir = env.XDG_STATE_HOME;
728
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
729
+ }
730
+ function usagePath(env = process7.env) {
731
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
732
+ }
733
+ function usageRecorded(env = process7.env) {
734
+ const off = env.KAYNOOO_CLI_NO_USAGE;
735
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
736
+ }
737
+ function flagNames(argv) {
738
+ const end = argv.indexOf("--");
739
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
740
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
741
+ }
742
+ function usageEntry(bin, command, argv, code, now = new Date) {
743
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
744
+ usageError = undefined;
745
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
746
+ }
747
+ function recordUsage(entry, env = process7.env) {
748
+ if (!usageRecorded(env))
749
+ return;
750
+ try {
751
+ const path = usagePath(env);
752
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
753
+ appendFileSync(path, `${JSON.stringify(entry)}
754
+ `, { mode: 384 });
755
+ } catch {}
756
+ }
757
+
758
+ // ../kit/src/cli.ts
681
759
  var LEVEL_OPTIONS = {
682
760
  ...OUTPUT_OPTIONS,
683
761
  help: { type: "boolean", short: "h", description: "show this help" }
@@ -730,7 +808,7 @@ async function expand(scope, words) {
730
808
  }
731
809
  return { ...scope, commands, lazy: [] };
732
810
  }
733
- async function help({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
811
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
734
812
  const colors = paint(stream);
735
813
  const prefix = path.join(" ");
736
814
  const summary = await resolveSummary(lazySummary);
@@ -757,8 +835,8 @@ async function help({ path, header, summary: lazySummary, commands, defaultComma
757
835
  `);
758
836
  }
759
837
  function printError(prefix, message, hint, cause) {
760
- const colors = paint(process5.stderr);
761
- const styled = takesControlCodes(process5.stderr);
838
+ const colors = paint(process8.stderr);
839
+ const styled = takesControlCodes(process8.stderr);
762
840
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
763
841
  const under = (label, text, tint) => text === undefined ? "" : `
764
842
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -777,6 +855,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
777
855
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
778
856
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
779
857
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
858
+ if (error instanceof UsageError)
859
+ noteUsageError(error.message);
780
860
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
781
861
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
782
862
  return error instanceof Exit ? error.code : 1;
@@ -799,11 +879,11 @@ async function dispatch(level, typed, { version, redact }) {
799
879
  }
800
880
  }
801
881
  if (name === undefined && level.path.length > 1) {
802
- console.error(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stderr));
882
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
803
883
  return 2;
804
884
  }
805
885
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
806
- console.log(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stdout));
886
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
807
887
  return 0;
808
888
  }
809
889
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -919,22 +999,50 @@ async function printCandidates(found) {
919
999
  console.log(line);
920
1000
  return 0;
921
1001
  }
922
- async function runCli(cli, argv = process5.argv.slice(2)) {
1002
+ function packageVersion(entry = Bun.main) {
1003
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1004
+ try {
1005
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
1006
+ if (typeof version === "string")
1007
+ return version;
1008
+ } catch {}
1009
+ if (dirname2(dir) === dir)
1010
+ return "0.0.0";
1011
+ }
1012
+ }
1013
+ async function runCli(cli, argv = process8.argv.slice(2)) {
1014
+ const version = cli.version ?? packageVersion();
923
1015
  if (argv[0] === COMPLETE)
924
1016
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
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 });
1017
+ const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(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, redact: cli.redact });
1018
+ if (cli.usage !== false) {
1019
+ try {
1020
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1021
+ } catch {}
1022
+ }
1023
+ return code;
1024
+ }
1025
+ function commandPath(scope, argv) {
1026
+ const path = [];
1027
+ let level = scope;
1028
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
1029
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1030
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1031
+ if (command === undefined)
1032
+ break;
1033
+ path.push(word);
1034
+ if (!("commands" in command))
1035
+ break;
1036
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
1037
+ }
1038
+ return path.length === 0 ? undefined : path.join(" ");
926
1039
  }
927
- // ../kit/src/logs.ts
928
- var DAY_MS = 24 * 60 * 60 * 1000;
929
1040
  // ../kit/src/secrets.ts
930
1041
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
931
1042
  // ../kit/src/sessions.ts
932
1043
  var {Glob } = globalThis.Bun;
933
1044
  var SESSION_FILES = new Glob("*.json");
934
1045
  var ACCOUNT_DIRS = new Glob("*/sessions");
935
- // package.json
936
- var version = "0.7.2";
937
-
938
1046
  // ../kit/src/shell.ts
939
1047
  var SEPARATORS = new Set([`
940
1048
  `, ";", "|"]);
@@ -964,13 +1072,20 @@ var OCTAL = /^[0-7]{1,3}/;
964
1072
  var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
965
1073
  var MAX_DEPTH = 8;
966
1074
  var MAX_BRACES = 256;
967
- var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh"]);
968
- var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, "su", "runuser"]);
1075
+ var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
1076
+ var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
1077
+ var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
1078
+ var POWERSHELL_COMMAND = /^-c(?:o(?:m(?:m(?:a(?:nd?)?)?)?)?)?$/i;
1079
+ var POWERSHELL = new Set(["pwsh", "powershell"]);
1080
+ var FUNCTION_DEFINITION = /^[\w.:-]+\(\)\{?$/;
1081
+ var FUNCTION_NAME = /^[\w.:-]+$/;
969
1082
  var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
1083
+ var FISH_VALUE_OPTIONS = new Set(["-C", "--init-command"]);
1084
+ var LET_PIECE = /^\s*let\s/;
970
1085
  var PRINTERS = new Set(["echo", "printf"]);
971
1086
  var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
972
- function wrapper(short = "", long = [], operands = 0) {
973
- return { short, long, operands };
1087
+ function wrapper(short = "", long = [], operands = 0, runsString = false) {
1088
+ return { short, long, operands, runsString };
974
1089
  }
975
1090
  var WRAPPERS = new Map([
976
1091
  ["command", wrapper()],
@@ -988,6 +1103,11 @@ var WRAPPERS = new Map([
988
1103
  ["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
989
1104
  ["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
990
1105
  ["chroot", wrapper("", ["--userspec", "--groups"], 1)],
1106
+ ["watch", wrapper("n", ["--interval"], 0, true)],
1107
+ ["flock", wrapper("wE", ["--timeout", "--conflict-exit-code"], 1)],
1108
+ ["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
1109
+ ["unbuffer", wrapper()],
1110
+ ["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
991
1111
  ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
992
1112
  ]);
993
1113
  function closerOf(quote) {
@@ -1059,10 +1179,19 @@ function splitCommand(command) {
1059
1179
  quote = char;
1060
1180
  continue;
1061
1181
  }
1182
+ if (char === "$" && command[i + 1] === "[") {
1183
+ const close = command.indexOf("]", i);
1184
+ i = close === -1 ? command.length : close;
1185
+ continue;
1186
+ }
1062
1187
  if (char === "`") {
1063
1188
  i = closingBackquote(command, i);
1064
1189
  continue;
1065
1190
  }
1191
+ if (command.startsWith("((", char === "$" ? i + 1 : i) && (char === "$" || startsComment(command, i))) {
1192
+ i = closingParen(command, char === "$" ? i + 1 : i);
1193
+ continue;
1194
+ }
1066
1195
  if (char === "#" && startsComment(command, i)) {
1067
1196
  const newline = command.indexOf(`
1068
1197
  `, i);
@@ -1071,7 +1200,7 @@ function splitCommand(command) {
1071
1200
  i = end - 1;
1072
1201
  continue;
1073
1202
  }
1074
- const heredoc = char === "<" && command[i + 1] === "<" && command[i + 2] !== "<" ? HEREDOC.exec(command.slice(i)) : null;
1203
+ const heredoc = char === "<" && command[i + 1] === "<" && command[i + 2] !== "<" && !LET_PIECE.test(command.slice(start, i)) ? HEREDOC.exec(command.slice(i)) : null;
1075
1204
  if (heredoc) {
1076
1205
  heredocs.push({ word: heredoc[2] ?? heredoc[3] ?? heredoc[4] ?? "", stripsTabs: heredoc[1] === "-", isQuoted: heredoc[4] === undefined });
1077
1206
  i += heredoc[0].length - 1;
@@ -1333,11 +1462,23 @@ function skipOptions(tokens, spec) {
1333
1462
  function parseCommand(text) {
1334
1463
  const tokens = tokenize(text);
1335
1464
  const assignments = [];
1465
+ const strings = [];
1336
1466
  let isWrapped = false;
1337
1467
  for (;; ) {
1338
1468
  const first = tokens[0] ?? "";
1339
1469
  const spec = WRAPPERS.get(first.split("/").pop() ?? "");
1340
- if (OPENERS.test(first)) {
1470
+ if (first === "function" && tokens.length > 1) {
1471
+ isWrapped = true;
1472
+ tokens.splice(0, 2);
1473
+ if (tokens[0] === "()")
1474
+ tokens.shift();
1475
+ } else if (FUNCTION_DEFINITION.test(first)) {
1476
+ isWrapped = true;
1477
+ tokens.shift();
1478
+ } else if (tokens[1] === "()" && FUNCTION_NAME.test(first)) {
1479
+ isWrapped = true;
1480
+ tokens.splice(0, 2);
1481
+ } else if (OPENERS.test(first)) {
1341
1482
  isWrapped = true;
1342
1483
  const rest = first.replace(OPENERS, "");
1343
1484
  if (rest === "")
@@ -1360,6 +1501,8 @@ function parseCommand(text) {
1360
1501
  isWrapped = true;
1361
1502
  tokens.shift();
1362
1503
  skipOptions(tokens, spec);
1504
+ if (spec.runsString && WHITESPACE.test(tokens[0] ?? ""))
1505
+ strings.push(tokens[0] ?? "");
1363
1506
  } else {
1364
1507
  break;
1365
1508
  }
@@ -1371,7 +1514,7 @@ function parseCommand(text) {
1371
1514
  if (tokens.length > 0)
1372
1515
  tokens.splice(-1, 1, ...last === "" ? [] : [last]);
1373
1516
  const [program = "", ...args] = tokens;
1374
- return { program: program.split("/").pop() ?? "", args, assignments, isWrapped };
1517
+ return { program: program.split("/").pop() ?? "", args, assignments, isWrapped, strings };
1375
1518
  }
1376
1519
  function shellQuote(word) {
1377
1520
  return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
@@ -1385,7 +1528,8 @@ function commandStrings(tokens) {
1385
1528
  const name = token.split("/").pop() ?? "";
1386
1529
  if (!COMMAND_STRING_PROGRAMS.has(name))
1387
1530
  continue;
1388
- const isUser = name === "su" || name === "runuser";
1531
+ const isScanned = SCANNED_PROGRAMS.has(name);
1532
+ const isPowershell = POWERSHELL.has(name);
1389
1533
  let isValue = false;
1390
1534
  for (let j = i + 1;j < tokens.length; j++) {
1391
1535
  const option = tokens[j] ?? "";
@@ -1393,19 +1537,20 @@ function commandStrings(tokens) {
1393
1537
  isValue = false;
1394
1538
  continue;
1395
1539
  }
1396
- if (SHELL_VALUE_OPTIONS.has(option)) {
1540
+ if (SHELL_VALUE_OPTIONS.has(option) || name === "fish" && FISH_VALUE_OPTIONS.has(option)) {
1397
1541
  isValue = true;
1398
1542
  continue;
1399
1543
  }
1400
- if (option.startsWith("--command=")) {
1401
- found.push(option.slice("--command=".length));
1544
+ if (option.startsWith("--command=") || option.startsWith("--commands=")) {
1545
+ found.push(option.slice(option.indexOf("=") + 1));
1402
1546
  break;
1403
1547
  }
1404
- if (option === "--command" || !option.startsWith("--") && option.startsWith("-") && option.slice(1).includes("c")) {
1405
- found.push(tokens[j + 1] ?? "");
1548
+ const isCommandOption = isPowershell ? POWERSHELL_COMMAND.test(option) : !option.startsWith("--") && option.startsWith("-") && option.slice(1).includes("c");
1549
+ if (option === "--command" || option === "--commands" || isCommandOption) {
1550
+ found.push(isPowershell ? tokens.slice(j + 1).join(" ") : tokens[j + 1] ?? "");
1406
1551
  break;
1407
1552
  }
1408
- if (!option.startsWith("-") && !isUser)
1553
+ if (!option.startsWith("-") && !isScanned)
1409
1554
  break;
1410
1555
  }
1411
1556
  }
@@ -1438,8 +1583,8 @@ function findExecs(args) {
1438
1583
  }
1439
1584
  function nestedCommands(piece, previous) {
1440
1585
  const tokens = tokenize(piece.command);
1441
- const { program, args } = parseCommand(piece.command);
1442
- const found = commandStrings(tokens);
1586
+ const { program, args, strings } = parseCommand(piece.command);
1587
+ const found = [...commandStrings(tokens), ...strings];
1443
1588
  if (program === "eval")
1444
1589
  found.push(args.join(" "));
1445
1590
  if (program === "find")
@@ -1524,13 +1669,12 @@ function resolvePath(base, arg, home) {
1524
1669
  return `/${parts.join("/")}`;
1525
1670
  }
1526
1671
 
1527
- // ../db/src/guard.ts
1672
+ // ../db/src/sql-tokens.ts
1528
1673
  var WORD_START = /[a-z_\P{ASCII}]/iu;
1529
1674
  var WORD_PART = /[\w$\P{ASCII}]/u;
1530
1675
  var SPACE = /\s/;
1531
1676
  var ESCAPE_PREFIX = /e/i;
1532
1677
  var DOLLAR_TAG = /^\$(?:[a-z_]\w*)?\$/i;
1533
- var LOCK_KIND = /^(?:update|share|no|key)$/;
1534
1678
  var DIGITS = /\d/;
1535
1679
  var COMMAND_ENDS = ";";
1536
1680
  var UNCLOSED = "unclosed";
@@ -1538,11 +1682,6 @@ var NUL = "\x00";
1538
1682
  var UNICODE_IDENTIFIER = 'U&"';
1539
1683
  var UNICODE_PREFIX = /u&$/i;
1540
1684
  var LINE_END = /[\r\n]/;
1541
- var PRIVILEGED_SET = new Set(["role", "session", "transaction", "global", "persist", "persist_only", "password", "default"]);
1542
- var READ_STARTS = new Set(["select", "with", "values", "table", "show", "explain", "describe", "desc"]);
1543
- var WRITING_STARTS = new Set(["replace", "load", "rename", "flush", "kill", "shutdown", "install", "uninstall", "purge", "optimize", "repair", "import", "prepare", "execute"]);
1544
- var WRITE_WORDS = new Set(["insert", "update", "delete", "merge", "truncate", "drop", "alter", "create", "grant", "revoke", "into", "call", "vacuum", "lock", "refresh", "reindex", "cluster", "do"]);
1545
- var SIDE_EFFECT_FUNCTIONS = /^(?:nextval|setval|set_config|pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_rotate_logfile|pg_switch_wal|pg_create_restore_point|pg_advisory_lock\w*|pg_advisory_xact_lock\w*|pg_try_advisory\w*|pg_notify|lo_\w+|dblink\w*|pg_read_file|pg_read_binary_file|pg_ls_\w+|pg_stat_file|pg_sleep\w*|pg_export_snapshot|pg_backup_start|pg_backup_stop|pg_start_backup|pg_stop_backup|txid_current|pg_current_xact_id|pg_current_logfile|pg_wal_replay_\w+|\w+_to_xml\w*|pg_logical_\w+|pg_replication_\w+|pg_drop_replication_slot|pg_stat_reset\w*|pg_promote|pg_file_\w+|sleep|benchmark|get_lock|release_lock|release_all_locks|load_file|master_pos_wait|source_pos_wait|sys_exec|sys_eval)$/;
1546
1685
  function tokenize2(sql, dialect = "postgres") {
1547
1686
  const tokens = [];
1548
1687
  const isMysql = dialect === "mysql";
@@ -1640,6 +1779,23 @@ function splitStatements(tokens) {
1640
1779
  }
1641
1780
  return statements.filter((statement) => statement.length > 0);
1642
1781
  }
1782
+
1783
+ // ../db/src/guard-test.ts
1784
+ var TEST_WRITE_STARTS = new Set(["insert", "update", "delete", "replace", "merge", "truncate", "create", "alter", "drop", "rename", "with", "select", "values", "table", "comment", "refresh"]);
1785
+ var DEFINITION_STARTS = new Set(["create", "alter", "drop", "rename"]);
1786
+ var STORED_CODE = new Set(["event", "procedure", "function", "trigger", "rule", "aggregate"]);
1787
+ var DEFINITION_MODIFIERS = new Set(["or", "replace", "temporary", "temp", "unlogged", "unique", "fulltext", "spatial", "definer"]);
1788
+ var SERVER_OBJECTS = new Set(["database", "user", "role", "server", "tablespace", "extension", "system", "subscription", "publication", "logfile", "instance", "resource"]);
1789
+ var FILE_WORDS = new Set(["infile", "outfile", "dumpfile"]);
1790
+ var SEQUENCE_FUNCTIONS = new Set(["nextval", "setval"]);
1791
+
1792
+ // ../db/src/guard.ts
1793
+ var LOCK_KIND = /^(?:update|share|no|key)$/;
1794
+ var PRIVILEGED_SET = new Set(["role", "session", "transaction", "global", "persist", "persist_only", "password", "default"]);
1795
+ var READ_STARTS = new Set(["select", "with", "values", "table", "show", "explain", "describe", "desc"]);
1796
+ var WRITING_STARTS = new Set(["replace", "load", "rename", "flush", "kill", "shutdown", "install", "uninstall", "purge", "optimize", "repair", "import", "prepare", "execute"]);
1797
+ var WRITE_WORDS = new Set(["insert", "update", "delete", "merge", "truncate", "drop", "alter", "create", "grant", "revoke", "into", "call", "vacuum", "lock", "refresh", "reindex", "cluster", "do"]);
1798
+ var SIDE_EFFECT_FUNCTIONS = /^(?:nextval|setval|set_config|pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_rotate_logfile|pg_switch_wal|pg_create_restore_point|pg_advisory_lock\w*|pg_advisory_xact_lock\w*|pg_try_advisory\w*|pg_notify|lo_\w+|dblink\w*|pg_read_file|pg_read_binary_file|pg_ls_\w+|pg_stat_file|pg_sleep\w*|pg_export_snapshot|pg_backup_start|pg_backup_stop|pg_start_backup|pg_stop_backup|txid_current|pg_current_xact_id|pg_current_logfile|pg_wal_replay_\w+|\w+_to_xml\w*|pg_logical_\w+|pg_replication_\w+|pg_drop_replication_slot|pg_stat_reset\w*|pg_promote|pg_file_\w+|sleep|benchmark|get_lock|release_lock|release_all_locks|load_file|master_pos_wait|source_pos_wait|sys_exec|sys_eval)$/;
1643
1799
  var isPunct = (token, text) => token?.kind === "punct" && token.text === text;
1644
1800
  function copyReads(statement, index) {
1645
1801
  let depth = 0;
@@ -1697,13 +1853,6 @@ function statementWrites(statement) {
1697
1853
  function writes(sql, dialect = "postgres") {
1698
1854
  return [...new Set(splitStatements(tokenize2(sql, dialect)).flatMap(statementWrites))];
1699
1855
  }
1700
- var TEST_WRITE_STARTS = new Set(["insert", "update", "delete", "replace", "merge", "truncate", "create", "alter", "drop", "rename", "with", "select", "values", "table", "comment", "refresh"]);
1701
- var DEFINITION_STARTS = new Set(["create", "alter", "drop", "rename"]);
1702
- var STORED_CODE = new Set(["event", "procedure", "function", "trigger", "rule", "aggregate"]);
1703
- var DEFINITION_MODIFIERS = new Set(["or", "replace", "temporary", "temp", "unlogged", "unique", "fulltext", "spatial", "definer"]);
1704
- var SERVER_OBJECTS = new Set(["database", "user", "role", "server", "tablespace", "extension", "system", "subscription", "publication", "logfile", "instance", "resource"]);
1705
- var FILE_WORDS = new Set(["infile", "outfile", "dumpfile"]);
1706
- var SEQUENCE_FUNCTIONS = new Set(["nextval", "setval"]);
1707
1856
 
1708
1857
  // ../db/src/clients.ts
1709
1858
  var SQL_CLIENTS = new Set(["psql", "mysql", "mariadb", "pgcli", "mycli", "sqlite3"]);
@@ -1718,12 +1867,18 @@ var STATEMENT_LONGS = new Set(["--command", "--execute"]);
1718
1867
  var DATABASE_LONGS = new Set(["--dbname", "--database"]);
1719
1868
  var VALUE_LONGS = new Set(["--host", "--port", "--username", "--user", "--output", "--set", "--variable", "--field-separator", "--record-separator", "--pset", "--log-file", "--socket"]);
1720
1869
  var PRINTERS2 = new Set(["echo", "printf"]);
1870
+ var FILE_LONGS = new Set(["--file"]);
1871
+ var KNOWN_LONGS = [...STATEMENT_LONGS, ...FILE_LONGS, ...DATABASE_LONGS, ...VALUE_LONGS];
1721
1872
  var LIST_OPTIONS = new Set(["-l", "--list"]);
1722
1873
  var REDIRECT_ONLY2 = /^\d*(?:>|>>|>&|&>|>\||<&|<>)$/;
1723
1874
  var REDIRECT_START2 = /^\d*>|^&>/;
1724
1875
  var URL_DATABASE = /^[a-z][a-z\d+.-]*:\/\/[^/]*\/([^?#]*)/i;
1725
1876
  var WRITING_CONSOLE = /^(?:doctrine:(?:migrations:(?:migrate|execute|rollup)|schema:(?:update|create|drop)|database:(?:create|drop)|fixtures:load)|migrate(?::\w+)?|db:(?:seed|wipe))$/;
1726
1877
  var TEST_SCOPED = /(?:^|[^a-z])test/i;
1878
+ var ASSIGNMENT2 = /^([A-Z_]\w*)=/i;
1879
+ var TARGET_VARIABLE = /(?:^|_|^PG)(?:ENV|ENVIRONMENT|DATABASE|DB|DBNAME|DSN|URL)$|^(?:DB|DATABASE)_NAME$/i;
1880
+ var USER_OPTION = /^(?:-[uU]|--user(?:name)?)$/;
1881
+ var USER_ATTACHED = /^(?:--user(?:name)?=|-[uU].)/;
1727
1882
  var SHOT_STACK = /\.worktrees\/[^/\s]+\/shot(?:\/|$)|--shot(?:-|$)/;
1728
1883
  var DEVICE_PATH = /^\/(?:dev|proc|sys)\//;
1729
1884
  var STDIN_PATHS = new Set(["-", "/dev/stdin"]);
@@ -1746,6 +1901,12 @@ function programOf(word) {
1746
1901
  function databaseOf(operand) {
1747
1902
  return URL_DATABASE.exec(operand)?.[1] ?? operand;
1748
1903
  }
1904
+ function fullOption(option) {
1905
+ if (KNOWN_LONGS.includes(option) || option.length < 4)
1906
+ return option;
1907
+ const candidates = KNOWN_LONGS.filter((each) => each.startsWith(option));
1908
+ return candidates.length === 1 ? candidates[0] : option;
1909
+ }
1749
1910
  function clientInput(name, args) {
1750
1911
  const input = { statements: [], files: [], databases: [], operands: [] };
1751
1912
  const valueShorts = VALUE_SHORTS[name] ?? "";
@@ -1769,7 +1930,8 @@ function clientInput(name, args) {
1769
1930
  } else if (REDIRECT_START2.test(arg)) {
1770
1931
  continue;
1771
1932
  } else if (arg.startsWith("--")) {
1772
- const [option = "", ...rest] = arg.split("=");
1933
+ const [spelled = "", ...rest] = arg.split("=");
1934
+ const option = fullOption(spelled);
1773
1935
  const attached = rest.length > 0 ? rest.join("=") : undefined;
1774
1936
  const value = attached ?? args[i + 1] ?? "";
1775
1937
  if (STATEMENT_LONGS.has(option))
@@ -1808,10 +1970,19 @@ function clientInput(name, args) {
1808
1970
  input.databases.push(databaseOf(input.operands[0]));
1809
1971
  return input;
1810
1972
  }
1973
+ function isTestWord(word) {
1974
+ const assignment = ASSIGNMENT2.exec(word);
1975
+ if (assignment !== null && !TARGET_VARIABLE.test(assignment[1] ?? ""))
1976
+ return false;
1977
+ return TEST_SCOPED.test(word) || SHOT_STACK.test(word);
1978
+ }
1979
+ function targetWords(words) {
1980
+ return words.filter((word, index) => !USER_OPTION.test(words[index - 1] ?? "") && !USER_ATTACHED.test(word));
1981
+ }
1811
1982
  function isTestScoped(words, client, input) {
1812
1983
  if (client === -1)
1813
- return words.some((word) => TEST_SCOPED.test(word) || SHOT_STACK.test(word));
1814
- return words.slice(0, client).some((word) => TEST_SCOPED.test(word) || SHOT_STACK.test(word)) || (input?.databases ?? []).some((name) => TEST_SCOPED.test(name));
1984
+ return targetWords(words).some(isTestWord);
1985
+ return targetWords(words.slice(0, client)).some(isTestWord) || (input?.databases ?? []).some((name) => TEST_SCOPED.test(name));
1815
1986
  }
1816
1987
  async function fileText(path, read) {
1817
1988
  return DEVICE_PATH.test(path) ? null : read(path);
@@ -1854,74 +2025,99 @@ async function sqlViolation(command, read) {
1854
2025
  return null;
1855
2026
  }
1856
2027
 
1857
- // ../env/src/files.ts
1858
- var ENV_FILE = /^(?:\.env(?:\..+)?|.+\.env|\.envrc)$/;
1859
- var TEMPLATE = /\.(?:example|sample|template|dist|defaults)$/;
1860
- var SKIPPED = new Set(["node_modules", ".git", "vendor"]);
1861
-
1862
- // ../env/src/guard.ts
1863
- var REDIRECT = /^\d*[<>]+&?/;
1864
- var ENVRC = ".envrc";
1865
- var PROC_ENVIRON = /^\/proc\/[^/]+\/environ$/;
1866
- var ENV_NAME_IN_CODE = /(?:^|[^\w.-])(\.env(?:\.[\w.-]*\w)?|\.envrc)(?![\w-])/g;
1867
- var ENV_NAME_IN_PATTERN = /(?:^|[^\w-])\.env(?![\w-])/;
1868
- var PYTHON_ENVIRON = /\bos\.environ\b(?!\s*(?:\[|\.get\b))/;
1869
- var VARIABLE = /\$(?:(\w+)|\{(\w+)\})/;
1870
- var ASSIGNMENT2 = /^\w+=/;
1871
- var SHORT_FLAGS = /^-[a-z]+$/i;
2028
+ // ../env/src/guard-dumps.ts
1872
2029
  var OPENER = /^[({]+/;
1873
- var ENV_SAMPLES = [".env", ".env.local", ".env.production", ".envrc"];
1874
- var MAX_VARIANTS = 64;
1875
- var INTERPRETERS = new Set(["bun", "deno", "node", "python", "python3", "ruby", "perl", "php", "lua", "awk", "gawk"]);
1876
- var CODE_OPTIONS = new Set(["-e", "-c", "-p", "-E", "-pe", "-r", "--eval", "--print", "--command"]);
1877
- var GREPS = new Set(["grep", "egrep", "fgrep"]);
1878
- var GREP_VALUE_OPTIONS = new Set(["-e", "-f", "-m", "-A", "-B", "-C", "-d", "-D", "--regexp", "--file", "--max-count", "--include", "--exclude", "--exclude-dir", "--exclude-from", "--context", "--after-context", "--before-context", "--label", "--binary-files", "--directories", "--devices"]);
1879
- var RG_VALUE_OPTIONS = new Set(["-e", "-f", "-g", "-t", "-T", "-m", "-A", "-B", "-C", "-j", "-d", "-r", "-M", "-E", "--replace", "--max-columns", "--encoding", "--regexp", "--file", "--glob", "--iglob", "--type", "--type-not", "--max-count", "--context", "--after-context", "--before-context", "--threads", "--max-depth", "--max-filesize"]);
1880
- var PATTERN_OPTIONS = new Set(["-e", "-f", "--regexp", "--file"]);
1881
- var GREP_NAMES_ONLY = new Set("lLcq");
1882
- var RG_NAMES_ONLY = new Set("lcq");
1883
- var NAMES_ONLY_LONG = new Set(["--files-with-matches", "--files-without-match", "--count", "--count-matches", "--quiet", "--silent"]);
1884
- var FIND_ACTIONS = new Set(["-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf", "-fls", "-files0-from"]);
1885
- var CAN_REACH_FILES = /read|write|open|exec|spawn|system|popen|import|require|eval|load|fetch|glob|stream|source|getline|constructor|file(?!s\b)|\bcat\b|\b(?:Bun|Deno|fs|os|io|sh|bash|process|globalThis|window|Function|qx)\b|\$\s*[`({]|`/i;
1886
- var HIDDEN_FLAGS = /^(?:-u{2,}|--hidden|-\.)$/i;
1887
- var REGEX_SPECIALS = /[.+^${}()|\\[\]]/g;
1888
- var NEGATED_CLASS = /^!/;
1889
- var GLOB_CHAR = /[*?[]/;
1890
- var HAS_R = /r/i;
1891
2030
  var DUMP_FLAGS = /^-[a-z]*[px]/;
1892
- var DECLARERS = new Set(["export", "declare", "local", "readonly", "typeset"]);
1893
- var WHOLE_TREE_OPERAND = /^(?:(?:\.\.?\/?)+|~\/?|\$HOME\/?|\/)$/;
1894
2031
  var GIT_PATCHES = new Set(["diff", "log", "show", "whatchanged", "format-patch", "grep"]);
1895
2032
  var GIT_NO_PATCH = new Set(["--stat", "--numstat", "--shortstat", "--name-only", "--name-status", "--summary", "-s", "--no-patch", "--check", "--quiet"]);
1896
2033
  var GIT_VALUE_OPTIONS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"]);
1897
2034
  var GIT_PATCH_FLAGS = new Set(["-p", "-u", "--patch", "-c", "--cc", "--patch-with-stat", "--patch-with-raw"]);
1898
2035
  var GIT_EXCLUDE = /^:(?:!|\^|\(exclude\))/;
1899
- var EXCLUDES_ENV = /^(?:--exclude(?:-dir)?=.*env|(?:--glob=|--iglob=|-g)?!.*env)/;
1900
- var EXCLUDE_OPTIONS = new Set(["--exclude", "--exclude-dir", "-g", "--glob", "--iglob"]);
1901
- var ENV_DUMP = /(?:console\.\w+|JSON\.stringify|Object\.(?:entries|keys|values)|print)\(\s*process\.env\s*[,)]/;
1902
- var HARMLESS = new Set(["ev", "redact", "ls", "stat", "test", "[", "[[", "touch"]);
1903
- var GIT_HARMLESS = new Set(["check-ignore", "ls-files", "status"]);
1904
- var XARGS_SAFE = new Set(["ls", "stat", "wc", "test", "[", "touch", "echo", "printf", "basename", "dirname", "ev", "redact", ""]);
1905
- var PARALLEL_VALUE_OPTIONS = new Set(["-j", "--jobs", "-P", "--max-procs", "-S", "--sshlogin", "-C", "--colsep", "-n", "--max-args", "-N", "-d", "--delimiter", "-E", "-I", "--timeout", "--delay", "--joblog", "--results", "--tmpdir", "-a", "--arg-file", "--halt", "--retries", "--tag-string"]);
1906
- var IDENTIFIER = /^[A-Z_]\w*$/i;
1907
- var READ_VALUE_OPTIONS = new Set(["-a", "-d", "-i", "-n", "-N", "-p", "-t", "-u"]);
1908
2036
  var ENV_PRINTERS = new Set(["env", "printenv"]);
1909
2037
  var DOCKER = new Set(["docker", "docker-compose"]);
1910
2038
  var SHELLS2 = new Set(["sh", "bash", "zsh", "ash"]);
2039
+ var SHELL_COMMAND_FLAG = /^-[abd-z]*c[a-z]*$/;
1911
2040
  var DOCKER_VALUE_OPTIONS = new Set(["-f", "--file", "-p", "--project-name", "--profile", "--env-file", "--project-directory", "--ansi", "--progress", "--parallel", "-H", "--host", "-c", "--context", "--config", "-l", "--log-level"]);
1912
2041
  var EXEC_VALUE_OPTIONS = new Set(["-e", "--env", "--env-file", "-u", "--user", "-w", "--workdir", "--index", "--detach-keys"]);
1913
2042
  var CONFIG_LISTS = new Set(["--services", "--volumes", "--profiles", "--images", "--networks", "--hash", "-q", "--quiet"]);
1914
2043
  var FORMAT_OPTIONS = new Set(["-f", "--format"]);
1915
2044
  var WHOLE_FORMAT = /Env|\{\{\s*json\s+\.\s*\}\}|^json$/;
1916
- var USE_EV = '.env files hold secrets that must never reach the transcript, so they are not read, edited or printed directly. Use `ev` instead: `ev list`, `ev get KEY` (masked), `ev grep <regex>` for the keys matching it, `ev show <rev>:<file>` for one at a git revision, `printf %s "$value" | ev set KEY [file]` (`--empty` for an empty value), `ev unset KEY`, `ev cp KEY --from .env --to .env.local`, `ev mv KEY --from .env --to .env.local`, `ev diff a b`, `ev missing`; and pipe output that may carry a secret through `redact`, as `docker compose exec <svc> printenv | redact` or `docker compose config | redact`. If `ev` is missing: `bun install -g @kaynooo/cli-env`.';
1917
- var USE_EV_SEARCH = "To search them, `ev grep <regex>` prints the matching keys, masked. `grep -l`, `-L` and `-c` (file names and counts) are allowed, and a tree-wide search can run as `rg <regex>`, which skips gitignored files, or `grep -r --exclude='.env*' <regex> .`.";
1918
- function isSearchCommand(piece) {
1919
- const { program } = parseCommand(piece.command);
1920
- return GREPS.has(program) || program === "rg" || program === "ag";
2045
+ function firstOperand(words, valueOptions) {
2046
+ for (let i = 0;i < words.length; i++) {
2047
+ const word = words[i] ?? "";
2048
+ if (valueOptions.has(word))
2049
+ i++;
2050
+ else if (!word.startsWith("-"))
2051
+ return i;
2052
+ }
2053
+ return words.length;
1921
2054
  }
1922
- function isEnvFile(path) {
1923
- const name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf(":")) + 1);
1924
- return (ENV_FILE.test(name) || name === ".env*" || name === ENVRC) && !TEMPLATE.test(name);
2055
+ function printsEnv([program = "", ...args]) {
2056
+ const flags = args.findIndex((arg) => !arg.startsWith("-") || SHELL_COMMAND_FLAG.test(arg));
2057
+ if (SHELLS2.has(program) && SHELL_COMMAND_FLAG.test(args[flags] ?? ""))
2058
+ return splitCommand(args[flags + 1] ?? "").some((piece) => ENV_PRINTERS.has(tokenize(piece.command)[0] ?? ""));
2059
+ return ENV_PRINTERS.has(program);
2060
+ }
2061
+ function dumpsContainerEnv(program, args) {
2062
+ if (!DOCKER.has(program))
2063
+ return false;
2064
+ const afterOptions = (words) => words.slice(firstOperand(words, DOCKER_VALUE_OPTIONS));
2065
+ let rest = afterOptions(args);
2066
+ const isCompose = program === "docker-compose" || rest[0] === "compose";
2067
+ if (program === "docker" && isCompose)
2068
+ rest = afterOptions(rest.slice(1));
2069
+ const [subcommand = "", ...after] = rest;
2070
+ if (subcommand === "exec")
2071
+ return printsEnv(after.slice(firstOperand(after, EXEC_VALUE_OPTIONS) + 1));
2072
+ if (isCompose)
2073
+ return subcommand === "config" && !after.some((word) => CONFIG_LISTS.has(word));
2074
+ if (subcommand !== "inspect" && (subcommand !== "container" || after[0] !== "inspect"))
2075
+ return false;
2076
+ const format = after.find((_, i) => FORMAT_OPTIONS.has(after[i - 1] ?? "")) ?? after.find((word) => word.startsWith("--format="))?.slice("--format=".length);
2077
+ return format === undefined || WHOLE_FORMAT.test(format);
2078
+ }
2079
+ function dumpsEnvironment(program, args, tokens) {
2080
+ const isBare = args.every((arg) => arg.startsWith("-"));
2081
+ if (program === "printenv" || program === "export")
2082
+ return isBare;
2083
+ if (program === "declare" || program === "typeset")
2084
+ return isBare && args.some((arg) => DUMP_FLAGS.test(arg));
2085
+ if (program === "set")
2086
+ return args.length === 0;
2087
+ return program === "" && tokens.some((token) => token.replace(OPENER, "") === "env");
2088
+ }
2089
+ function printsTrackedEnv(program, args) {
2090
+ if (program !== "git")
2091
+ return false;
2092
+ const at = args.findIndex((arg, i) => !arg.startsWith("-") && !GIT_VALUE_OPTIONS.has(args[i - 1] ?? ""));
2093
+ const name = args[at] ?? "";
2094
+ const rest = args.slice(at + 1);
2095
+ if (!GIT_PATCHES.has(name) || rest.some((arg) => GIT_EXCLUDE.test(arg)))
2096
+ return false;
2097
+ if (name === "grep")
2098
+ return true;
2099
+ if (name === "log" || name === "whatchanged")
2100
+ return rest.some((arg) => GIT_PATCH_FLAGS.has(arg));
2101
+ return !rest.some((arg) => GIT_NO_PATCH.has(arg));
2102
+ }
2103
+
2104
+ // ../env/src/files.ts
2105
+ var ENV_FILE = /^(?:\.env(?:\..+)?|.+\.env|\.envrc)$/;
2106
+ var TEMPLATE = /\.(?:example|sample|template|dist|defaults)$/;
2107
+ var SKIPPED = new Set(["node_modules", ".git", "vendor"]);
2108
+
2109
+ // ../env/src/guard-paths.ts
2110
+ var REDIRECT = /^\d*[<>]+&?/;
2111
+ var ENVRC = ".envrc";
2112
+ var PROC_ENVIRON = /^\/proc\/[^/]+\/environ$/;
2113
+ var ENV_SAMPLES = [".env", ".env.local", ".env.production", ".envrc"];
2114
+ var REGEX_SPECIALS = /[.+^${}()|\\[\]]/g;
2115
+ var NEGATED_CLASS = /^!/;
2116
+ var GLOB_CHAR = /[*?[]/;
2117
+ var EXCLUDE_OPTIONS = new Set(["--exclude", "--exclude-dir", "-g", "--glob", "--iglob"]);
2118
+ function isEnvFile(path) {
2119
+ const name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf(":")) + 1);
2120
+ return (ENV_FILE.test(name) || name === ".env*" || name === ENVRC) && !TEMPLATE.test(name);
1925
2121
  }
1926
2122
  function globRegex(glob) {
1927
2123
  let source = "";
@@ -1961,43 +2157,25 @@ function namesEnvFile(word, previous, isGlob) {
1961
2157
  const path = targetOf(word);
1962
2158
  return isEnvFile(path) || PROC_ENVIRON.test(path) || isGlob && globReachesEnv(path);
1963
2159
  }
1964
- function variablesOf(command) {
1965
- const variables = new Map;
1966
- const add = (assignment) => {
1967
- const at = assignment.indexOf("=");
1968
- const name = assignment.slice(0, at);
1969
- variables.set(name, [...variables.get(name) ?? [], assignment.slice(at + 1)]);
1970
- };
1971
- for (const piece of splitCommand(command)) {
1972
- const { program, args, assignments } = parseCommand(piece.command);
1973
- const tokens = tokenize(piece.command);
1974
- const declared = DECLARERS.has(program) ? args.filter((arg) => ASSIGNMENT2.test(arg)) : [];
1975
- for (const assignment of [...assignments, ...declared])
1976
- add(assignment);
1977
- if (tokens[0] === "for" && tokens[2] === "in" && tokens[1] !== undefined)
1978
- variables.set(tokens[1], [...variables.get(tokens[1]) ?? [], ...tokens.slice(3)]);
1979
- }
1980
- return variables;
1981
- }
1982
- function variantsOf(word, variables) {
1983
- let found = [word.text];
1984
- for (let round = 0;round < 4 && found.some((each) => VARIABLE.test(each)); round++) {
1985
- found = found.flatMap((each) => {
1986
- const match = VARIABLE.exec(each);
1987
- const values = variables.get(match?.[1] ?? match?.[2] ?? "");
1988
- if (match === null || values === undefined)
1989
- return [each.replace(VARIABLE, "")];
1990
- return values.map((value) => each.slice(0, match.index) + value + each.slice(match.index + match[0].length));
1991
- }).slice(0, MAX_VARIANTS);
1992
- }
1993
- return found.flatMap((each) => word.hasBrace ? braceExpand(each) : [each]);
1994
- }
1995
- function codeReadsEnvFile(code) {
1996
- return [...code.matchAll(ENV_NAME_IN_CODE)].some((match) => isEnvFile(match[1] ?? "")) && CAN_REACH_FILES.test(code);
1997
- }
1998
- function codeReadsEnv(found, heredocs) {
1999
- const sources = [...found.filter((word, i) => word.isProse || CODE_OPTIONS.has(found[i - 1]?.text ?? "")).map((word) => word.text), ...heredocs];
2000
- return sources.some((code) => PYTHON_ENVIRON.test(code) || codeReadsEnvFile(code));
2160
+
2161
+ // ../env/src/guard-search.ts
2162
+ var ENV_NAME_IN_PATTERN = /(?:^|[^\w-])\.env(?![\w-])/;
2163
+ var SHORT_FLAGS = /^-[a-z]+$/i;
2164
+ var GREPS = new Set(["grep", "egrep", "fgrep"]);
2165
+ var GREP_VALUE_OPTIONS = new Set(["-e", "-f", "-m", "-A", "-B", "-C", "-d", "-D", "--regexp", "--file", "--max-count", "--include", "--exclude", "--exclude-dir", "--exclude-from", "--context", "--after-context", "--before-context", "--label", "--binary-files", "--directories", "--devices"]);
2166
+ var RG_VALUE_OPTIONS = new Set(["-e", "-f", "-g", "-t", "-T", "-m", "-A", "-B", "-C", "-j", "-d", "-r", "-M", "-E", "--replace", "--max-columns", "--encoding", "--regexp", "--file", "--glob", "--iglob", "--type", "--type-not", "--max-count", "--context", "--after-context", "--before-context", "--threads", "--max-depth", "--max-filesize"]);
2167
+ var PATTERN_OPTIONS = new Set(["-e", "-f", "--regexp", "--file"]);
2168
+ var GREP_NAMES_ONLY = new Set("lLcq");
2169
+ var RG_NAMES_ONLY = new Set("lcq");
2170
+ var NAMES_ONLY_LONG = new Set(["--files-with-matches", "--files-without-match", "--count", "--count-matches", "--quiet", "--silent"]);
2171
+ var FIND_ACTIONS = new Set(["-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf", "-fls", "-files0-from"]);
2172
+ var HIDDEN_FLAGS = /^(?:-u{2,}|--hidden|-\.)$/i;
2173
+ var HAS_R = /r/i;
2174
+ var WHOLE_TREE_OPERAND = /^(?:(?:\.\.?\/?)+|~\/?|\$HOME\/?|\/)$/;
2175
+ var EXCLUDES_ENV = /^(?:--exclude(?:-dir)?=.*env|(?:--glob=|--iglob=|-g)?!.*env)/;
2176
+ function isSearchCommand(piece) {
2177
+ const { program } = parseCommand(piece.command);
2178
+ return GREPS.has(program) || program === "rg" || program === "ag";
2001
2179
  }
2002
2180
  function printsNamesOnly(program, args) {
2003
2181
  const isGrep = GREPS.has(program);
@@ -2065,58 +2243,6 @@ function patternIndex(args, valueOptions) {
2065
2243
  }
2066
2244
  return;
2067
2245
  }
2068
- function firstOperand(words, valueOptions) {
2069
- for (let i = 0;i < words.length; i++) {
2070
- const word = words[i] ?? "";
2071
- if (valueOptions.has(word))
2072
- i++;
2073
- else if (!word.startsWith("-"))
2074
- return i;
2075
- }
2076
- return words.length;
2077
- }
2078
- function printsEnv([program = "", ...args]) {
2079
- if (SHELLS2.has(program) && args[0] === "-c")
2080
- return splitCommand(args[1] ?? "").some((piece) => ENV_PRINTERS.has(tokenize(piece.command)[0] ?? ""));
2081
- return ENV_PRINTERS.has(program);
2082
- }
2083
- function dumpsContainerEnv(program, args) {
2084
- if (!DOCKER.has(program))
2085
- return false;
2086
- const afterOptions = (words) => words.slice(firstOperand(words, DOCKER_VALUE_OPTIONS));
2087
- let rest = afterOptions(args);
2088
- const isCompose = program === "docker-compose" || rest[0] === "compose";
2089
- if (program === "docker" && isCompose)
2090
- rest = afterOptions(rest.slice(1));
2091
- const [subcommand = "", ...after] = rest;
2092
- if (subcommand === "exec")
2093
- return printsEnv(after.slice(firstOperand(after, EXEC_VALUE_OPTIONS) + 1));
2094
- if (isCompose)
2095
- return subcommand === "config" && !after.some((word) => CONFIG_LISTS.has(word));
2096
- if (subcommand !== "inspect" && (subcommand !== "container" || after[0] !== "inspect"))
2097
- return false;
2098
- const format = after.find((_, i) => FORMAT_OPTIONS.has(after[i - 1] ?? "")) ?? after.find((word) => word.startsWith("--format="))?.slice("--format=".length);
2099
- return format === undefined || WHOLE_FORMAT.test(format);
2100
- }
2101
- function readsEnv(piece, variables) {
2102
- const { program, args } = parseCommand(piece.command);
2103
- if (program === "" || HARMLESS.has(program) || program === "git" && GIT_HARMLESS.has(args[0] ?? ""))
2104
- return false;
2105
- if (INTERPRETERS.has(program) && codeReadsEnv(words(piece.command), piece.heredocs))
2106
- return true;
2107
- if (printsNamesOnly(program, args) || listsFiles(program, args))
2108
- return false;
2109
- return namesEnv(piece, variables);
2110
- }
2111
- function namesEnv(piece, variables) {
2112
- const { program, args } = parseCommand(piece.command);
2113
- const found = words(piece.command);
2114
- const isExclusion = (word) => program === "git" && GIT_EXCLUDE.test(word.text);
2115
- const isSearch = GREPS.has(program) || program === "rg" || program === "ag";
2116
- const patternAt = isSearch ? patternIndex(args, GREPS.has(program) ? GREP_VALUE_OPTIONS : RG_VALUE_OPTIONS) : undefined;
2117
- const pattern = patternAt === undefined ? undefined : found.length - args.length + patternAt;
2118
- return found.some((word, index) => index !== pattern && !word.isProse && !isExclusion(word) && variantsOf(word, variables).some((variant) => namesEnvFile(variant, found[index - 1]?.text, word.hasGlob)));
2119
- }
2120
2246
  function operandsOf(args, valueOptions) {
2121
2247
  const operands = [];
2122
2248
  let hasPattern = false;
@@ -2143,30 +2269,6 @@ function searchesEnv(program, args) {
2143
2269
  const operands = operandsOf(args, isGrep ? GREP_VALUE_OPTIONS : RG_VALUE_OPTIONS);
2144
2270
  return operands.length === 0 || operands.some((operand) => WHOLE_TREE_OPERAND.test(operand));
2145
2271
  }
2146
- function dumpsEnvironment(program, args, tokens) {
2147
- const isBare = args.every((arg) => arg.startsWith("-"));
2148
- if (program === "printenv" || program === "export")
2149
- return isBare;
2150
- if (program === "declare" || program === "typeset")
2151
- return isBare && args.some((arg) => DUMP_FLAGS.test(arg));
2152
- if (program === "set")
2153
- return args.length === 0;
2154
- return program === "" && tokens.some((token) => token.replace(OPENER, "") === "env");
2155
- }
2156
- function printsTrackedEnv(program, args) {
2157
- if (program !== "git")
2158
- return false;
2159
- const at = args.findIndex((arg, i) => !arg.startsWith("-") && !GIT_VALUE_OPTIONS.has(args[i - 1] ?? ""));
2160
- const name = args[at] ?? "";
2161
- const rest = args.slice(at + 1);
2162
- if (!GIT_PATCHES.has(name) || rest.some((arg) => GIT_EXCLUDE.test(arg)))
2163
- return false;
2164
- if (name === "grep")
2165
- return true;
2166
- if (name === "log" || name === "whatchanged")
2167
- return rest.some((arg) => GIT_PATCH_FLAGS.has(arg));
2168
- return !rest.some((arg) => GIT_NO_PATCH.has(arg));
2169
- }
2170
2272
  function searchesEnvNames(piece) {
2171
2273
  const { program, args } = parseCommand(piece.command);
2172
2274
  if (!GREPS.has(program) && program !== "rg")
@@ -2174,6 +2276,82 @@ function searchesEnvNames(piece) {
2174
2276
  const at = patternIndex(args, GREPS.has(program) ? GREP_VALUE_OPTIONS : RG_VALUE_OPTIONS);
2175
2277
  return at !== undefined && ENV_NAME_IN_PATTERN.test((args[at] ?? "").replaceAll("\\", ""));
2176
2278
  }
2279
+
2280
+ // ../env/src/guard-names.ts
2281
+ var ENV_NAME_IN_CODE = /(?:^|[^\w.-])(\.env(?:\.[\w.-]*\w)?|\.envrc)(?![\w-])/g;
2282
+ var PYTHON_ENVIRON = /\bos\.environ\b(?!\s*(?:\[|\.get\b))/;
2283
+ var VARIABLE = /\$(?:(\w+)|\{(\w+)\})/;
2284
+ var ASSIGNMENT3 = /^\w+=/;
2285
+ var MAX_VARIANTS = 64;
2286
+ var INTERPRETERS = new Set(["bun", "deno", "node", "python", "python3", "ruby", "perl", "php", "lua", "awk", "gawk"]);
2287
+ var CODE_OPTIONS = new Set(["-e", "-c", "-p", "-E", "-pe", "-r", "--eval", "--print", "--command"]);
2288
+ var CAN_REACH_FILES = /read|write|open|exec|spawn|system|popen|import|require|eval|load|fetch|glob|stream|source|getline|constructor|file(?!s\b)|\bcat\b|\b(?:Bun|Deno|fs|os|io|sh|bash|process|globalThis|window|Function|qx)\b|\$\s*[`({]|`/i;
2289
+ var DECLARERS = new Set(["export", "declare", "local", "readonly", "typeset"]);
2290
+ var HARMLESS = new Set(["ev", "redact", "ls", "stat", "test", "[", "[[", "touch"]);
2291
+ var GIT_HARMLESS = new Set(["check-ignore", "ls-files", "status"]);
2292
+ function variablesOf(command) {
2293
+ const variables = new Map;
2294
+ const add = (assignment) => {
2295
+ const at = assignment.indexOf("=");
2296
+ const name = assignment.slice(0, at);
2297
+ variables.set(name, [...variables.get(name) ?? [], assignment.slice(at + 1)]);
2298
+ };
2299
+ for (const piece of splitCommand(command)) {
2300
+ const { program, args, assignments } = parseCommand(piece.command);
2301
+ const tokens = tokenize(piece.command);
2302
+ const declared = DECLARERS.has(program) ? args.filter((arg) => ASSIGNMENT3.test(arg)) : [];
2303
+ for (const assignment of [...assignments, ...declared])
2304
+ add(assignment);
2305
+ if (tokens[0] === "for" && tokens[2] === "in" && tokens[1] !== undefined)
2306
+ variables.set(tokens[1], [...variables.get(tokens[1]) ?? [], ...tokens.slice(3)]);
2307
+ }
2308
+ return variables;
2309
+ }
2310
+ function variantsOf(word, variables) {
2311
+ let found = [word.text];
2312
+ for (let round = 0;round < 4 && found.some((each) => VARIABLE.test(each)); round++) {
2313
+ found = found.flatMap((each) => {
2314
+ const match = VARIABLE.exec(each);
2315
+ const values = variables.get(match?.[1] ?? match?.[2] ?? "");
2316
+ if (match === null || values === undefined)
2317
+ return [each.replace(VARIABLE, "")];
2318
+ return values.map((value) => each.slice(0, match.index) + value + each.slice(match.index + match[0].length));
2319
+ }).slice(0, MAX_VARIANTS);
2320
+ }
2321
+ return found.flatMap((each) => word.hasBrace ? braceExpand(each) : [each]);
2322
+ }
2323
+ function codeReadsEnvFile(code) {
2324
+ return [...code.matchAll(ENV_NAME_IN_CODE)].some((match) => isEnvFile(match[1] ?? "")) && CAN_REACH_FILES.test(code);
2325
+ }
2326
+ function codeReadsEnv(found, heredocs) {
2327
+ const sources = [...found.filter((word, i) => word.isProse || CODE_OPTIONS.has(found[i - 1]?.text ?? "")).map((word) => word.text), ...heredocs];
2328
+ return sources.some((code) => PYTHON_ENVIRON.test(code) || codeReadsEnvFile(code));
2329
+ }
2330
+ function readsEnv(piece, variables) {
2331
+ const { program, args } = parseCommand(piece.command);
2332
+ if (program === "" || HARMLESS.has(program) || program === "git" && GIT_HARMLESS.has(args[0] ?? ""))
2333
+ return false;
2334
+ if (INTERPRETERS.has(program) && codeReadsEnv(words(piece.command), piece.heredocs))
2335
+ return true;
2336
+ if (printsNamesOnly(program, args) || listsFiles(program, args))
2337
+ return false;
2338
+ return namesEnv(piece, variables);
2339
+ }
2340
+ function namesEnv(piece, variables) {
2341
+ const { program, args } = parseCommand(piece.command);
2342
+ const found = words(piece.command);
2343
+ const isExclusion = (word) => program === "git" && GIT_EXCLUDE.test(word.text);
2344
+ const isSearch = GREPS.has(program) || program === "rg" || program === "ag";
2345
+ const patternAt = isSearch ? patternIndex(args, GREPS.has(program) ? GREP_VALUE_OPTIONS : RG_VALUE_OPTIONS) : undefined;
2346
+ const pattern = patternAt === undefined ? undefined : found.length - args.length + patternAt;
2347
+ return found.some((word, index) => index !== pattern && !word.isProse && !isExclusion(word) && variantsOf(word, variables).some((variant) => namesEnvFile(variant, found[index - 1]?.text, word.hasGlob)));
2348
+ }
2349
+
2350
+ // ../env/src/guard-pipes.ts
2351
+ var XARGS_SAFE = new Set(["ls", "stat", "wc", "test", "[", "touch", "echo", "printf", "basename", "dirname", "ev", "redact", ""]);
2352
+ var PARALLEL_VALUE_OPTIONS = new Set(["-j", "--jobs", "-P", "--max-procs", "-S", "--sshlogin", "-C", "--colsep", "-n", "--max-args", "-N", "-d", "--delimiter", "-E", "-I", "--timeout", "--delay", "--joblog", "--results", "--tmpdir", "-a", "--arg-file", "--halt", "--retries", "--tag-string"]);
2353
+ var IDENTIFIER = /^[A-Z_]\w*$/i;
2354
+ var READ_VALUE_OPTIONS = new Set(["-a", "-d", "-i", "-n", "-N", "-p", "-t", "-u"]);
2177
2355
  function listsEnvUpstream(pieces, index, variables) {
2178
2356
  for (let at = index - 1;at >= 0 && pieces[at]?.separator.startsWith("|"); at--) {
2179
2357
  if (namesEnv(pieces[at], variables) || searchesEnvNames(pieces[at]))
@@ -2188,7 +2366,7 @@ function parallelRunner(args) {
2188
2366
  function runnerReadsListedEnv(pieces, index, variables) {
2189
2367
  const command = pieces[index]?.command ?? "";
2190
2368
  const { program, args, isWrapped } = parseCommand(command);
2191
- const isXargs = isWrapped && tokenize(command).includes("xargs");
2369
+ const isXargs = isWrapped && tokenize(command).some((word) => word === "xargs" || word === "parallel");
2192
2370
  if (program !== "parallel" && !isXargs)
2193
2371
  return false;
2194
2372
  return !XARGS_SAFE.has(isXargs ? program : parallelRunner(args)) && listsEnvUpstream(pieces, index, variables);
@@ -2214,6 +2392,11 @@ function loopReadsListedEnv(pieces, index, variables) {
2214
2392
  }
2215
2393
  return false;
2216
2394
  }
2395
+
2396
+ // ../env/src/guard.ts
2397
+ var ENV_DUMP = /(?:console\.\w+|JSON\.stringify|Object\.(?:entries|keys|values)|print)\(\s*process\.env\s*[,)]/;
2398
+ var USE_EV = '.env files hold secrets that must never reach the transcript, so they are not read, edited or printed directly. Use `ev` instead: `ev list`, `ev get KEY` (masked), `ev grep <regex>` for the keys matching it, `ev show <rev>:<file>` for one at a git revision, `printf %s "$value" | ev set KEY [file]` (`--empty` for an empty value), `ev unset KEY`, `ev cp KEY --from .env --to .env.local`, `ev mv KEY --from .env --to .env.local`, `ev diff a b`, `ev missing`; and pipe output that may carry a secret through `redact`, as `docker compose exec <svc> printenv | redact` or `docker compose config | redact`. If `ev` is missing: `bun install -g @kaynooo/cli-env`.';
2399
+ var USE_EV_SEARCH = "To search them, `ev grep <regex>` prints the matching keys, masked. `grep -l`, `-L` and `-c` (file names and counts) are allowed, and a tree-wide search can run as `rg <regex>`, which skips gitignored files, or `grep -r --exclude='.env*' <regex> .`.";
2217
2400
  function touchingPieces(command, options = {}) {
2218
2401
  const pieces = splitCommand(command);
2219
2402
  if (ENV_DUMP.test(command) || substitutions(command).some((each) => touchesEnv(each, options)))
@@ -2295,7 +2478,7 @@ function commitMessageViolation(message) {
2295
2478
  var FOLD_LINES = 150;
2296
2479
 
2297
2480
  // ../out/src/wrap.ts
2298
- var ASSIGNMENT3 = /^\w+=/;
2481
+ var ASSIGNMENT4 = /^\w+=/;
2299
2482
  var EXCLUDED = /(?:^|\s)(?:--json|--help|--version|-h|--watch(?:-?all|=\S*)?|--watchAll)(?:\s|$)/;
2300
2483
  var SHORT_WATCH = /(?:^|\s)(?:\S*\/)?(?:tsc|tsgo|vue-tsc|vitest|jest)\s(?:.*\s)?-w(?:\s|$)/;
2301
2484
  var LONG_RUNNING = /^(?:dev|watch|serve|start|up|run|preview|storybook)(?:[:-]\S*)?$/;
@@ -2396,7 +2579,7 @@ function withoutFilters(command) {
2396
2579
  return { rest, stages };
2397
2580
  }
2398
2581
  function listed2(words) {
2399
- const start = words.findIndex((word) => !ASSIGNMENT3.test(word));
2582
+ const start = words.findIndex((word) => !ASSIGNMENT4.test(word));
2400
2583
  const path = words[start];
2401
2584
  if (path === undefined)
2402
2585
  return false;
@@ -2417,12 +2600,15 @@ function shouldWrap(command) {
2417
2600
  function wrap(command) {
2418
2601
  const { rest, stages } = withoutFilters(command.trim());
2419
2602
  const out = ["out", ...stages.flatMap((stage) => ["--was", shellQuote(stage)]), "--"].join(" ");
2420
- if (scan(rest).segments.length <= 1 && !ASSIGNMENT3.test(rest))
2603
+ if (scan(rest).segments.length <= 1 && !ASSIGNMENT4.test(rest))
2421
2604
  return `${out} ${rest}`;
2422
2605
  return `${out} sh -c ${shellQuote(rest)}`;
2423
2606
  }
2424
2607
 
2425
2608
  // ../pkg/src/added.ts
2609
+ import { existsSync, readdirSync, readFileSync as readFileSync2 } from "fs";
2610
+ import { dirname as dirname3, join as join3 } from "path";
2611
+ import process10 from "process";
2426
2612
  var REDIRECT2 = /^\d*[<>]/;
2427
2613
  var BARE_REDIRECT = /^\d*(?:[<>]|>>)$/;
2428
2614
  var ADDS = {
@@ -2439,27 +2625,62 @@ var RUNS = {
2439
2625
  };
2440
2626
  var RUNNERS = new Set(["bunx", "npx"]);
2441
2627
  var PACKAGE_FLAGS = new Set(["-p", "--package"]);
2442
- var VALUE_FLAGS = new Set(["--cwd", "--filter", "-F", "--workspace", "--registry", "--prefix", "-C", "--dir", "--config", "--cache-dir", "--loglevel", "--tag", "--save-prefix", "--userconfig", "--omit", "--include", "--fetch-timeout", "--fetch-retries", "--install-strategy", "--cache", ...PACKAGE_FLAGS]);
2628
+ var VALUE_FLAGS = new Set(["--cwd", "--filter", "-F", "-c", "--call", "--workspace", "--registry", "--prefix", "-C", "--dir", "--config", "--cache-dir", "--loglevel", "--tag", "--save-prefix", "--userconfig", "--omit", "--include", "--fetch-timeout", "--fetch-retries", "--install-strategy", "--cache", ...PACKAGE_FLAGS]);
2443
2629
  var NOT_REGISTRY = /^(?:[./~]|file:|link:|portal:|workspace:|git[+:]|github:|gitlab:|bitbucket:|https?:)|\.tgz$|^[\w.-]+\/[\w.-]+(?:#.*)?$/;
2444
2630
  var NPM_ALIAS = /^(?:@[^/]+\/)?[^@]+@npm:(.+)$/;
2445
2631
  var PUBLISH = /\b(?:ft|cli\.ts)\s+release\b|\b(?:bun|npm|pnpm|yarn)\s+publish\b|\bjust\s+(?:patch|minor|major)\b/;
2632
+ var EXACT_SPEC = /^(?:@[^/]+\/)?[^@]+@\d+\.\d+\.\d+(?:[-+][\w.+-]+)?$/;
2633
+ function manifestName(folder) {
2634
+ try {
2635
+ const { name } = JSON.parse(readFileSync2(join3(folder, "package.json"), "utf8"));
2636
+ return typeof name === "string" ? name : undefined;
2637
+ } catch {
2638
+ return;
2639
+ }
2640
+ }
2641
+ function ownPackages() {
2642
+ const names = new Set;
2643
+ let folder = process10.cwd();
2644
+ while (true) {
2645
+ const name = manifestName(folder);
2646
+ if (name !== undefined)
2647
+ names.add(name);
2648
+ for (const member of existsSync(join3(folder, "packages")) ? readdirSync(join3(folder, "packages")) : []) {
2649
+ const memberName = manifestName(join3(folder, "packages", member));
2650
+ if (memberName !== undefined)
2651
+ names.add(memberName);
2652
+ }
2653
+ if (existsSync(join3(folder, ".git")) || dirname3(folder) === folder)
2654
+ return names;
2655
+ folder = dirname3(folder);
2656
+ }
2657
+ }
2658
+ function specName(spec) {
2659
+ return spec.slice(0, spec.lastIndexOf("@"));
2660
+ }
2446
2661
  function addedPackages(command) {
2447
2662
  let published = false;
2663
+ let own;
2448
2664
  return splitCommand(command).flatMap((piece) => {
2449
2665
  published ||= PUBLISH.test(piece.command);
2450
2666
  const { program, args } = parseCommand(piece.command);
2451
2667
  const [sub = "", ...rest] = args;
2452
- if (published)
2453
- return [];
2454
- if (RUNNERS.has(program))
2455
- return runnerPackages(args);
2456
- if (RUNS[program]?.has(sub))
2457
- return runnerPackages(rest);
2458
- if (!ADDS[program]?.has(sub))
2459
- return [];
2460
- return rest.flatMap((word, index) => isSkipped(word, rest[index - 1] ?? "") ? [] : registryName(word));
2668
+ const names = piecePackages(program, sub, args, rest);
2669
+ if (!published)
2670
+ return names;
2671
+ own ??= ownPackages();
2672
+ return names.filter((name) => !EXACT_SPEC.test(name) || !own.has(specName(name)));
2461
2673
  });
2462
2674
  }
2675
+ function piecePackages(program, sub, args, rest) {
2676
+ if (RUNNERS.has(program))
2677
+ return runnerPackages(args);
2678
+ if (RUNS[program]?.has(sub))
2679
+ return runnerPackages(rest);
2680
+ if (!ADDS[program]?.has(sub))
2681
+ return [];
2682
+ return rest.flatMap((word, index) => isSkipped(word, rest[index - 1] ?? "") ? [] : registryName(word));
2683
+ }
2463
2684
  function isSkipped(word, previous) {
2464
2685
  return word.startsWith("-") || REDIRECT2.test(word) || VALUE_FLAGS.has(previous) || BARE_REDIRECT.test(previous);
2465
2686
  }
@@ -2564,7 +2785,9 @@ function installRequests(command, cwd, home) {
2564
2785
  let hasLeadingFlag = false;
2565
2786
  for (let i = 0;i < args.length; i++) {
2566
2787
  const arg = args[i] ?? "";
2567
- const [flag = "", value] = arg.split("=", 2);
2788
+ const equals = arg.indexOf("=");
2789
+ const flag = equals === -1 ? arg : arg.slice(0, equals);
2790
+ const value = equals === -1 ? undefined : arg.slice(equals + 1);
2568
2791
  if (DIR_FLAGS.has(flag) && value !== undefined && value !== "") {
2569
2792
  dir = resolvePath(cwd, value, home);
2570
2793
  } else if (VALUE_FLAGS2.has(arg)) {
@@ -2607,6 +2830,7 @@ var WHOLE_TREE = new Set(["-A", "--all", "-u", "--update", "--no-ignore-removal"
2607
2830
  var COMMIT_VALUE_SHORTS = new Set(["m", "F", "c", "C", "t"]);
2608
2831
  var COMMIT_VALUE_LONGS = new Set(["--message", "--file", "--reuse-message", "--reedit-message", "--template", "--author", "--date", "--fixup", "--squash", "--cleanup", "--trailer", "--pathspec-from-file"]);
2609
2832
  var SHORT_CLUSTER = /^-[A-Z]+$/i;
2833
+ var SHORT_OPTIONS = /^-[A-Z]/i;
2610
2834
  var STAGES_ALL = /[Au]/;
2611
2835
  var ALL_TAGS = new Set(["--tags", "--follow-tags"]);
2612
2836
  var TOP_MAGIC = /^:(?:\/|\([^)]*\))/;
@@ -2670,7 +2894,7 @@ function commitsAll(args) {
2670
2894
  i++;
2671
2895
  continue;
2672
2896
  }
2673
- if (!SHORT_CLUSTER.test(arg))
2897
+ if (!SHORT_OPTIONS.test(arg))
2674
2898
  continue;
2675
2899
  for (const [index, flag] of [...arg.slice(1)].entries()) {
2676
2900
  if (flag === "a")
@@ -2734,6 +2958,10 @@ function heredocBody(text, opener) {
2734
2958
  `), rest: lines.slice(end + 1).join(`
2735
2959
  `) };
2736
2960
  }
2961
+ var FD_PATH = /^\/dev\/fd\/\d+$/;
2962
+ function isStdin(file) {
2963
+ return file === "-" || file === "/dev/stdin" || FD_PATH.test(file);
2964
+ }
2737
2965
  function sourceOf(args, text) {
2738
2966
  const source = { parts: [], file: null, stdin: null, isReused: false, hasTrailerFlag: false };
2739
2967
  const take = (option, value) => {
@@ -2762,7 +2990,7 @@ function sourceOf(args, text) {
2762
2990
  take(option, args[++i] ?? "");
2763
2991
  continue;
2764
2992
  }
2765
- if (!SHORT_CLUSTER.test(arg))
2993
+ if (!SHORT_OPTIONS.test(arg))
2766
2994
  continue;
2767
2995
  for (const [index, flag] of [...arg.slice(1)].entries()) {
2768
2996
  if (flag === "s")
@@ -2773,7 +3001,7 @@ function sourceOf(args, text) {
2773
3001
  break;
2774
3002
  }
2775
3003
  }
2776
- if (source.file === "-")
3004
+ if (source.file !== null && isStdin(source.file))
2777
3005
  source.stdin = heredocBody(text, HEREDOC_OPENER)?.body ?? null;
2778
3006
  return source;
2779
3007
  }
@@ -2850,12 +3078,149 @@ function gcLine(command) {
2850
3078
  return ["gc", shellQuote(title), ...options, "--", ...paths.map((path) => shellQuote(path))].join(" ");
2851
3079
  }
2852
3080
 
3081
+ // src/destructive.ts
3082
+ var FETCHERS = new Set(["curl", "wget", "fetch"]);
3083
+ var EVALUATORS = new Set(["eval", "source", "."]);
3084
+ var FETCH_SUBSTITUTION = /(?:\$\(|<\(|`)\s*(?:curl|wget|fetch)\b/;
3085
+ var RECURSIVE_LETTER = /r/i;
3086
+ var HOME_PREFIX = /^(?:~|\$HOME|\$\{HOME(?::?[-?=+][^}]*)?\}?)(?=\/|$)/;
3087
+ var CURRENT_DIRECTORY = /^(?:\$PWD|\$\{PWD\}?|\$\(pwd\)?|`pwd`?)(?=\/|$)/;
3088
+ var SAFE_REBASE = new Set(["--abort", "--continue", "--quit", "--show-current-patch", "--skip", "--edit-todo"]);
3089
+ var INTERPRETERS2 = new Set(["python", "node", "bun", "perl", "ruby"]);
3090
+ var VERSION_SUFFIX = /[\d.]+$/;
3091
+ var PASS_THROUGH = new Set(["tee", "cat", "pv", "tr", "sed"]);
3092
+ var COMMIT_FIRST = "Commit what you want to keep with `gc` first.";
3093
+ var SAFE_BASE = "`base -- <cmd>` runs a command at HEAD with the working tree untouched, and `git worktree add` gives a clean tree.";
3094
+ var RESET_HARD = `Never \`git reset --hard\`: it throws away uncommitted work, and peer sessions edit this tree live. ${COMMIT_FIRST} \`git reset --soft\` or \`--mixed\` moves HEAD and keeps the changes; ${SAFE_BASE}`;
3095
+ var DISCARD_TREE = `Never discard the whole working tree (\`git checkout -- .\`, \`git checkout -f\`, \`git restore .\`, \`git rm -r .\`, \`git switch -f\`): it throws away uncommitted work, and peer sessions edit this tree live. ${COMMIT_FIRST} Restore named paths only, and \`git restore --staged\` just unstages. ${SAFE_BASE}`;
3096
+ var CLEAN = `Never \`git clean -f\`: it deletes untracked files that peer sessions or the user have not committed yet. \`git clean -n\` lists what it would remove; delete named files yourself.`;
3097
+ var FORCE_PUSH = "Never force-push with `--force`, `-f`, `--mirror` or a `+refspec`: it overwrites commits on the remote. When the user asked for one, `git push --force-with-lease` refuses to overwrite what you have not seen.";
3098
+ var REMOTE_DELETE = "Never delete a remote branch or tag with `git push --delete` or `git push origin :ref`: it removes work from the remote for everyone. Ask the user to run it themselves.";
3099
+ var BRANCH_DELETE = "Never `git branch -D`: it drops commits no other branch holds. `git branch -d` deletes a merged branch only; ask the user before dropping an unmerged one.";
3100
+ var REBASE = `Never start a \`git rebase\`: it rewrites history and stops halfway on conflicts in a tree others edit. ${COMMIT_FIRST} \`git cherry-pick\` or \`git merge\` keep history, and \`git worktree add\` gives a clean tree to do it in. \`--continue\` and \`--abort\` stay allowed.`;
3101
+ var REWRITE_HISTORY = "Never `git filter-branch` or `git filter-repo`: they rewrite every commit of the repository. Ask the user to run it themselves.";
3102
+ var BROAD_RM = "Never `rm -r` on `/`, `~`, `$HOME`, `.`, `..`, `*` or a top-level directory: it deletes far more than the task. Name the exact directory, such as `dist` or `node_modules`.";
3103
+ var PIPE_TO_SHELL = 'Never run what `curl`/`wget` fetches straight in a shell (`| sh`, `bash <(curl ...)`, `eval "$(curl ...)"`): it runs code nobody read. Download it to a file, read it, then run it, or hand the command to the user.';
3104
+ function hasOption(args, long, shorts) {
3105
+ for (const arg of args) {
3106
+ if (arg === "--")
3107
+ return false;
3108
+ if (long.includes(arg) || SHORT_CLUSTER.test(arg) && [...arg.slice(1)].some((letter) => shorts.includes(letter)))
3109
+ return true;
3110
+ }
3111
+ return false;
3112
+ }
3113
+ function isBroadPath(path) {
3114
+ const arg = path.replace(CURRENT_DIRECTORY, ".");
3115
+ const home = HOME_PREFIX.exec(arg);
3116
+ const isAbsolute = home === null && arg.startsWith("/");
3117
+ const parts = [];
3118
+ for (const part of (home === null ? arg : arg.slice(home[0].length)).split("/")) {
3119
+ if (part === ".." && parts.length > 0 && parts.at(-1) !== "..")
3120
+ parts.pop();
3121
+ else if (part === ".." && !isAbsolute && home === null)
3122
+ parts.push(part);
3123
+ else if (part !== "" && part !== "." && part !== "..")
3124
+ parts.push(part);
3125
+ }
3126
+ if (parts.at(-1) === "*" || parts.at(-1) === ".*")
3127
+ parts.pop();
3128
+ if (home !== null)
3129
+ return parts.length === 0;
3130
+ return isAbsolute ? parts.length <= 1 : parts.every((part) => part === "..");
3131
+ }
3132
+ function removesBroadly(args) {
3133
+ if (args.includes("--no-preserve-root"))
3134
+ return true;
3135
+ const options = args.slice(0, args.includes("--") ? args.indexOf("--") : args.length);
3136
+ const isRecursive = options.some((arg) => arg === "--recursive" || SHORT_CLUSTER.test(arg) && RECURSIVE_LETTER.test(arg));
3137
+ if (!isRecursive)
3138
+ return false;
3139
+ const targets = args.filter((arg, i) => !arg.startsWith("-") || args.includes("--") && i > args.indexOf("--"));
3140
+ return targets.some(isBroadPath);
3141
+ }
3142
+ function checksOutTree(rest, operands) {
3143
+ if (rest.includes("--"))
3144
+ return operands.some((arg) => arg !== "--" && isWholeTree(arg));
3145
+ return operands.length === 1 ? isWholeTree(operands[0] ?? "") : operands.slice(1).some(isWholeTree);
3146
+ }
3147
+ function gitDestructive(name, rest) {
3148
+ const operands = rest.filter((arg) => !arg.startsWith("-") || arg === "--");
3149
+ if (name === "reset")
3150
+ return rest.includes("--hard") ? RESET_HARD : null;
3151
+ if (name === "checkout" && !hasOption(rest, ["--patch"], "p") && (hasOption(rest, ["--force"], "f") || checksOutTree(rest, operands)))
3152
+ return DISCARD_TREE;
3153
+ if (name === "switch" && hasOption(rest, ["--force", "--discard-changes"], "f"))
3154
+ return DISCARD_TREE;
3155
+ if (name === "restore") {
3156
+ const isStagedOnly = hasOption(rest, ["--staged"], "S") && !hasOption(rest, ["--worktree"], "W");
3157
+ return !isStagedOnly && !hasOption(rest, ["--patch"], "p") && operands.some((arg) => arg !== "--" && isWholeTree(arg)) ? DISCARD_TREE : null;
3158
+ }
3159
+ if (name === "rm")
3160
+ return !hasOption(rest, ["--cached", "--dry-run"], "n") && operands.some((arg) => arg !== "--" && isWholeTree(arg)) ? DISCARD_TREE : null;
3161
+ if (name === "clean")
3162
+ return hasOption(rest, ["--force"], "f") && !hasOption(rest, ["--dry-run"], "n") ? CLEAN : null;
3163
+ if (name === "push") {
3164
+ const isForced = hasOption(rest, ["--force", "--mirror"], "f") || rest.some((arg) => arg.startsWith("--force=") || !arg.startsWith("-") && arg.startsWith("+"));
3165
+ if (isForced)
3166
+ return FORCE_PUSH;
3167
+ return hasOption(rest, ["--delete"], "d") || rest.some((arg) => arg.startsWith(":") && arg.length > 1) ? REMOTE_DELETE : null;
3168
+ }
3169
+ if (name === "branch")
3170
+ return hasOption(rest, [], "D") || hasOption(rest, ["--delete"], "d") && hasOption(rest, ["--force"], "f") ? BRANCH_DELETE : null;
3171
+ if (name === "rebase")
3172
+ return rest.some((arg) => SAFE_REBASE.has(arg)) ? null : REBASE;
3173
+ return name === "filter-branch" || name === "filter-repo" ? REWRITE_HISTORY : null;
3174
+ }
3175
+ function feedsExecutor(stages) {
3176
+ for (const stage of stages) {
3177
+ const { program, args } = parseCommand(stage.command);
3178
+ const hasScript = args.some((arg) => !arg.startsWith("-"));
3179
+ if (SHELLS.has(program))
3180
+ return !hasOption(args, [], "n") && (!hasScript || args.includes("-s"));
3181
+ if (INTERPRETERS2.has(program.replace(VERSION_SUFFIX, "")))
3182
+ return !hasScript;
3183
+ if (!PASS_THROUGH.has(program) || stage.separator !== "|")
3184
+ return false;
3185
+ }
3186
+ return false;
3187
+ }
3188
+ function runsDownload(command) {
3189
+ const pieces = splitCommand(command);
3190
+ return pieces.some((piece, index) => {
3191
+ const { program } = parseCommand(piece.command);
3192
+ if (FETCHERS.has(program) && piece.separator === "|")
3193
+ return feedsExecutor(pieces.slice(index + 1));
3194
+ return (SHELLS.has(program) || EVALUATORS.has(program)) && FETCH_SUBSTITUTION.test(piece.command);
3195
+ });
3196
+ }
3197
+ function destructiveViolation(command) {
3198
+ if (runsDownload(command))
3199
+ return PIPE_TO_SHELL;
3200
+ for (const piece of splitCommand(command)) {
3201
+ const { program, args } = parseCommand(piece.command);
3202
+ if (program === "rm" && removesBroadly(args))
3203
+ return BROAD_RM;
3204
+ if (program !== "git")
3205
+ continue;
3206
+ const { name, rest } = subcommandOf(args);
3207
+ const violation = gitDestructive(name, rest);
3208
+ if (violation !== null)
3209
+ return violation;
3210
+ }
3211
+ return null;
3212
+ }
3213
+
2853
3214
  // src/remote.ts
2854
3215
  var SHELL_PROGRAMS = new Set(["ssh", "scp", "sftp", "mosh", "mosh-client", "autossh"]);
2855
3216
  var SOCKET_PROGRAMS = new Set(["nc", "ncat", "netcat", "telnet", "socat"]);
2856
3217
  var URL_PROGRAMS = new Set(["git", "docker", "docker-compose"]);
2857
3218
  var DECLARERS2 = new Set(["export", "declare", "typeset"]);
2858
3219
  var RSYNC_REMOTE = /^(?:[\w.-]+@)?[\w.-]{2,}:/;
3220
+ var SCP_ADDRESS = /^[^/:\s-][^/:\s]*:(?!\/\/)/;
3221
+ var SCP_HOST_ADDRESS = /^(?:[\w.-]+@[\w.-]+|[\w-]+(?:\.[\w-]+)+):(?!\/\/)/;
3222
+ var GIT_TRANSPORTS = new Set(["clone", "fetch", "pull", "push", "ls-remote"]);
3223
+ var TRANSPORT_VALUE_OPTIONS = new Set(["--depth", "-b", "--branch", "-o", "--origin", "--push-option", "-c", "--config", "--reference", "--separate-git-dir", "--template", "-j", "--jobs", "--filter", "--shallow-since", "--shallow-exclude", "-u", "--upload-pack", "--receive-pack", "--exec", "--server-option", "--repo", "--deepen"]);
2859
3224
  var SSH_URL = /^ssh:\/\//;
2860
3225
  var SSH_URL_WORD = /^(?:[\w-]+=)?ssh:\/\//;
2861
3226
  var LOOPBACK = /(?:^|[:=@[])(?:localhost|127(?:\.\d+){3}|::1)(?:[:\]/]|$)/;
@@ -2890,6 +3255,24 @@ function isDockerRemote(args, assignments) {
2890
3255
  function isSocketRemote(args) {
2891
3256
  return !args.some((arg) => LISTENS.test(arg) || LOOPBACK.test(arg));
2892
3257
  }
3258
+ function firstOperand2(args) {
3259
+ for (let i = 0;i < args.length; i++) {
3260
+ const arg = args[i] ?? "";
3261
+ if (TRANSPORT_VALUE_OPTIONS.has(arg))
3262
+ i++;
3263
+ else if (!arg.startsWith("-"))
3264
+ return arg;
3265
+ }
3266
+ return;
3267
+ }
3268
+ function isScpAddress(args) {
3269
+ const { name, rest } = subcommandOf(args);
3270
+ if (!GIT_TRANSPORTS.has(name))
3271
+ return false;
3272
+ const address = name === "clone" || name === "ls-remote" ? SCP_ADDRESS : SCP_HOST_ADDRESS;
3273
+ const repository = firstOperand2(rest);
3274
+ return repository !== undefined && address.test(repository);
3275
+ }
2893
3276
  function isRemote(text) {
2894
3277
  const { program, args, assignments } = parseCommand(text);
2895
3278
  const declared = DECLARERS2.has(program) ? args : [];
@@ -2899,6 +3282,8 @@ function isRemote(text) {
2899
3282
  return isSocketRemote(args);
2900
3283
  if (program === "rsync")
2901
3284
  return args.some((arg) => !arg.startsWith("-") && RSYNC_REMOTE.test(arg));
3285
+ if (program === "git" && isScpAddress(args))
3286
+ return true;
2902
3287
  if (program === "kubectl")
2903
3288
  return args.some((arg) => KUBECTL_SERVER.test(arg));
2904
3289
  if ([...assignments, ...declared].some((assignment) => REMOTE_VARIABLE.test(assignment)))
@@ -3271,13 +3656,13 @@ function commitViolation(command, { cwd, read }) {
3271
3656
  for (const source of commitSources(command)) {
3272
3657
  if (source.hasTrailerFlag)
3273
3658
  return TRAILERS;
3274
- if (source.isReused || source.file?.startsWith("/dev/") === true)
3275
- continue;
3276
3659
  const { file } = source;
3660
+ if (source.isReused || file?.startsWith("/dev/") === true && !isStdin(file))
3661
+ continue;
3277
3662
  let message = source.stdin;
3278
3663
  if (file === null)
3279
3664
  message = inlineMessage(source.parts);
3280
- else if (file !== "-")
3665
+ else if (!isStdin(file))
3281
3666
  message = read(absolute(file, cwd));
3282
3667
  if (message === null && (source.parts.length > 0 || file !== null))
3283
3668
  return UNREADABLE_MESSAGE;
@@ -3302,6 +3687,10 @@ function mismatches(command, { cwd, home, exists }) {
3302
3687
  return mismatch === null ? [] : [mismatch];
3303
3688
  });
3304
3689
  }
3690
+ function nestedMismatches(run, context, own) {
3691
+ const ownTexts = new Set(own.map((mismatch) => mismatch.piece.command.trim()));
3692
+ return run.slice(1).flatMap((each) => mismatches(each, context)).filter((mismatch) => !ownTexts.has(mismatch.piece.command.trim())).map((mismatch) => ({ ...mismatch, rewrite: null }));
3693
+ }
3305
3694
  async function checkCommand(command, context) {
3306
3695
  const violations = [];
3307
3696
  const notes = [];
@@ -3322,6 +3711,7 @@ async function checkCommand(command, context) {
3322
3711
  const readSql = async (path) => Promise.resolve(context.read(absolute(path, context.cwd)));
3323
3712
  add("remote", await guarded("remote", () => first(run.map(remoteViolation))));
3324
3713
  add("git", await guarded("git", () => first(run.map((each) => gitViolation(each, context.isPushAsked)))));
3714
+ add("destructive", await guarded("destructive", () => first(run.map(destructiveViolation))));
3325
3715
  const commit = await guarded("commit", () => first(run.map((each) => commitViolation(each, context))));
3326
3716
  add("commit", commit === null ? null : `${commit} ${USE_GC}`);
3327
3717
  add("sql", await guarded("sql", async () => first(await Promise.all(run.map(async (each) => sqlViolation(each, readSql))))));
@@ -3333,7 +3723,7 @@ async function checkCommand(command, context) {
3333
3723
  }));
3334
3724
  add("edit", context.canSub ? await guarded("edit", () => first(run.map(replaceViolation))) : null);
3335
3725
  const found = mismatches(command, context);
3336
- const refused = found.find((mismatch) => mismatch.rewrite === null || !context.canRewrite);
3726
+ const refused = [...found, ...nestedMismatches(run, context, found)].find((mismatch) => mismatch.rewrite === null || !context.canRewrite);
3337
3727
  const rewrite = refused?.rewrite ?? null;
3338
3728
  const route = rewrite === null ? "Run it with the pinned manager instead." : `Run \`${rewrite.trim()}\` instead.`;
3339
3729
  add("package-manager", refused === undefined ? null : `${refused.reason} ${route}`);
@@ -3352,8 +3742,8 @@ function checkPath(path) {
3352
3742
 
3353
3743
  // src/bins.ts
3354
3744
  var BINS = {
3355
- check: "`check`: runs the repo's check, typecheck, lint and test steps (package.json, composer.json and PHP tool configs, a Justfile, a Makefile) and prints only what failed, each full log saved to a file; a step runs inside the running compose service that mounts its folder (`--in <service>`, `--host`), never starting one; validate a change with it rather than chaining the scripts or `docker compose exec` by hand (`--only lint,test`, `--list`, `--slot`).",
3356
- fix: "`fix`: runs the repo's fixers and formatters (its fix, lint:fix and format scripts, php-cs-fixer, just fmt, go fmt, cargo fmt, ruff), in the compose service like `check`, and lists the files they changed.",
3745
+ check: "`check`: runs the repo's check, typecheck, lint and test steps (package.json, composer.json and PHP tool configs, a Justfile, a Makefile) and prints only what failed, each full log saved to a file; a step runs inside the running compose service that mounts its folder (`--in <service>`, `--host`), never starting one; validate a change with it rather than chaining the scripts or `docker compose exec` by hand (`--only lint,test`, `--list`, `--slot`, `--failed` to re-run what failed last, `--fix` for the fixers).",
3746
+ fix: "`fix` (the alias of `check --fix`): runs the repo's fixers and formatters (its fix, lint:fix and format scripts, php-cs-fixer, just fmt, go fmt, cargo fmt, ruff), in the compose service like `check`, and lists the files they changed.",
3357
3747
  errs: "`errs [log]`, `errs -- <cmd>`: turns tsc, tsgo, eslint, bun check, bun test, vitest, playwright, phpunit, phpstan and php-cs-fixer output into one `file:line:col: message (rule)` line per error, counting the lines it did not recognise (`--json`); use it instead of reading raw type, lint or test logs.",
3358
3748
  db: '`db "<sql>"`: one read-only statement against the Postgres, MySQL or MariaDB in DATABASE_URL (`-e KEY` for another) or, without one, the compose project\'s running database service (`-s <service>`, `-c <container>` for any container, `-d <database>`), credentials never shown; a write runs on a database whose name ends in `_test` and is printed for the user to run otherwise; `db tables`, `db describe <table>`, `db dbs`; use it instead of `docker exec <container> psql` or `mysql`.',
3359
3749
  ev: "`ev`: .env files read and edited with values masked (`ev list`, `ev get KEY`, `ev grep <regex>`, `ev show <rev>:<file>`, `ev set`, `ev diff`, `ev missing`); `ev audit [dir]` finds env files others can read or git tracks, and compose files writing secrets out; `ev pins [dir]` lists the env vars reaching outside that the tests of an app leave unpinned.",
@@ -3476,10 +3866,24 @@ async function hook(event, input, machine) {
3476
3866
  return event === "user-prompt-submit" ? userPromptSubmit(input, machine) : sessionStart(machine);
3477
3867
  }
3478
3868
 
3869
+ // src/rules.ts
3870
+ var LISTED = [
3871
+ { name: "remote", refuses: "ssh, scp, rsync and deploys to a remote machine", route: "hand the command to the user" },
3872
+ { name: "git", refuses: "stash, whole-tree add and commit, push without being asked, tags", route: "stage by path with `gc`, push only when asked" },
3873
+ { name: "destructive", refuses: "reset --hard, discarding the tree, clean -f, force push, branch -D, rebase, filter-branch, rm -r on a broad path, curl piped to a shell", route: "commit with `gc` first, `base`, `git worktree add`, `--force-with-lease` only when asked" },
3874
+ { name: "commit", refuses: "a commit message breaking the format, an unreadable one, trailers", route: "`gc <title> -m <line> -- <path>...`" },
3875
+ { name: "sql", refuses: "SQL writes and DDL, a file the client cannot read", route: '`db "<sql>"`, writes on a `*_test` database or handed over' },
3876
+ { name: "env", refuses: "reading or printing an env file, a diff of a tracked one", route: "`ev`, and `rg` for a tree-wide search" },
3877
+ { name: "edit", refuses: "sed -i and replace scripts", route: "`sub` (only while `sub` is installed)" },
3878
+ { name: "package-manager", refuses: "a manager other than the repo's lockfile pins", route: "the pinned manager, rewritten by `guard check`, named by `guard hook`" },
3879
+ { name: "pkg", refuses: "an install `pkg check` refuses or cannot check", route: "`pkg <name>` before adding it", runs: "hook" }
3880
+ ];
3881
+ var RULES2 = LISTED.map((rule) => ({ runs: "check and hook", ...rule }));
3882
+
3479
3883
  // src/cli.ts
3480
3884
  var checkUsage = `guard check [options] [<command> | -]
3481
3885
 
3482
- Checks a shell command against the rules: remote machines, git (stash, whole-tree add and commit, push, tags), commit messages, SQL writes, env files, package managers and in-place edits (sed -i and replace scripts, pointed at sub).
3886
+ Checks a shell command against the rules: remote machines, git (stash, whole-tree add and commit, push, tags), destructive commands (reset --hard, force push, rebase, broad rm), commit messages, SQL writes, env files, package managers and in-place edits (sed -i and replace scripts, pointed at sub).
3483
3887
  Prints each broken rule with the route to take instead and exits 1, prints nothing and exits 0 when the command is clean.
3484
3888
  The command is read from stdin with - or when none is given; a rule may rewrite it instead (the pinned package manager, a noisy run through out), printed as \`runs as: <command>\`.
3485
3889
 
@@ -3509,7 +3913,7 @@ var MAX_READ = 1e6;
3509
3913
  function readText(path) {
3510
3914
  try {
3511
3915
  const stats = statSync(path, { throwIfNoEntry: false });
3512
- return stats?.isFile() === true && stats.size <= MAX_READ ? readFileSync(path, "utf8") : null;
3916
+ return stats?.isFile() === true && stats.size <= MAX_READ ? readFileSync3(path, "utf8") : null;
3513
3917
  } catch {
3514
3918
  return null;
3515
3919
  }
@@ -3528,14 +3932,14 @@ ${checkUsage}`);
3528
3932
  const given = positionals[0] ?? "-";
3529
3933
  const command = given === "-" ? await readInput("-", { noStdin: "give the command, or pipe it on stdin" }) : given;
3530
3934
  const context = {
3531
- cwd: values.cwd ?? process7.cwd(),
3532
- home: homedir(),
3935
+ cwd: values.cwd ?? process11.cwd(),
3936
+ home: homedir2(),
3533
3937
  isPushAsked: values["push-asked"] === true,
3534
3938
  canRewrite: true,
3535
3939
  canWrap: values["no-wrap"] !== true && Bun.which("out") !== null,
3536
3940
  canSub: Bun.which("sub") !== null,
3537
3941
  read: readText,
3538
- exists: existsSync
3942
+ exists: existsSync2
3539
3943
  };
3540
3944
  const verdict = await checkCommand(command, context);
3541
3945
  if (values.json === true)
@@ -3560,25 +3964,44 @@ ${pathUsage}`);
3560
3964
  report(violations);
3561
3965
  return violations.length > 0 ? 1 : 0;
3562
3966
  }
3967
+ var rulesUsage = `guard rules [--json]
3968
+
3969
+ Lists every rule \`guard check\` and \`guard hook\` apply: its name as a violation carries it, what it refuses, the route its refusal points at and where it runs.
3970
+
3971
+ Exits 0 once it listed them.`;
3972
+ var rulesOptions = {
3973
+ json: jsonOption("[{name, refuses, route, runs}]")
3974
+ };
3975
+ function rules(args) {
3976
+ const parsed = parse(args, rulesUsage, rulesOptions);
3977
+ if (parsed.values.json === true) {
3978
+ console.log(JSON.stringify(RULES2));
3979
+ return 0;
3980
+ }
3981
+ for (const rule of RULES2)
3982
+ console.log(`${rule.name.padEnd(16)} ${rule.refuses}
3983
+ ${" ".repeat(16)} -> ${rule.route}${rule.runs === "hook" ? " (hook only)" : ""}`);
3984
+ return 0;
3985
+ }
3563
3986
  function machine() {
3564
- const home = homedir();
3565
- const stateDir = `${process7.env.XDG_STATE_HOME ?? `${home}/.local/state`}/guard`;
3987
+ const home = homedir2();
3988
+ const stateDir = `${stateHome()}/guard`;
3566
3989
  return {
3567
3990
  home,
3568
3991
  stateDir,
3569
3992
  has: (bin) => Bun.which(bin) !== null,
3570
3993
  run: async (argv, cwd) => runCommand(argv, { cwd }),
3571
3994
  read: readText,
3572
- exists: existsSync,
3995
+ exists: existsSync2,
3573
3996
  write: (path, text) => {
3574
- mkdirSync(dirname(path), { recursive: true });
3997
+ mkdirSync2(dirname4(path), { recursive: true });
3575
3998
  writeFileSync(path, text);
3576
3999
  },
3577
4000
  remove: (path) => rmSync(path, { force: true }),
3578
4001
  log: (text) => {
3579
4002
  try {
3580
- mkdirSync(stateDir, { recursive: true });
3581
- appendFileSync(`${stateDir}/errors.log`, text);
4003
+ mkdirSync2(stateDir, { recursive: true });
4004
+ appendFileSync2(`${stateDir}/errors.log`, text);
3582
4005
  } catch {}
3583
4006
  }
3584
4007
  };
@@ -3595,15 +4018,16 @@ ${hookUsage}`, 1);
3595
4018
  console.log(JSON.stringify(reply));
3596
4019
  return 0;
3597
4020
  }
3598
- process7.exitCode = await runCli({
4021
+ process11.exitCode = await runCli({
3599
4022
  name: "guard",
3600
- version,
4023
+ usage: false,
3601
4024
  about: "the safety rules a Claude Code Bash call is held to, each refusal naming the route",
3602
4025
  replaces: "a hook script per rule, each wording its own refusal",
3603
4026
  examples: [['guard check "git push --force"', "the rules a command breaks, with their routes"], ["guard path .env", "whether a file tool may open a path"]],
3604
4027
  commands: {
3605
4028
  check: { run: check, summary: "check a shell command, printing each broken rule with its route" },
3606
4029
  path: { run: async (args) => Promise.resolve(path(args)), summary: "check a path a file tool would open" },
4030
+ rules: { run: async (args) => Promise.resolve(rules(args)), summary: "list every rule with what it refuses and its route" },
3607
4031
  hook: { run: hookCommand, summary: "answer a Claude Code hook event, JSON in and out" }
3608
4032
  },
3609
4033
  defaultCommand: "check"