@kaynooo/cli-workspace 0.10.1 → 0.11.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/sweep-cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/sweep-cli.ts
5
- import process18 from "process";
5
+ import process21 from "process";
6
6
 
7
7
  // ../kit/src/advisory.ts
8
8
  var SEVERITIES = ["low", "moderate", "high", "critical"];
@@ -517,24 +517,20 @@ function printJson(value) {
517
517
 
518
518
  // ../kit/src/help.ts
519
519
  import process8 from "process";
520
- var OPTIONAL = /\[[^\]]+\]/g;
520
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
521
521
  var USAGE_PREFIX = /^usage:\s*/i;
522
522
  var FULL_STOP = /\.$/;
523
523
  function usageLine(usage, colors = paint(process8.stdout)) {
524
524
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
525
525
  }
526
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
527
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
526
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
527
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
528
528
  `);
529
529
  }
530
530
  function exitRows(exits, colors = paint(process8.stdout)) {
531
531
  if (exits.length === 0)
532
532
  return [];
533
- const width = Math.max(...exits.map(([code]) => String(code).length));
534
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
535
- }
536
- function replacesRows(replaces, colors = paint(process8.stdout)) {
537
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
533
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
538
534
  }
539
535
  function wantsHelpJson(env = process8.env) {
540
536
  return env.KIT_HELP === "json";
@@ -560,29 +556,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
560
556
  return [];
561
557
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
562
558
  }
559
+ var MAX_INLINE_CHOICES = 24;
563
560
  function optionRows(options, colors = paint(process8.stdout)) {
564
561
  const rows = Object.entries(options).map(([name, option]) => {
565
562
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
566
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
563
+ const choices = option.choices?.join("|");
564
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
565
+ const named = inline ? `<${choices}>` : "<value>";
567
566
  const placeholder = option.optional === undefined ? named : `[${named}]`;
568
567
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
569
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
568
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
569
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
570
570
  });
571
571
  const width = Math.max(0, ...rows.map((row) => row.width));
572
572
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
573
573
  }
574
574
 
575
575
  // ../kit/src/text.ts
576
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
577
576
  function distance(a, b) {
578
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
579
- for (const [i, left] of [...a].entries()) {
577
+ const left = [...a];
578
+ const right = [...b];
579
+ let before = [];
580
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
581
+ for (const [i, x] of left.entries()) {
580
582
  const current = [i + 1];
581
- for (const [j, right] of [...b].entries())
582
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
583
+ for (const [j, y] of right.entries()) {
584
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
585
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
586
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
587
+ current.push(cost);
588
+ }
589
+ before = previous;
583
590
  previous = current;
584
591
  }
585
- return previous[b.length] ?? 0;
592
+ return previous[right.length] ?? 0;
586
593
  }
587
594
  function closest(name, names) {
588
595
  const started = names.find((known) => known.startsWith(name));
@@ -821,9 +828,33 @@ function nearestOption(message, options, allowNegative) {
821
828
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
822
829
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
823
830
  }
831
+ // ../kit/src/argv.ts
832
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
833
+ import { resolve as resolve3 } from "path";
834
+ import process10 from "process";
835
+ function commandLine() {
836
+ try {
837
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
838
+ } catch {
839
+ return;
840
+ }
841
+ }
842
+ function realPath(word) {
843
+ try {
844
+ return realpathSync(resolve3(word));
845
+ } catch {
846
+ return;
847
+ }
848
+ }
849
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
850
+ const target = script === undefined ? undefined : realPath(script) ?? script;
851
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
852
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
853
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
854
+ }
824
855
  // ../kit/src/process.ts
825
856
  import { constants } from "os";
826
- import process10 from "process";
857
+ import process11 from "process";
827
858
  var KILL_GRACE_MS = 2000;
828
859
  function exitCodeOf(code, signal) {
829
860
  if (code !== null)
@@ -843,7 +874,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
843
874
  return;
844
875
  try {
845
876
  if (grouped)
846
- process10.kill(-proc.pid, killing);
877
+ process11.kill(-proc.pid, killing);
847
878
  else
848
879
  proc.kill(killing);
849
880
  } catch {}
@@ -918,10 +949,10 @@ var RESET_STYLE = `${ESC}[0m`;
918
949
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
919
950
 
920
951
  // ../kit/src/tool.ts
921
- import process11 from "process";
952
+ import process12 from "process";
922
953
  function cwdGone() {
923
954
  try {
924
- process11.cwd();
955
+ process12.cwd();
925
956
  return false;
926
957
  } catch {
927
958
  return true;
@@ -943,7 +974,7 @@ function spawnFailure(command, error) {
943
974
  async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
944
975
  let ran;
945
976
  try {
946
- ran = await runCommand(argv, { env: process11.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
977
+ ran = await runCommand(argv, { env: process12.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
947
978
  } catch (error) {
948
979
  throw spawnFailure(label, error);
949
980
  }
@@ -958,15 +989,33 @@ async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
958
989
  return { code: ran.code, ...streams };
959
990
  }
960
991
  // ../kit/src/cli.ts
961
- import { readFileSync as readFileSync3, realpathSync } from "fs";
992
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
962
993
  import { dirname as dirname3, join as join5 } from "path";
994
+ import process15 from "process";
995
+
996
+ // ../kit/src/notify.ts
963
997
  import process13 from "process";
998
+ var NOTIFY_AFTER_MS = 1e4;
999
+ var CANCELLED = 130;
1000
+ function base64(text) {
1001
+ return Buffer.from(text).toString("base64");
1002
+ }
1003
+ function notification(title, body, env = process13.env) {
1004
+ const id = `kit${process13.pid}`;
1005
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
1006
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1007
+ }
1008
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1009
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1010
+ return;
1011
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1012
+ }
964
1013
 
965
1014
  // ../kit/src/usage.ts
966
1015
  import { appendFileSync, mkdirSync } from "fs";
967
1016
  import { homedir as homedir3 } from "os";
968
1017
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
969
- import process12 from "process";
1018
+ import process14 from "process";
970
1019
 
971
1020
  // ../kit/src/logs.ts
972
1021
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -980,14 +1029,14 @@ var usageError;
980
1029
  function noteUsageError(message) {
981
1030
  usageError = message;
982
1031
  }
983
- function stateHome(env = process12.env) {
1032
+ function stateHome(env = process14.env) {
984
1033
  const dir = env.XDG_STATE_HOME;
985
1034
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
986
1035
  }
987
- function usagePath(env = process12.env) {
1036
+ function usagePath(env = process14.env) {
988
1037
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
989
1038
  }
990
- function usageRecorded(env = process12.env) {
1039
+ function usageRecorded(env = process14.env) {
991
1040
  const off = env.KAYNOOO_CLI_NO_USAGE;
992
1041
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
993
1042
  }
@@ -1001,7 +1050,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
1001
1050
  usageError = undefined;
1002
1051
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1003
1052
  }
1004
- function recordUsage(entry, env = process12.env) {
1053
+ function recordUsage(entry, env = process14.env) {
1005
1054
  if (!usageRecorded(env))
1006
1055
  return;
1007
1056
  try {
@@ -1078,7 +1127,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1078
1127
  header(colors, summary),
1079
1128
  "",
1080
1129
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
1081
- ...replacesRows(replaces, colors),
1082
1130
  "",
1083
1131
  ...await commandRows(commands, colors),
1084
1132
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -1092,8 +1140,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1092
1140
  `);
