@kaynooo/cli-workspace 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/audit-cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/audit-cli.ts
5
- import process15 from "process";
5
+ import process17 from "process";
6
6
 
7
7
  // ../kit/src/advisory.ts
8
8
  var SEVERITIES = ["low", "moderate", "high", "critical"];
@@ -13,14 +13,35 @@ function isIgnored(advisory, ignore) {
13
13
  return ignore.includes(advisory.ghsa ?? "") || ignore.includes(String(advisory.id));
14
14
  }
15
15
  // ../kit/src/args.ts
16
- import process8 from "process";
16
+ import process9 from "process";
17
17
  import { parseArgs } from "util";
18
18
 
19
19
  // ../kit/src/format.ts
20
- import process6 from "process";
20
+ import process7 from "process";
21
+
22
+ // ../kit/src/mode.ts
23
+ import process2 from "process";
24
+ var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
25
+ var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
26
+ function isSet(value) {
27
+ return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
28
+ }
29
+ function outputMode(stream = process2.stdout, env = process2.env) {
30
+ const chosen = env.KIT_MODE;
31
+ if (chosen !== undefined && MODES.has(chosen))
32
+ return chosen;
33
+ if (AGENT_VARIABLES.some((name) => isSet(env[name])))
34
+ return "agent";
35
+ if (stream.isTTY === true)
36
+ return "terminal";
37
+ return isSet(env.CI) ? "ci" : "pipe";
38
+ }
39
+ function isInteractive(streams = process2) {
40
+ return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
41
+ }
21
42
 
22
43
  // ../kit/src/style.ts
23
- import process5 from "process";
44
+ import process6 from "process";
24
45
 