1093
1141
  }
1094
1142
  function printError(prefix, message, hint, cause) {
1095
- const colors = paint(process13.stderr);
1096
- const styled = takesControlCodes(process13.stderr);
1143
+ const colors = paint(process15.stderr);
1144
+ const styled = takesControlCodes(process15.stderr);
1097
1145
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1098
1146
  const under = (label, text, tint) => text === undefined ? "" : `
1099
1147
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1136,11 +1184,11 @@ async function dispatch(level, typed, { version, redact }) {
1136
1184
  }
1137
1185
  }
1138
1186
  if (name === undefined && level.path.length > 1) {
1139
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
1187
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
1140
1188
  return 2;
1141
1189
  }
1142
1190
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1143
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1191
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
1144
1192
  return 0;
1145
1193
  }
1146
1194
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1196,24 +1244,24 @@ function candidateLine(candidate) {
1196
1244
  }
1197
1245
  function positionalBeingTyped(before, { options, positionals }) {
1198
1246
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1199
- let index = 0;
1247
+ const typed = [];
1200
1248
  let at = 0;
1201
1249
  while (at < before.length) {
1202
1250
  const word = before[at];
1203
1251
  if (word === "--") {
1204
- index += before.length - at - 1;
1252
+ typed.push(...before.slice(at + 1));
1205
1253
  break;
1206
1254
  }
1207
1255
  if (!word.startsWith("-"))
1208
- index++;
1256
+ typed.push(word);
1209
1257
  else if (takesValue(word))
1210
1258
  at++;
1211
1259
  at++;
1212
1260
  }
1213
1261
  const last = positionals.at(-1);
1214
- if (index < positionals.length)
1215
- return positionals[index];
1216
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1262
+ if (typed.length < positionals.length)
1263
+ return { name: positionals[typed.length], typed };
1264
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1217
1265
  }
1218
1266
  async function leafCandidates(run, words) {
1219
1267
  const completing = await completingOf(run);
@@ -1221,12 +1269,12 @@ async function leafCandidates(run, words) {
1221
1269
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1222
1270
  const flag = words.at(-2);
1223
1271
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1272
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1224
1273
  if (option?.type === "string") {
1225
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1274
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1226
1275
  return values === undefined ? [FILES] : values.map(candidateLine);
1227
1276
  }
1228
- const name = positionalBeingTyped(words.slice(0, -1), completing);
1229
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1277
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1230
1278
  return values === undefined ? [FILES] : values.map(candidateLine);
1231
1279
  }
1232
1280
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -1257,9 +1305,13 @@ async function printCandidates(found) {
1257
1305
  return 0;
1258
1306
  }
1259
1307
  function packageVersion(entry = Bun.main) {
1260
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1308
+ let resolved = entry;
1309
+ try {
1310
+ resolved = realpathSync2(entry);
1311
+ } catch {}
1312
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1261
1313
  try {
1262
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1314
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1263
1315
  if (typeof version === "string")
1264
1316
  return version;
1265
1317
  } catch {}
@@ -1267,14 +1319,17 @@ function packageVersion(entry = Bun.main) {
1267
1319
  return "0.0.0";
1268
1320
  }
1269
1321
  }
1270
- async function runCli(cli, argv = process13.argv.slice(2)) {
1322
+ async function runCli(cli, argv = scriptArgs()) {
1271
1323
  const version = cli.version ?? packageVersion();
1272
1324
  if (argv[0] === COMPLETE)
1273
1325
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1326
+ const started = performance.now();
1274
1327
  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 });
1328
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1329
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1275
1330
  if (cli.usage !== false) {
1276
1331
  try {
1277
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1332
+ recordUsage(usageEntry(cli.name, command, argv, code));
1278
1333
  } catch {}
1279
1334
  }
1280
1335
  return code;
@@ -1294,7 +1349,7 @@ function commandPath(scope, argv) {
1294
1349
  }
1295
1350
  return path.length === 0 ? undefined : path.join(" ");
1296
1351
  }
1297
- async function runMain({ name, version, run, redact, usage }, argv = process13.argv.slice(2)) {
1352
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1298
1353
  if (argv[0] === COMPLETE)
1299
1354
  return printCandidates(leafCandidates(run, argv.slice(1)));
1300
1355
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1302,11 +1357,13 @@ async function runMain({ name, version, run, redact, usage }, argv = process13.a
1302
1357
  return 0;
1303
1358
  }
1304
1359
  let code;
1360
+ const started = performance.now();
1305
1361
  try {
1306
1362
  code = await run(argv);
1307
1363
  } catch (error) {
1308
1364
  code = reportThrown(name, error, redact, wantsJson(argv));
1309
1365
  }
1366
+ notifyEnd(name, code, performance.now() - started);
1310
1367
  if (usage !== false) {
1311
1368
  try {
1312
1369
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1346,7 +1403,7 @@ function parseSize(text, bareUnit = 1) {
1346
1403
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1347
1404
  }
1348
1405
  // ../kit/src/watch.ts
1349
- import process14 from "process";
1406
+ import process16 from "process";
1350
1407
  import { format } from "util";
1351
1408
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1352
1409
  var DEFAULT_SECONDS = 2;
@@ -1368,7 +1425,7 @@ function withoutWatch(args) {
1368
1425
  }
1369
1426
  return rest;
1370
1427
  }
1371
- async function watching(value, step, stream = process14.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1428
+ async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1372
1429
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1373
1430
  if (!takesControlCodes(stream))
1374
1431
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1376,12 +1433,12 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
1376
1433
  for (let round = 0;round < rounds; round++) {
1377
1434
  const held = [];
1378
1435
  const { log, info } = console;
1379
- const write = process14.stdout.write.bind(process14.stdout);
1436
+ const write = process16.stdout.write.bind(process16.stdout);
1380
1437
  const hold = (...parts) => void held.push(`${format(...parts)}
1381
1438
  `);
1382
1439
  console.log = hold;
1383
1440
  console.info = hold;
1384
- process14.stdout.write = (text) => {
1441
+ process16.stdout.write = (text) => {
1385
1442
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1386
1443
  return true;
1387
1444
  };
@@ -1390,7 +1447,7 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
1390
1447
  } finally {
1391
1448
  console.log = log;
1392
1449
  console.info = info;
1393
- process14.stdout.write = write;
1450
+ process16.stdout.write = write;
1394
1451
  }
1395
1452
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1396
1453
  await sleep(interval);
@@ -1399,8 +1456,8 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
1399
1456
  }
1400
1457
  // ../kit/src/workspace-root.ts
1401
1458
  import { homedir as homedir4 } from "os";
1402
- import { dirname as dirname4, join as join6, resolve as resolve3 } from "path";
1403
- import process15 from "process";
1459
+ import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
1460
+ import process17 from "process";
1404
1461
  function expandHome(path, home) {
1405
1462
  if (path === "~")
1406
1463
  return home;
@@ -1410,9 +1467,9 @@ function configured(env, home) {
1410
1467
  const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
1411
1468
  return typeof folder === "string" && folder !== "" ? folder : undefined;
1412
1469
  }
1413
- function workspaceRoot({ given, env = process15.env, home = homedir4() } = {}) {
1470
+ function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
1414
1471
  const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1415
- return resolve3(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1472
+ return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1416
1473
  }
1417
1474
  // src/sweep.ts
1418
1475
  import { existsSync as existsSync6, statSync as statSync2 } from "fs";
@@ -1420,7 +1477,21 @@ import { homedir as homedir6 } from "os";
1420
1477
  import { relative } from "path";
1421
1478
 
1422
1479
  // ../kit/src/prompt.ts
1423
- import process17 from "process";
1480
+ import process20 from "process";
1481
+
1482
+ // ../kit/src/job.ts
1483
+ import process19 from "process";
1484
+ function stopJob() {
1485
+ process19.kill(0, "SIGTSTP");
1486
+ }
1487
+
1488
+ // ../kit/src/picker/line.ts
1489
+ var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
1490
+ var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
1491
+ var FORWARD_KILLS = new Set(["killnext", "killend"]);
1492
+ function isEditKey(key) {
1493
+ return EDIT_KEYS.has(key);
1494
+ }
1424
1495
 
1425
1496
  // ../kit/src/picker/score.ts
1426
1497
  var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
@@ -1452,10 +1523,29 @@ var KEYS = {
1452
1523
  "\n": "enter",
1453
1524
  "\x03": "cancel",
1454
1525
  "\x1B": "cancel",
1526
+ "\x1B[D": "left",
1527
+ "\x1BOD": "left",
1528
+ "\x1B[C": "right",
1529
+ "\x1BOC": "right",
1530
+ "\x1B[1;5D": "wordleft",
1531
+ "\x1B[1;3D": "wordleft",
1532
+ "\x1Bb": "wordleft",
1533
+ "\x1B[1;5C": "wordright",
1534
+ "\x1B[1;3C": "wordright",
1535
+ "\x1Bf": "wordright",
1536
+ "\x01": "linestart",
1537
+ "\x05": "lineend",
1455
1538
  "\x7F": "erase",
1456
- "\b": "erase",
1539
+ "\x1B[3~": "delete",
1540
+ "\b": "killword",
1541
+ "\x1B\x7F": "killword",
1542
+ "\x1B[3;5~": "killnext",
1543
+ "\x1Bd": "killnext",
1457
1544
  "\x15": "clear",
1545
+ "\v": "killend",
1458
1546
  "\x17": "word",
1547
+ "\x19": "yank",
1548
+ "\x1A": "suspend",
1459
1549
  "\t": "tab",
1460
1550
  "\x1F": "help",
1461
1551
  "\x1BOP": "help",
@@ -1485,10 +1575,21 @@ function parseKeys(input, paste = { active: false }, ctrls = []) {
1485
1575
  });
1486
1576
  }
1487
1577
 
1578
+ // ../kit/src/redraw.ts
1579
+ var SYNC_START = "\x1B[?2026h";
1580
+ var SYNC_END = "\x1B[?2026l";
1581
+ function overwrite(lines, columns) {
1582
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1583
+ `);
1584
+ }
1585
+ function rowsTaken(lines, columns) {
1586
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1587
+ }
1588
+
1488
1589
  // ../kit/src/prompt.ts