25
46
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
26
47
  function x(s) {
@@ -287,13 +308,13 @@ var t = le();
287
308
  import { existsSync as existsSync3, readFileSync, statSync } from "fs";
288
309
  import { homedir as homedir2 } from "os";
289
310
  import { join as join3, resolve as resolve2 } from "path";
290
- import process4 from "process";
311
+ import process5 from "process";
291
312
 
292
313
  // ../kit/src/config.ts
293
314
  import { existsSync } from "fs";
294
315
  import { dirname, join, resolve } from "path";
295
- import process2 from "process";
296
- function findUp(names, from = process2.cwd(), stop = () => false) {
316
+ import process3 from "process";
317
+ function findUp(names, from = process3.cwd(), stop = () => false) {
297
318
  const wanted = typeof names === "string" ? [names] : names;
298
319
  for (let dir = resolve(from);; dir = dirname(dir)) {
299
320
  const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
@@ -308,9 +329,9 @@ function findUp(names, from = process2.cwd(), stop = () => false) {
308
329
  import { existsSync as existsSync2 } from "fs";
309
330
  import { homedir } from "os";
310
331
  import { join as join2 } from "path";
311
- import process3 from "process";
332
+ import process4 from "process";
312
333
  function configBase(where = {}) {
313
- const xdg = where.xdg ?? (where.home === undefined ? process3.env.XDG_CONFIG_HOME : undefined);
334
+ const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
314
335
  return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
315
336
  }
316
337
  function userConfigPath(bin, where = {}) {
@@ -350,10 +371,30 @@ function isColorSpec(spec) {
350
371
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
351
372
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
352
373
  }
353
- function tinted(colors, spec) {
374
+ var CUBE = [0, 95, 135, 175, 215, 255];
375
+ function cubeLevel(channel) {
376
+ return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
377
+ }
378
+ function nearest256(hex) {
379
+ const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
380
+ const levels = rgb.map(cubeLevel);
381
+ const cube = levels.map((level) => CUBE[level]);
382
+ const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
383
+ const greyValue = 8 + grey * 10;
384
+ const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
385
+ return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
386
+ }
387
+ function hasTrueColor(env) {
388
+ return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
389
+ }
390
+ function tinted(colors, spec, env = process5.env) {
354
391
  if (typeof spec === "number")
355
392
  return colors.ansi256(spec);
356
- return spec.trim().split(SPACES).reduce((chain, token) => HEX.test(token) ? chain.hex(token) : chain[token] ?? chain, colors);
393
+ return spec.trim().split(SPACES).reduce((chain, token) => {
394
+ if (HEX.test(token))
395
+ return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
396
+ return chain[token] ?? chain;
397
+ }, colors);
357
398
  }
358
399
  function isRecord(value) {
359
400
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -437,7 +478,7 @@ function warnOnce(message) {
437
478
  function isPath(chosen) {
438
479
  return chosen.includes("/") || chosen.endsWith(".json");
439
480
  }
440
- function loadTheme({ env = process4.env, from = process4.cwd(), home = homedir2(), warn = warnOnce } = {}) {
481
+ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
441
482
  const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
442
483
  const sources = [];
443
484
  const chosen = env.KIT_THEME ?? "";
@@ -467,7 +508,7 @@ function loadTheme({ env = process4.env, from = process4.cwd(), home = homedir2(
467
508
  var current;
468
509
  var currentKey = "";
469
510
  function activeTheme() {
470
- const key = `${process4.cwd()}\x00${process4.env.KIT_THEME ?? ""}\x00${process4.env.XDG_CONFIG_HOME ?? ""}`;
511
+ const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
471
512
  if (current === undefined || key !== currentKey) {
472
513
  current = loadTheme();
473
514
  currentKey = key;
@@ -477,38 +518,38 @@ function activeTheme() {
477
518
 
478
519
  // ../kit/src/style.ts
479
520
  var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:" };
480
- function takesControlCodes(stream, env = process5.env) {
481
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
521
+ function takesControlCodes(stream, env = process6.env) {
522
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
482
523
  }
483
- function paint(stream, env = process5.env) {
524
+ function paint(stream, env = process6.env) {
484
525
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
485
526
  }
486
- function marked(mark, text, stream, detail, env = process5.env) {
527
+ function marked(mark, text, stream, detail, env = process6.env) {
487
528
  const colors = paint(stream, env);
488
529
  let head = MARK_WORDS[mark];
489
530
  if (takesControlCodes(stream, env)) {
490
531
  const { theme } = activeTheme();
491
- head = tinted(colors.bold, theme.colors[mark])(theme.glyphs[mark]);
532
+ head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
492
533
  }
493
534
  return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
494
535
  }
495
536
  function ok(text, detail) {
496
- console.log(marked("ok", text, process5.stdout, detail));
537
+ console.log(marked("ok", text, process6.stdout, detail));
497
538
  }
498
539
  function note(text, detail) {
499
- console.log(marked("note", text, process5.stdout, detail));
540
+ console.log(marked("note", text, process6.stdout, detail));
500
541
  }
501
542
  function problem(text, detail) {
502
- console.error(marked("problem", text, process5.stderr, detail));
543
+ console.error(marked("problem", text, process6.stderr, detail));
503
544
  }
504
- function role(name, stream, env = process5.env) {
545
+ function role(name, stream, env = process6.env) {
505
546
  const colors = paint(stream, env);
506
- return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name]) : colors;
547
+ return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
507
548
  }
508
549
  var STATUS_WORDS = {
509
550
  passed: ["passed", "success", "succeeded", "ok"],
510
551
  failed: ["failed", "failure", "error", "errored"],
511
- running: ["running", "in_progress", "started"],
552
+ running: ["running", "in_progress", "started", "holding"],
512
553
  queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
513
554
  skipped: ["skipped", "cancelled", "canceled", "manual"]
514
555
  };
@@ -551,8 +592,11 @@ var ESCAPE = String.fromCharCode(27);
551
592
  function textWidth(text) {
552
593
  return Bun.stringWidth(text);
553
594
  }
554
- function table(rows, { cellWidth, header = false, align = [], fit, stream = process6.stdout } = {}) {
595
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
555
596
  const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
597
+ if (outputMode(stream, env) === "agent")
598
+ return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
599
+ `);
556
600
  const widths = [];
557
601
  for (const row of cells) {
558
602
  for (const [index, cell] of row.entries())
@@ -587,32 +631,35 @@ function narrow(rows, widths, limit) {
587
631
  }
588
632
  return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
589
633
  }
634
+ function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
635
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
636
+ }
590
637
  function printJson(value) {
591
- console.log(JSON.stringify(value, undefined, 2));
638
+ console.log(jsonText(value));
592
639
  }
593
640
 
594
641
  // ../kit/src/help.ts
595
- import process7 from "process";
642
+ import process8 from "process";
596
643
  var OPTIONAL = /\[[^\]]+\]/g;
597
644
  var USAGE_PREFIX = /^usage:\s*/i;
598
645
  var FULL_STOP = /\.$/;
599
- function usageLine(usage, colors = paint(process7.stdout)) {
646
+ function usageLine(usage, colors = paint(process8.stdout)) {
600
647
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
601
648
  }
602
- function helpText(usage, options, colors = paint(process7.stdout), { examples = [], replaces, exits = [] } = {}) {
649
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
603
650
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
604
651
  `);
605
652
  }
606
- function exitRows(exits, colors = paint(process7.stdout)) {
653
+ function exitRows(exits, colors = paint(process8.stdout)) {
607
654
  if (exits.length === 0)
608
655
  return [];
609
656
  const width = Math.max(...exits.map(([code]) => String(code).length));
610
657
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
611
658
  }
612
- function replacesRows(replaces, colors = paint(process7.stdout)) {
613
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
659
+ function replacesRows(replaces, colors = paint(process8.stdout)) {
660
+ return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
614
661
  }
615
- function wantsHelpJson(env = process7.env) {
662
+ function wantsHelpJson(env = process8.env) {
616
663
  return env.KIT_HELP === "json";
617
664
  }
618
665
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -631,12 +678,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
631
678
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
632
679
  };
633
680
  }
634
- function exampleRows(examples, colors = paint(process7.stdout)) {
635
- if (examples.length === 0)
681
+ function exampleRows(examples, colors = paint(process8.stdout)) {
682
+ if (examples.length === 0 || outputMode() === "agent")
636
683
  return [];
637
684
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
638
685
  }
639
- function optionRows(options, colors = paint(process7.stdout)) {
686
+ function optionRows(options, colors = paint(process8.stdout)) {
640
687
  const rows = Object.entries(options).map(([name, option]) => {
641
688
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
642
689
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -729,7 +776,7 @@ var OUTPUT_OPTIONS = {
729
776
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
730
777
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
731
778
  };
732
- function applyOutput(color, plain, env = process8.env) {
779
+ function applyOutput(color, plain, env = process9.env) {
733
780
  const when = plain === true ? "never" : color ?? "auto";
734
781
  if (when === "auto")
735
782
  return;
@@ -900,7 +947,7 @@ function nearestOption(message, options, allowNegative) {
900
947
  }
901
948
  // ../kit/src/process.ts
902
949
  import { constants } from "os";
903
- import process9 from "process";
950
+ import process10 from "process";
904
951
  var KILL_GRACE_MS = 2000;
905
952
  function exitCodeOf(code, signal) {
906
953
  if (code !== null)
@@ -920,7 +967,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
920
967
  return;
921
968
  try {
922
969
  if (grouped)
923
- process9.kill(-proc.pid, killing);
970
+ process10.kill(-proc.pid, killing);
924
971
  else
925
972
  proc.kill(killing);
926
973
  } catch {}
@@ -995,10 +1042,10 @@ var RESET_STYLE = `${ESC}[0m`;
995
1042
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
996
1043
 
997
1044
  // ../kit/src/tool.ts
998
- import process10 from "process";
1045
+ import process11 from "process";
999
1046
  function cwdGone() {
1000
1047
  try {
1001
- process10.cwd();
1048
+ process11.cwd();
1002
1049
  return false;
1003
1050
  } catch {
1004
1051
  return true;
@@ -1020,7 +1067,7 @@ function spawnFailure(command, error) {
1020
1067
  async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
1021
1068
  let ran;
1022
1069
  try {
1023
- ran = await runCommand(argv, { env: process10.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
1070
+ ran = await runCommand(argv, { env: process11.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
1024
1071
  } catch (error) {
1025
1072
  throw spawnFailure(label, error);
1026
1073
  }
@@ -1037,13 +1084,13 @@ async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
1037
1084
  // ../kit/src/cli.ts
1038
1085
  import { readFileSync as readFileSync2, realpathSync } from "fs";
1039
1086
  import { dirname as dirname3, join as join5 } from "path";
1040
- import process12 from "process";
1087
+ import process13 from "process";
1041
1088
 
1042
1089
  // ../kit/src/usage.ts
1043
1090
  import { appendFileSync, mkdirSync } from "fs";
1044
1091
  import { homedir as homedir3 } from "os";
1045
1092
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1046
- import process11 from "process";
1093
+ import process12 from "process";
1047
1094
 
1048
1095
  // ../kit/src/logs.ts
1049
1096
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -1057,14 +1104,14 @@ var usageError;
1057
1104
  function noteUsageError(message) {
1058
1105
  usageError = message;
1059
1106
  }
1060
- function stateHome(env = process11.env) {
1107
+ function stateHome(env = process12.env) {
1061
1108
  const dir = env.XDG_STATE_HOME;
1062
1109
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1063
1110
  }
1064
- function usagePath(env = process11.env) {
1111
+ function usagePath(env = process12.env) {
1065
1112
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1066
1113
  }
1067
- function usageRecorded(env = process11.env) {
1114
+ function usageRecorded(env = process12.env) {
1068
1115
  const off = env.KAYNOOO_CLI_NO_USAGE;
1069
1116
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1070
1117
  }
@@ -1078,7 +1125,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
1078
1125
  usageError = undefined;
1079
1126
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1080
1127
  }
1081
- function recordUsage(entry, env = process11.env) {
1128
+ function recordUsage(entry, env = process12.env) {
1082
1129
  if (!usageRecorded(env))
1083
1130
  return;
1084
1131
  try {
@@ -1169,8 +1216,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1169
1216
  `);
1170
1217
  }
1171
1218
  function printError(prefix, message, hint, cause) {
1172
- const colors = paint(process12.stderr);
1173
- const styled = takesControlCodes(process12.stderr);
1219
+ const colors = paint(process13.stderr);
1220
+ const styled = takesControlCodes(process13.stderr);
1174
1221
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1175
1222
  const under = (label, text, tint) => text === undefined ? "" : `
1176
1223
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1213,11 +1260,11 @@ async function dispatch(level, typed, { version, redact }) {
1213
1260
  }
1214
1261
  }
1215
1262
  if (name === undefined && level.path.length > 1) {
1216
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stderr));
1263
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
1217
1264
  return 2;
1218
1265
  }
1219
1266
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1220
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stdout));
1267
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1221
1268
  return 0;
1222
1269
  }
1223
1270
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1344,7 +1391,7 @@ function packageVersion(entry = Bun.main) {
1344
1391
  return "0.0.0";
1345
1392
  }
1346
1393
  }
1347
- async function runCli(cli, argv = process12.argv.slice(2)) {
1394
+ async function runCli(cli, argv = process13.argv.slice(2)) {
1348
1395
  const version = cli.version ?? packageVersion();
1349
1396
  if (argv[0] === COMPLETE)
1350
1397
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -1371,7 +1418,7 @@ function commandPath(scope, argv) {
1371
1418
  }
1372
1419
  return path.length === 0 ? undefined : path.join(" ");
1373
1420
  }
1374
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1421
+ async function runMain({ name, version, run, redact, usage }, argv = process13.argv.slice(2)) {
1375
1422
  if (argv[0] === COMPLETE)
1376
1423
  return printCandidates(leafCandidates(run, argv.slice(1)));
1377
1424
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1391,6 +1438,19 @@ async function runMain({ name, version, run, redact, usage }, argv = process12.a
1391
1438
  }
1392
1439
  return code;
1393
1440
  }
1441
+ // ../kit/src/pool.ts
1442
+ async function pool(items, limit, task) {
1443
+ const results = Array.from({ length: items.length });
1444
+ let next = 0;
1445
+ async function worker() {
1446
+ while (next < items.length) {
1447
+ const index = next++;
1448
+ results[index] = await task(items[index]);
1449
+ }
1450
+ }
1451
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1452
+ return results;
1453
+ }
1394
1454
  // ../kit/src/secrets.ts
1395
1455
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1396
1456
  // ../kit/src/sessions.ts
@@ -1407,15 +1467,41 @@ function parseSize(text, bareUnit = 1) {
1407
1467
  const suffix = match[2].toLowerCase();
1408
1468
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1409
1469
  }
1470
+ // ../kit/src/workspace-root.ts
1471
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
1472
+ import { homedir as homedir4 } from "os";
1473
+ import { dirname as dirname4, join as join6, resolve as resolve3 } from "path";
1474
+ import process14 from "process";
1475
+ function expandHome(path, home) {
1476
+ if (path === "~")
1477
+ return home;
1478
+ return path.startsWith("~/") ? join6(home, path.slice(2)) : path;
1479
+ }
1480
+ function configured(env, home) {
1481
+ const path = userConfigPath("config", { home, xdg: env.XDG_CONFIG_HOME });
1482
+ if (!existsSync4(path))
1483
+ return;
1484
+ try {
1485
+ const parsed = JSON.parse(readFileSync3(path, "utf8"));
1486
+ const folder = typeof parsed === "object" && parsed !== null ? parsed.workspace : undefined;
1487
+ return typeof folder === "string" && folder !== "" ? folder : undefined;
1488
+ } catch {
1489
+ return;
1490
+ }
1491
+ }
1492
+ function workspaceRoot({ given, env = process14.env, home = homedir4() } = {}) {
1493
+ const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1494
+ return resolve3(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1495
+ }
1410
1496
  // src/audit.ts
1411
- import { existsSync as existsSync5, readdirSync, statSync as statSync2 } from "fs";
1497
+ import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
1412
1498
  import { readdir } from "fs/promises";
1413
- import { join as join7, relative, resolve as resolve3 } from "path";
1414
- import process14 from "process";
1499
+ import { join as join8, relative, resolve as resolve4 } from "path";
1500
+ import process16 from "process";
1415
1501
 
1416
1502
  // src/report.ts
1417
- import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
1418
- import { join as join6 } from "path";
1503
+ import { existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
1504
+ import { join as join7 } from "path";
1419
1505
  var UPPER_BOUND = /<\s*(\d[\w.+-]*)/;
1420
1506
  var DEPENDENCY_KINDS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
1421
1507
  var GHSA = /GHSA-[\w-]+$/;
@@ -1439,7 +1525,7 @@ function fixFor(advisories) {
1439
1525
  return;
1440
1526
  return fixes.reduce((highest, fix) => Bun.semver.order(fix, highest) > 0 ? fix : highest);
1441
1527
  }
1442
- function findingsOf(audit, reaching, direct, level, ignore = []) {
1528
+ function findingsOf(audit, reaching, direct, level, ignore = [], via = new Map) {
1443
1529
  const found = [];
1444
1530
  for (const [name, all] of Object.entries(audit)) {
1445
1531
  const kept = all.filter((advisory) => severityRank(advisory.severity) >= severityRank(level) && !isIgnored({ id: advisory.id, ghsa: GHSA.exec(advisory.url)?.[0] }, ignore));
@@ -1452,14 +1538,53 @@ function findingsOf(audit, reaching, direct, level, ignore = []) {
1452
1538
  advisories,
1453
1539
  scope: reaching.has(name) ? "prod" : "dev",
1454
1540
  direct: direct.has(name),
1541
+ via: direct.has(name) ? [] : via.get(name) ?? [],
1455
1542
  fix: fixFor(kept)
1456
1543
  });
1457
1544
  }
1458
1545
  return found.toSorted((a, b) => severityRank(b.severity) - severityRank(a.severity) || Number(b.scope === "prod") - Number(a.scope === "prod") || a.package.localeCompare(b.package));
1459
1546
  }
1547
+ function lockGraph(lockText) {
1548
+ const graph = new Map;
1549
+ let lock;
1550
+ try {
1551
+ lock = Bun.JSONC.parse(lockText);
1552
+ } catch {
1553
+ return graph;
1554
+ }
1555
+ for (const entry of Object.values(lock?.packages ?? {})) {
1556
+ const resolution = entry[0];
1557
+ const info = entry[2];
1558
+ if (typeof resolution !== "string" || typeof info !== "object" || info === null)
1559
+ continue;
1560
+ const at = resolution.indexOf("@", 1);
1561
+ const name = at === -1 ? resolution : resolution.slice(0, at);
1562
+ const wanted = DEPENDENCY_KINDS.flatMap((kind) => Object.keys(info[kind] ?? {}));
1563
+ graph.set(name, [...new Set([...graph.get(name) ?? [], ...wanted])]);
1564
+ }
1565
+ return graph;
1566
+ }
1567
+ function reachedFrom(graph, direct, targets) {
1568
+ const from = new Map;
1569
+ for (const start of direct) {
1570
+ const seen = new Set([start]);
1571
+ const queue = [start];
1572
+ for (let name = queue.shift();name !== undefined; name = queue.shift()) {
1573
+ if (name !== start && targets.has(name))
1574
+ from.set(name, [...from.get(name) ?? [], start]);
1575
+ for (const next of graph.get(name) ?? []) {
1576
+ if (!seen.has(next)) {
1577
+ seen.add(next);
1578
+ queue.push(next);
1579
+ }
1580
+ }
1581
+ }
1582
+ }
1583
+ return new Map([...from].map(([name, starts]) => [name, starts.toSorted()]));
1584
+ }
1460
1585
  function readManifest(path) {
1461
1586
  try {
1462
- return existsSync4(path) ? JSON.parse(readFileSync3(path, "utf8")) : {};
1587
+ return existsSync5(path) ? JSON.parse(readFileSync4(path, "utf8")) : {};
1463
1588
  } catch {
1464
1589
  return {};
1465
1590
  }
@@ -1471,9 +1596,9 @@ function namesIn(manifest) {
1471
1596
  });
1472
1597
  }
1473
1598
  function directDependencies(root, workspaces) {
1474
- const names = new Set(namesIn(readManifest(join6(root, "package.json"))));
1599
+ const names = new Set(namesIn(readManifest(join7(root, "package.json"))));
1475
1600
  for (const workspace of workspaces) {
1476
- for (const name of namesIn(readManifest(join6(root, workspace, "package.json"))))
1601
+ for (const name of namesIn(readManifest(join7(root, workspace, "package.json"))))
1477
1602
  names.add(name);
1478
1603
  }
1479
1604
  return names;
@@ -1485,15 +1610,15 @@ function workspacePatterns(field) {
1485
1610
  return Array.isArray(packages) ? packages : [];
1486
1611
  }
1487
1612
  function workspaceFolders(root, children) {
1488
- const patterns = workspacePatterns(readManifest(join6(root, "package.json")).workspaces);
1489
- return patterns.filter((pattern) => typeof pattern === "string").flatMap((pattern) => pattern.endsWith("/*") ? children(pattern.slice(0, -2)).map((name) => join6(pattern.slice(0, -2), name)) : [pattern]);
1613
+ const patterns = workspacePatterns(readManifest(join7(root, "package.json")).workspaces);
1614
+ return patterns.filter((pattern) => typeof pattern === "string").flatMap((pattern) => pattern.endsWith("/*") ? children(pattern.slice(0, -2)).map((name) => join7(pattern.slice(0, -2), name)) : [pattern]);
1490
1615
  }
1491
1616
 
1492
1617
  // src/audit.ts
1493
1618
  var USAGE = `audit [options] [root]: the known vulnerabilities of the Bun repositories under root (the current folder by default), one table per repository
1494
1619
 
1495
- Each package with an advisory is one row: its worst severity, how many advisories, whether a production dependency needs it (prod) or only a development one (dev), whether the repository asks for it itself (direct) or a dependency does (the row then says via), and the version that fixes every advisory at once, "-" when an advisory names none. The worst and the production ones come first.
1496
- It runs \`bun audit --json\` in each repository holding a bun.lock, which reaches the registry; the walk goes three levels deep, stops at a bun.lock and skips node_modules and hidden folders.
1620
+ Each package with an advisory is one row: its worst severity, how many advisories, whether a production dependency needs it (prod) or only a development one (dev), whether the repository asks for it itself (direct) or a dependency does (the row then says via and the direct dependencies leading to it, upgrading one of which is what fixes it), and the version that fixes every advisory at once, "-" when an advisory names none. The worst and the production ones come first.
1621
+ Advisories under --level (moderate by default) are counted under the table, and what \`bun audit\` warned about, such as a private registry that would not audit its packages, is repeated there. It runs \`bun audit --json\` in each repository holding a bun.lock, which reaches the registry; the walk goes three levels deep, stops at a bun.lock and skips node_modules and hidden folders.
1497
1622
 
1498
1623
  Reach for it to sweep many repositories at once; \`pkg audit\` vets the one repository in a folder (package age, install scripts, licences) as well as its advisories, and shares --level, --prod and --ignore.`;
1499
1624
  var EXITS = [[0, "no repository has an advisory at the level asked"], [1, "one has"], [2, "a repository's audit failed, no bun.lock sits under root, a usage error or a root that is no folder"]];
@@ -1501,13 +1626,18 @@ var OPTIONS = {
1501
1626
  level: { type: "string", choices: SEVERITIES, default: "moderate", description: "only the advisories at least this severe: low, moderate, high or critical" },
1502
1627
  prod: { type: "boolean", description: "only the packages a production dependency needs" },
1503
1628
  ignore: { type: "string", multiple: true, description: "an advisory skipped by GHSA or numeric id, repeatable" },
1504
- json: jsonOption("[{repo, path, findings: [{package, severity, scope, direct, fix, advisories: [{id, ghsa, url, title, severity, fixed}]}], error}]")
1629
+ json: jsonOption("[{repo, path, findings: [{package, severity, scope, direct, via, fix, advisories: [{id, ghsa, url, title, severity, fixed}]}], error}]")
1505
1630
  };
1506
1631
  var MAX_DEPTH = 3;
1507
1632
  var CONCURRENCY = 4;
1508
1633
  var AUDIT_MS = 60000;
1634
+ var WARNING = /^warn: .+$/gm;
1635
+ var VIA_SHOWN = 2;
1636
+ function countAdvisories(findings) {
1637
+ return findings.reduce((sum, found) => sum + found.advisories.length, 0);
1638
+ }
1509
1639
  function holdsLock(dir) {
1510
- return existsSync5(join7(dir, "bun.lock")) || existsSync5(join7(dir, "bun.lockb"));
1640
+ return existsSync6(join8(dir, "bun.lock")) || existsSync6(join8(dir, "bun.lockb"));
1511
1641
  }
1512
1642
  async function findRepos(root) {
1513
1643
  if (holdsLock(root))
@@ -1523,7 +1653,7 @@ async function findRepos(root) {
1523
1653
  for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
1524
1654
  if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith("."))
1525
1655
  continue;
1526
- const path = join7(dir, entry.name);
1656
+ const path = join8(dir, entry.name);
1527
1657
  if (holdsLock(path))
1528
1658
  found.push(path);
1529
1659
  else if (depth < MAX_DEPTH)
@@ -1533,22 +1663,10 @@ async function findRepos(root) {
1533
1663
  await walk(root, 1);
1534
1664
  return found;
1535
1665
  }
1536
- async function pool(items, limit, task) {
1537
- const results = Array.from({ length: items.length });
1538
- let next = 0;
1539
- async function worker() {
1540
- while (next < items.length) {
1541
- const index = next++;
1542
- results[index] = await task(items[index]);
1543
- }
1544
- }
1545
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1546
- return results;
1547
- }
1548
1666
  function children(root) {
1549
1667
  return (folder) => {
1550
1668
  try {
1551
- return readdirSync(join7(root, folder), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
1669
+ return readdirSync(join8(root, folder), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
1552
1670
  } catch {
1553
1671
  return [];
1554
1672
  }
@@ -1562,10 +1680,26 @@ async function audited(path, shown, level, ignore) {
1562
1680
  const audit = parseAudit(stdoutOf(all));
1563
1681
  const reached = parseAudit(stdoutOf(production));
1564
1682
  if (audit === undefined || reached === undefined)
1565
- return { repo: shown, path, findings: [], error: failure(audit === undefined ? all : production) };
1683
+ return { repo: shown, path, findings: [], below: 0, warnings: [], error: failure(audit === undefined ? all : production) };
1566
1684
  const reaching = new Set(Object.keys(reached));
1567
1685
  const direct = directDependencies(path, workspaceFolders(path, children(path)));
1568
- return { repo: shown, path, findings: findingsOf(audit, reaching, direct, level, ignore), error: undefined };
1686
+ const via = reachedFrom(lockGraph(lockText(path)), direct, new Set(Object.keys(audit)));
1687
+ const findings = findingsOf(audit, reaching, direct, level, ignore, via);
1688
+ return { repo: shown, path, findings, below: countAdvisories(findingsOf(audit, reaching, direct, "low", ignore)) - countAdvisories(findings), warnings: [...new Set(all.text.match(WARNING) ?? [])], error: undefined };
1689
+ }
1690
+ function lockText(path) {
1691
+ try {
1692
+ return readFileSync5(join8(path, "bun.lock"), "utf8");
1693
+ } catch {
1694
+ return "";
1695
+ }
1696
+ }
1697
+ function originOf(found) {
1698
+ if (found.direct)
1699
+ return "direct";
1700
+ if (found.via.length === 0)
1701
+ return "via";
1702
+ return `via ${found.via.slice(0, VIA_SHOWN).join(", ")}${found.via.length > VIA_SHOWN ? ` +${found.via.length - VIA_SHOWN}` : ""}`;
1569
1703
  }
1570
1704
  function stdoutOf(ran) {
1571
1705
  return Buffer.concat(ran.chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
@@ -1575,7 +1709,7 @@ function failure(ran) {
1575
1709
  `).at(-1) ?? `exit ${ran.code}`;
1576
1710
  }
1577
1711
  function tint(severity) {
1578
- const colors = paint(process14.stdout);
1712
+ const colors = paint(process16.stdout);
1579
1713
  if (severity === "critical" || severity === "high")
1580
1714
  return colors.red;
1581
1715
  return severity === "moderate" ? colors.yellow : colors.dim;
@@ -1586,14 +1720,14 @@ function rows(findings) {
1586
1720
  tint(found.severity)(found.severity),
1587
1721
  String(found.advisories.length),
1588
1722
  found.scope,
1589
- found.direct ? "direct" : "via",
1723
+ originOf(found),
1590
1724
  found.fix ?? "-"
1591
1725
  ]);
1592
1726
  }
1593
1727
  async function audit(args) {
1594
1728
  const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["[root]"], exits: EXITS, replaces: "a bun audit run in each repository and a read of every advisory to find what is worth fixing", examples: ["audit", "audit ~/Workspace --level high --prod"] });
1595
- const root = resolve3(positionals[0] ?? ".");
1596
- if (!existsSync5(root) || !statSync2(root).isDirectory())
1729
+ const root = resolve4(positionals[0] ?? ".");
1730
+ if (!existsSync6(root) || !statSync2(root).isDirectory())
1597
1731
  fail(`no folder ${root}`);
1598
1732
  const level = oneOf(values.level, "level", SEVERITIES);
1599
1733
  const paths = await findRepos(root);
@@ -1610,8 +1744,8 @@ async function audit(args) {
1610
1744
  return kept.some((each) => each.findings.length > 0) ? 1 : 0;
1611
1745
  }
1612
1746
  function show(audits, total) {
1613
- const label = role("label", process14.stdout);
1614
- const path = role("path", process14.stdout);
1747
+ const label = role("label", process16.stdout);
1748
+ const path = role("path", process16.stdout);
1615
1749
  const flagged = audits.filter((each) => each.error !== undefined || each.findings.length > 0);
1616
1750
  if (flagged.length === 0) {
1617
1751
  console.log(label(`no advisory in ${total} ${total === 1 ? "repository" : "repositories"}`));
@@ -1621,8 +1755,14 @@ function show(audits, total) {
1621
1755
  console.log(`${path(each.repo)} ${label(each.error === undefined ? `${each.findings.length} ${each.findings.length === 1 ? "package" : "packages"}` : `audit failed: ${each.error}`)}`);
1622
1756
  if (each.findings.length > 0)
1623
1757
  console.log(table([["package", "severity", "advisories", "scope", "origin", "fix"], ...rows(each.findings)], { header: true, align: ["left", "left", "right", "left", "left", "left"] }));
1758
+ if (each.findings.some((found) => !found.direct))
1759
+ console.log(label("via: a dependency of the ones named, fixed by upgrading one of them to a release that depends on the fixed version"));
1760
+ if (each.below > 0)
1761
+ console.log(label(`${each.below} ${each.below === 1 ? "advisory" : "advisories"} below the level left out, --level low lists them`));
1762
+ for (const warning of each.warnings)
1763
+ console.log(label(warning));
1624
1764
  }
1625
1765
  }
1626
1766
 
1627
1767
  // src/audit-cli.ts
1628
- process15.exitCode = await runMain({ name: "audit", run: audit });
1768
+ process17.exitCode = await runMain({ name: "audit", run: audit });