1489
- var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "erase"]);
1590
+ var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
1490
1591
  function readKeys(input, paste = { active: false }) {
1491
- return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key));
1592
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
1492
1593
  }
1493
1594
  async function confirm(question, { default: fallback, ...settings } = {}) {
1494
1595
  let answered = fallback;
@@ -1512,7 +1613,7 @@ function asking(colors, question, typed, keys) {
1512
1613
  function answer(colors, question, state, picked) {
1513
1614
  return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1514
1615
  }
1515
- async function ask(question, { hint, terminal = process17 }, render, press) {
1616
+ async function ask(question, { hint, terminal = process20 }, render, press) {
1516
1617
  const { stdin, stderr } = terminal;
1517
1618
  if (!isInteractive(terminal))
1518
1619
  fail(`cannot ask "${question}" off a terminal`, 2, hint);
@@ -1522,12 +1623,22 @@ async function ask(question, { hint, terminal = process17 }, render, press) {
1522
1623
  const columns = () => stderr.columns || 80;
1523
1624
  const draw = (state, last = false) => {
1524
1625
  const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1525
- stderr.write(`\r\x1B[0J${frame.join(`
1526
- `)}${last || frame.length < 2 ? "" : `\x1B[${frame.length - 1}A`}${last ? "" : "\r"}`);
1626
+ const rows = rowsTaken(frame, columns());
1627
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
1527
1628
  current = state;
1528
1629
  };
1529
1630
  const redraw = () => draw(current);
1530
1631
  const paste = { active: false };
1632
+ const stop = terminal.stop ?? (terminal === process20 ? stopJob : undefined);
1633
+ const suspend = () => {
1634
+ if (stop === undefined)
1635
+ return;
1636
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
1637
+ stdin.setRawMode(false);
1638
+ stop();
1639
+ stdin.setRawMode(true);
1640
+ stderr.write("\x1B[?25l\x1B[?2004h");
1641
+ };
1531
1642
  try {
1532
1643
  stderr.on?.("resize", redraw);
1533
1644
  stdin.setRawMode(true);
@@ -1537,6 +1648,10 @@ async function ask(question, { hint, terminal = process17 }, render, press) {
1537
1648
  return await new Promise((resolve) => {
1538
1649
  function onData(data) {
1539
1650
  for (const key of readKeys(data.toString(), paste)) {
1651
+ if (key === "suspend") {
1652
+ suspend();
1653
+ continue;
1654
+ }
1540
1655
  const pressed = press(key);
1541
1656
  if (pressed !== undefined) {
1542
1657
  settle(pressed);
@@ -1652,9 +1767,10 @@ async function sizeOf(folder) {
1652
1767
  }
1653
1768
 
1654
1769
  // src/sweep-scan.ts
1655
- var FOLDER_NAMES = new Set(["node_modules", ".nuxt", ".next", ".output", "dist", "build", ".turbo", ".svelte-kit", "target"]);
1770
+ var FOLDER_NAMES = new Set(["node_modules", ".nuxt", ".next", ".output", "dist", "build", ".turbo", ".svelte-kit", "target", "vendor", ".venv", "__pycache__", ".gradle"]);
1771
+ var NEEDS_BESIDE = { target: ["Cargo.toml"], vendor: ["composer.json", "composer.lock"] };
1656
1772
  var MAX_DEPTH = 3;
1657
- var PROJECT_CACHE_NAMES = new Set([".turbo", ".nuxt", ".next", ".svelte-kit"]);
1773
+ var PROJECT_CACHE_NAMES = new Set([".turbo", ".nuxt", ".next", ".svelte-kit", "__pycache__", ".gradle"]);
1658
1774
  var GLOBAL_CACHES = [".bun/install/cache", ".npm/_cacache", ".cache/pip", ".cache/uv", ".cache/ms-playwright", ".cache/puppeteer", ".cache/go-build", ".cache/typescript", ".cargo/registry"];
1659
1775
  function isCachePath(path, home = homedir5()) {
1660
1776
  return GLOBAL_CACHES.some((cache) => join8(home, cache) === path) || basename(path) === ".cache" && basename(dirname5(path)) === "node_modules";
@@ -1699,7 +1815,7 @@ async function findCandidates(root, home = homedir5(), withGlobal = true) {
1699
1815
  }
1700
1816
  continue;
1701
1817
  }
1702
- if (FOLDER_NAMES.has(entry.name) && (entry.name !== "target" || existsSync4(join8(dir, "Cargo.toml")))) {
1818
+ if (FOLDER_NAMES.has(entry.name) && (NEEDS_BESIDE[entry.name]?.some((file) => existsSync4(join8(dir, file))) ?? true)) {
1703
1819
  if (entry.isSymbolicLink()) {
1704
1820
  found.skipped.push({ path, reason: "symlink" });
1705
1821
  } else if (entry.isDirectory()) {
@@ -1886,18 +2002,17 @@ async function applyAll(entries, done) {
1886
2002
  // src/sweep.ts
1887
2003
  var LARGE = 100 * 1024 ** 2;
1888
2004
  var BIG = 1024 ** 3;
1889
- var USAGE = `sweep [options] [root]: lists the regenerable folders (node_modules, .output, dist, build, target beside a Cargo.toml), the caches (.nuxt, .next, .turbo, .svelte-kit and node_modules/.cache per project; ~/.bun/install/cache, ~/.npm/_cacache, ~/.cache/{pip,uv,ms-playwright,puppeteer,go-build,typescript} and ~/.cargo/registry, exact paths only, listed only when no root is given or with --only caches) and the .worktrees/* and .claude/worktrees/* entries under root (the configured workspace, ~/Workspace by default, ${MAX_DEPTH} levels down), largest first with the age of the repo's last commit; --only worktrees, folders or caches keeps one kind
1890
-
1891
- Dry unless --apply, which deletes after a confirm showing the total (read from the terminal; off one, pass --yes). A folder is deleted for good, not trashed. Never touched: a symlink, a folder git tracks files in, a build folder git does not ignore. A worktree is removed with git worktree remove, never forced, and only when it is clean and every commit of its branch is on another branch or a remote; the others stay listed as kept and count for nothing in the total. With --docker the Docker usage comes after the list, left to dclean.
2005
+ var USAGE = `sweep [options] [root]: lists the regenerable folders (node_modules, .output, dist, build, .venv, target beside a Cargo.toml, vendor beside a composer.json or composer.lock), the caches (.nuxt, .next, .turbo, .svelte-kit, __pycache__, .gradle and node_modules/.cache per project; ~/.bun/install/cache, ~/.npm/_cacache, ~/.cache/{pip,uv,ms-playwright,puppeteer,go-build,typescript} and ~/.cargo/registry, exact paths only, listed only when no root is given or with --only caches) and the .worktrees/* and .claude/worktrees/* entries under root (the configured workspace, ~/Workspace by default, ${MAX_DEPTH} levels down), largest first with the age of the repo's last commit; --only worktrees, folders or caches keeps one kind
1892
2006
 
1893
- Exits 0 when it listed, or removed every entry it was allowed to, 1 when a removal failed or the confirm was declined, 2 on a usage error, a missing root, or --apply off a terminal without --yes.`;
2007
+ Dry unless --apply, which deletes after a confirm showing the total (read from the terminal; off one, pass --yes). A folder is deleted for good, not trashed. Never touched: a symlink, a folder git tracks files in, a build folder git does not ignore. A worktree is removed with git worktree remove, never forced, and only when it is clean and every commit of its branch is on another branch or a remote; the others stay listed as kept and count for nothing in the total. With --docker the Docker usage comes after the list, left to dclean.`;
2008
+ var EXITS = [[0, "it listed, or removed every entry it was allowed to"], [1, "a removal failed or the confirm was declined"], [2, "a usage error, a missing root, or --apply off a terminal without --yes"]];
1894
2009
  var ONLY_KINDS = { worktrees: "worktree", folders: "folder", caches: "cache" };
1895
2010
  var OPTIONS = {
1896
2011
  apply: { type: "boolean", description: "delete what is listed as removable, after the confirm" },
1897
2012
  yes: { type: "boolean", short: "y", description: "with --apply, skip the confirm" },
1898
2013
  older: { type: "string", description: "only the entries whose repo last committed longer ago than this (30d, 12h)" },
1899
2014
  min: { type: "string", description: "only the entries of at least this size (500K, 10M, 1G)" },
1900
- only: { type: "string", description: "worktrees, folders or caches: leave the other kinds out (.nuxt, .next, .turbo and .svelte-kit are caches; the global caches are listed with no root or with caches)" },
2015
+ only: { type: "string", description: "worktrees, folders or caches: leave the other kinds out (.nuxt, .next, .turbo, .svelte-kit, __pycache__ and .gradle are caches; the global caches are listed with no root or with caches)" },
1901
2016
  docker: { type: "boolean", description: "add the docker system df output, which alone takes about ten seconds" },
1902
2017
  json: jsonOption("{root, entries: [{path, kind (folder, worktree or cache), bytes, committedAt, action (remove or keep), reason}], skipped: [{path, reason}], reclaimable, docker, removed?}")
1903
2018
  };
@@ -1912,7 +2027,7 @@ async function dockerUsage() {
1912
2027
  }
1913
2028
  }
1914
2029
  async function sweep(args) {
1915
- const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["[root]"], replaces: "find ~/Workspace -name node_modules, du -sh and rm -rf by hand", examples: ["sweep", "sweep ~/Workspace --older 30d --min 100M --apply", "sweep --only worktrees --apply"] });
2030
+ const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, positionals: ["[root]"], replaces: "find ~/Workspace -name node_modules, du -sh and rm -rf by hand", examples: ["sweep", "sweep ~/Workspace --older 30d --min 100M --apply", "sweep --only worktrees --apply"] });
1916
2031
  if (positionals.length > 1)
1917
2032
  badUsage("give one root");
1918
2033
  const root = workspaceRoot({ given: positionals[0] });
@@ -1990,4 +2105,4 @@ ${tt(reclaimable)} reclaimable${skipped === 0 ? "" : `, ${skipped} skipped (syml
1990
2105
  }
1991
2106
 
1992
2107
  // src/sweep-cli.ts
1993
- process18.exitCode = await runMain({ name: "sweep", run: sweep });
2108
+ process21.exitCode = await runMain({ name: "sweep", run: sweep });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-workspace",
3
3
  "type": "module",
4
- "version": "0.10.1",
4
+ "version": "0.11.0",
5
5
  "description": "ws, repos, sweep, audit: the repositories of the workspace that need attention, the folders worth reclaiming and their known vulnerabilities.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -34,6 +34,6 @@
34
34
  "audit": "$npm_execpath src/audit-cli.ts"
35
35
  },
36
36
  "devDependencies": {
37
- "@kaynooo/cli-kit": "0.37.0"
37
+ "@kaynooo/cli-kit": "0.40.0"
38
38
  }
39
39
  }