@kaynooo/cli-workspace 0.11.0 → 0.14.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/cli.js CHANGED
@@ -1,28 +1,18 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
3
+ var __esm = (fn, res, err) => () => {
4
+ if (fn)
5
+ try {
6
+ res = fn(fn = 0);
7
+ } catch (e) {
8
+ err = [e];
9
+ }
10
+ if (err)
11
+ throw err[0];
12
+ return res;
13
+ };
3
14
 
4
- // src/cli.ts
5
- import process24 from "process";
6
-
7
- // ../kit/src/advisory.ts
8
- var SEVERITIES = ["low", "moderate", "high", "critical"];
9
- function severityRank(severity) {
10
- return SEVERITIES.indexOf(severity);
11
- }
12
- function isIgnored(advisory, ignore) {
13
- return ignore.includes(advisory.ghsa ?? "") || ignore.includes(String(advisory.id));
14
- }
15
- // ../kit/src/args.ts
16
- import process9 from "process";
17
- import { parseArgs } from "util";
18
-
19
- // ../kit/src/format.ts
20
- import process7 from "process";
21
-
22
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-n6z2kk96.js
23
- var r = new Map;
24
- var i = new Map;
25
- var l = new Map;
15
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-n6z2kk96.js
26
16
  function a(e, t, o) {
27
17
  return JSON.stringify([e ?? null, t ?? null, o]);
28
18
  }
@@ -32,12 +22,15 @@ function y(e, t) {
32
22
  n = new Intl.NumberFormat(e, t), i.set(o, n);
33
23
  return n;
34
24
  }
25
+ var r, i, l;
26
+ var init_chunk_n6z2kk96 = __esm(() => {
27
+ r = new Map;
28
+ i = new Map;
29
+ l = new Map;
30
+ });
35
31
 
36
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
37
- var N = new Map;
38
- var Nt = /\s+\S*$/;
39
- var Y = /\s/;
40
- function ko(t, e, r = "...") {
32
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
33
+ function Ao(t, e, r = "...") {
41
34
  let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
42
35
  if (t.length <= e)
43
36
  return t;
@@ -48,13 +41,22 @@ function ko(t, e, r = "...") {
48
41
  c = c.trimEnd();
49
42
  return s ? (c + n).slice(0, l) : c + n;
50
43
  }
51
- var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
52
- var z = new Map;
44
+ var N, Nt, Y, be, W;
45
+ var init_chunk_rkhsft4a = __esm(() => {
46
+ N = new Map;
47
+ Nt = /\s+\S*$/;
48
+ Y = /\s/;
49
+ be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
50
+ W = new Map;
51
+ });
52
+
53
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
54
+ var init_text = __esm(() => {
55
+ init_chunk_rkhsft4a();
56
+ });
53
57
 
54
58
  // ../kit/src/mode.ts
55
59
  import process2 from "process";
56
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
57
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
58
60
  function isSet(value) {
59
61
  return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
60
62
  }
@@ -71,12 +73,13 @@ function outputMode(stream = process2.stdout, env = process2.env) {
71
73
  function isInteractive(streams = process2) {
72
74
  return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
73
75
  }
76
+ var MODES, AGENT_VARIABLES;
77
+ var init_mode = __esm(() => {
78
+ MODES = new Set(["terminal", "ci", "agent", "pipe"]);
79
+ AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
80
+ });
74
81
 
75
- // ../kit/src/style.ts
76
- import process6 from "process";
77
-
78
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
79
- var G2 = /^[a-f0-9]+$/i;
82
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
80
83
  function b(r) {
81
84
  let e = r.startsWith("#") ? r.slice(1) : r;
82
85
  if (!G2.test(e))
@@ -87,11 +90,6 @@ function b(r) {
87
90
  throw Error(`Invalid hex color length: ${e.length}`);
88
91
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
89
92
  }
90
- var B2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
91
- let [l, n, c] = b(r);
92
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
93
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
94
- var h = new Set(["", "1", "2", "3", "true"]);
95
93
  function C(r, e = globalThis.process?.env ?? {}) {
96
94
  if (e.FORCE_COLOR !== undefined)
97
95
  return h.has(e.FORCE_COLOR);
@@ -105,7 +103,7 @@ function f(r, e = []) {
105
103
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
106
104
  let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
107
105
  return new Proxy(c, { get(t, i) {
108
- let a = B2[i];
106
+ let a = B[i];
109
107
  if (Array.isArray(a)) {
110
108
  let s = g.get(i);
111
109
  if (s === undefined)
@@ -128,13 +126,21 @@ function f(r, e = []) {
128
126
  function Fe(r = {}) {
129
127
  return f(r);
130
128
  }
131
- var o = Fe();
129
+ var G2, B, h, o;
130
+ var init_chunk_x450vn3m = __esm(() => {
131
+ G2 = /^[a-f0-9]+$/i;
132
+ B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
133
+ let [l, n, c] = b(r);
134
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
135
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
136
+ h = new Set(["", "1", "2", "3", "true"]);
137
+ o = Fe();
138
+ });
132
139
 
133
- // ../kit/src/theme.ts
134
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
135
- import { homedir as homedir2 } from "os";
136
- import { join as join3, resolve as resolve2 } from "path";
137
- import process5 from "process";
140
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
141
+ var init_colors = __esm(() => {
142
+ init_chunk_x450vn3m();
143
+ });
138
144
 
139
145
  // ../kit/src/config.ts
140
146
  import { existsSync } from "fs";
@@ -150,6 +156,9 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
150
156
  return;
151
157
  }
152
158
  }
159
+ var init_config = __esm(() => {
160
+ init_args();
161
+ });
153
162
 
154
163
  // ../kit/src/user-config.ts
155
164
  import { existsSync as existsSync2, readFileSync } from "fs";
@@ -185,36 +194,49 @@ function configuredNumber(bin, key, fallback, where = {}, legacy = []) {
185
194
  const value = readUserConfig(bin, where, legacy)[key];
186
195
  return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
187
196
  }
197
+ var init_user_config = () => {};
188
198
 
189
199
  // ../kit/src/theme.ts
190
- var ENDS = new Map;
191
- var DEFAULT = {
192
- colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
193
- glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
194
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
195
- bins: {},
196
- gradient: ["#c084fc", "#67e8f9"]
197
- };
198
- var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
199
- var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
200
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
201
- var PRESETS = {
202
- default: {},
203
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
204
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
205
- ascii: { glyphs: ASCII }
206
- };
207
- var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
208
- var HEX = /^#[0-9a-f]{6}$/i;
209
- var CONTROL = /\p{Cc}/u;
210
- var MAX_FILE_BYTES = 64 * 1024;
211
- var SPACES = /\s+/;
200
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
201
+ import { homedir as homedir2 } from "os";
202
+ import { join as join3, resolve as resolve2 } from "path";
203
+ import process5 from "process";
204
+ function toLinear(channel) {
205
+ const value = channel / 255;
206
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
207
+ }
208
+ function toOklab(hex) {
209
+ const [r, g, b] = [1, 3, 5].map((at) => toLinear(Number.parseInt(hex.slice(at, at + 2), 16)));
210
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
211
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
212
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
213
+ return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];
214
+ }
215
+ function fromOklab([lightness, a, b]) {
216
+ const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;
217
+ const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;
218
+ const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;
219
+ const channels = [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s];
220
+ return `#${channels.map((channel) => fromLinear(channel).toString(16).padStart(2, "0")).join("")}`;
221
+ }
222
+ function gradientAt(theme, ratio) {
223
+ if (theme.gradient === undefined)
224
+ return;
225
+ const key = theme.gradient.join();
226
+ let ends = ENDS.get(key);
227
+ if (ends === undefined) {
228
+ ends = [toOklab(theme.gradient[0]), toOklab(theme.gradient[1])];
229
+ ENDS.set(key, ends);
230
+ }
231
+ const at = Math.min(1, Math.max(0, ratio));
232
+ const [from, to] = ends;
233
+ return fromOklab(from.map((start, index) => start + (to[index] - start) * at));
234
+ }
212
235
  function isColorSpec(spec) {
213
236
  if (typeof spec === "number")
214
237
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
215
238
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
216
239
  }
217
- var CUBE = [0, 95, 135, 175, 215, 255];
218
240
  function cubeLevel(channel) {
219
241
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
220
242
  }
@@ -239,6 +261,9 @@ function tinted(colors, spec, env = process5.env) {
239
261
  return chain[token] ?? chain;
240
262
  }, colors);
241
263
  }
264
+ function shaded(theme, colors, glyph, cells, width, env = process5.env) {
265
+ return Array.from({ length: cells }, (_, index) => tinted(colors, gradientAt(theme, width <= 1 ? 0 : index / (width - 1)) ?? theme.colors.accent, env)(glyph)).join("");
266
+ }
242
267
  function isRecord(value) {
243
268
  return typeof value === "object" && value !== null && !Array.isArray(value);
244
269
  }
@@ -319,7 +344,6 @@ function applyFile(theme, file, where, warn) {
319
344
  function endsWalk(home) {
320
345
  return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
321
346
  }
322
- var warned = new Set;
323
347
  function warnOnce(message) {
324
348
  if (warned.has(message))
325
349
  return;
@@ -356,8 +380,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
356
380
  }
357
381
  return { theme, sources, preset };
358
382
  }
359
- var current;
360
- var currentKey = "";
361
383
  function activeTheme() {
362
384
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
363
385
  if (current === undefined || key !== currentKey) {
@@ -366,9 +388,38 @@ function activeTheme() {
366
388
  }
367
389
  return current;
368
390
  }
391
+ var fromLinear = (value) => Math.round(255 * Math.min(1, Math.max(0, value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055))), ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
392
+ var init_theme = __esm(() => {
393
+ init_config();
394
+ init_user_config();
395
+ ENDS = new Map;
396
+ DEFAULT = {
397
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
398
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
399
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
400
+ bins: {},
401
+ gradient: ["#c084fc", "#67e8f9"]
402
+ };
403
+ BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
404
+ MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
405
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
406
+ PRESETS = {
407
+ default: {},
408
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
409
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
410
+ ascii: { glyphs: ASCII }
411
+ };
412
+ STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
413
+ HEX = /^#[0-9a-f]{6}$/i;
414
+ CONTROL = /\p{Cc}/u;
415
+ MAX_FILE_BYTES = 64 * 1024;
416
+ SPACES = /\s+/;
417
+ CUBE = [0, 95, 135, 175, 215, 255];
418
+ warned = new Set;
419
+ });
369
420
 
370
421
  // ../kit/src/style.ts
371
- var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
422
+ import process6 from "process";
372
423
  function takesControlCodes(stream, env = process6.env) {
373
424
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
374
425
  }
@@ -397,14 +448,6 @@ function role(name, stream, env = process6.env) {
397
448
  const colors = paint(stream, env);
398
449
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
399
450
  }
400
- var STATUS_WORDS = {
401
- passed: ["passed", "success", "succeeded", "ok"],
402
- failed: ["failed", "failure", "error", "errored"],
403
- running: ["running", "in_progress", "started", "holding"],
404
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
405
- skipped: ["skipped", "cancelled", "canceled", "manual"]
406
- };
407
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
408
451
  function header(bin, context, stream, env = process6.env) {
409
452
  if (!takesControlCodes(stream, env))
410
453
  return "";
@@ -420,7 +463,23 @@ function printHeader(bin, context, stream = process6.stdout, env = process6.env)
420
463
  if (line !== "")
421
464
  console.log(line);
422
465
  }
423
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-knqbxp56.js
466
+ var MARK_WORDS, STATUS_WORDS, STATUS_OF;
467
+ var init_style = __esm(() => {
468
+ init_colors();
469
+ init_mode();
470
+ init_theme();
471
+ MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
472
+ STATUS_WORDS = {
473
+ passed: ["passed", "success", "succeeded", "ok"],
474
+ failed: ["failed", "failure", "error", "errored"],
475
+ running: ["running", "in_progress", "started", "holding"],
476
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
477
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
478
+ };
479
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
480
+ });
481
+
482
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-knqbxp56.js
424
483
  function tt(i, { units: r = "iec", dp: t = 1, locale: n } = {}) {
425
484
  let e = r === "si" ? 1000 : 1024;
426
485
  if (Math.abs(i) < e)
@@ -431,9 +490,17 @@ function tt(i, { units: r = "iec", dp: t = 1, locale: n } = {}) {
431
490
  while (Math.round(Math.abs(i) * a) / a >= e && o < s.length - 1);
432
491
  return `${n ? y(n, { minimumFractionDigits: t, maximumFractionDigits: t }).format(i) : i.toFixed(t)} ${s[o]}`;
433
492
  }
493
+ var init_chunk_knqbxp56 = __esm(() => {
494
+ init_chunk_n6z2kk96();
495
+ });
496
+
497
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/format/index.js
498
+ var init_format = __esm(() => {
499
+ init_chunk_knqbxp56();
500
+ });
434
501
 
435
502
  // ../kit/src/format.ts
436
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
503
+ import process7 from "process";
437
504
  function formatSeconds(total) {
438
505
  let rest = Math.max(0, Math.round(total));
439
506
  const amounts = UNITS.map(([unit, size]) => {
@@ -450,6 +517,9 @@ function formatSeconds(total) {
450
517
  function formatDuration(ms) {
451
518
  return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
452
519
  }
520
+ function formatElapsed(ms) {
521
+ return formatSeconds(Math.floor(Math.max(0, ms) / 1000));
522
+ }
453
523
  function upTo(text, separator) {
454
524
  const end = text.indexOf(separator);
455
525
  return end === -1 ? text : text.slice(0, end);
@@ -462,10 +532,8 @@ function formatAge(date, now = Date.now()) {
462
532
  return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
463
533
  }
464
534
  function truncate(text, width) {
465
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
535
+ return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
466
536
  }
467
- var LINE_BREAKS = /\s*\n\s*/g;
468
- var ESCAPE = String.fromCharCode(27);
469
537
  function textWidth(text) {
470
538
  return Bun.stringWidth(text);
471
539
  }
@@ -514,12 +582,19 @@ function jsonText(value, replacer, { stream = process7.stdout, env = process7.en
514
582
  function printJson(value) {
515
583
  console.log(jsonText(value));
516
584
  }
585
+ var UNITS, LINE_BREAKS, ESCAPE;
586
+ var init_format2 = __esm(() => {
587
+ init_text();
588
+ init_mode();
589
+ init_style();
590
+ init_format();
591
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
592
+ LINE_BREAKS = /\s*\n\s*/g;
593
+ ESCAPE = String.fromCharCode(27);
594
+ });
517
595
 
518
596
  // ../kit/src/help.ts
519
597
  import process8 from "process";
520
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
521
- var USAGE_PREFIX = /^usage:\s*/i;
522
- var FULL_STOP = /\.$/;
523
598
  function usageLine(usage, colors = paint(process8.stdout)) {
524
599
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
525
600
  }
@@ -556,7 +631,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
556
631
  return [];
557
632
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
558
633
  }
559
- var MAX_INLINE_CHOICES = 24;
560
634
  function optionRows(options, colors = paint(process8.stdout)) {
561
635
  const rows = Object.entries(options).map(([name, option]) => {
562
636
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -571,6 +645,14 @@ function optionRows(options, colors = paint(process8.stdout)) {
571
645
  const width = Math.max(0, ...rows.map((row) => row.width));
572
646
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
573
647
  }
648
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, MAX_INLINE_CHOICES = 24;
649
+ var init_help = __esm(() => {
650
+ init_mode();
651
+ init_style();
652
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
653
+ USAGE_PREFIX = /^usage:\s*/i;
654
+ FULL_STOP = /\.$/;
655
+ });
574
656
 
575
657
  // ../kit/src/text.ts
576
658
  function distance(a, b) {
@@ -598,9 +680,9 @@ function closest(name, names) {
598
680
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
599
681
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
600
682
  }
683
+ var init_text2 = () => {};
684
+
601
685
  // ../kit/src/input.ts
602
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
603
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
604
686
  function duration(value, name, fallback, unit = "s") {
605
687
  if (value === undefined)
606
688
  return fallback;
@@ -610,40 +692,26 @@ function duration(value, name, fallback, unit = "s") {
610
692
  badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
611
693
  return ms;
612
694
  }
695
+ var DURATION, UNIT_MS;
696
+ var init_input = __esm(() => {
697
+ init_args();
698
+ DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
699
+ UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
700
+ });
613
701
 
614
702
  // ../kit/src/args.ts
615
- var DASHES = /^-+/;
703
+ import process9 from "process";
704
+ import { parseArgs } from "util";
616
705
  function jsonOption(holds) {
617
706
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
618
707
  }
619
- class Exit extends Error {
620
- code;
621
- hint;
622
- constructor(message, code, hint) {
623
- super(message);
624
- this.code = code;
625
- this.hint = hint;
626
- }
627
- }
628
708
  function fail(message, code = 2, hint) {
629
709
  throw new Exit(message, code, hint);
630
710
  }
631
-
632
- class UsageError extends Exit {
633
- constructor(message, hint) {
634
- super(message, 2, hint);
635
- }
636
- }
637
711
  function badUsage(message) {
638
712
  throw new UsageError(message);
639
713
  }
640
714
 
641
- class HelpShown extends Exit {
642
- constructor() {
643
- super("help shown", 0);
644
- }
645
- }
646
-
647
715
  class Completing {
648
716
  options;
649
717
  positionals;
@@ -654,11 +722,6 @@ class Completing {
654
722
  this.candidates = candidates;
655
723
  }
656
724
  }
657
- var completion = { active: false };
658
- var OUTPUT_OPTIONS = {
659
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
660
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
661
- };
662
725
  function applyOutput(color, plain, env = process9.env) {
663
726
  const when = plain === true ? "never" : color ?? "auto";
664
727
  if (when === "auto")
@@ -812,7 +875,6 @@ function parseError(error) {
812
875
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
813
876
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
814
877
  }
815
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
816
878
  function nearestOption(message, options, allowNegative) {
817
879
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
818
880
  if (typed === undefined)
@@ -828,6 +890,303 @@ function nearestOption(message, options, allowNegative) {
828
890
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
829
891
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
830
892
  }
893
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
894
+ var init_args = __esm(() => {
895
+ init_format2();
896
+ init_help();
897
+ init_text2();
898
+ init_help();
899
+ init_input();
900
+ DASHES = /^-+/;
901
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
902
+ Exit = class Exit extends Error {
903
+ code;
904
+ hint;
905
+ [EXIT] = true;
906
+ constructor(message, code, hint) {
907
+ super(message);
908
+ this.code = code;
909
+ this.hint = hint;
910
+ }
911
+ static [Symbol.hasInstance](value) {
912
+ if (this !== Exit)
913
+ return Function.prototype[Symbol.hasInstance].call(this, value);
914
+ return typeof value === "object" && value !== null && value[EXIT] === true;
915
+ }
916
+ };
917
+ UsageError = class UsageError extends Exit {
918
+ constructor(message, hint) {
919
+ super(message, 2, hint);
920
+ }
921
+ };
922
+ HelpShown = class HelpShown extends Exit {
923
+ constructor() {
924
+ super("help shown", 0);
925
+ }
926
+ };
927
+ completion = { active: false };
928
+ OUTPUT_OPTIONS = {
929
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
930
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
931
+ };
932
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
933
+ });
934
+
935
+ // ../kit/src/folders.ts
936
+ var SKIPPED_FOLDERS;
937
+ var init_folders = __esm(() => {
938
+ init_user_config();
939
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
940
+ });
941
+
942
+ // ../kit/src/answers.ts
943
+ var init_answers = __esm(() => {
944
+ init_folders();
945
+ });
946
+
947
+ // ../kit/src/job.ts
948
+ import process24 from "process";
949
+ function stopJob() {
950
+ process24.kill(0, "SIGTSTP");
951
+ }
952
+ var init_job = () => {};
953
+
954
+ // ../kit/src/picker/line.ts
955
+ function isEditKey(key) {
956
+ return EDIT_KEYS.has(key);
957
+ }
958
+ var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS;
959
+ var init_line = __esm(() => {
960
+ EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
961
+ BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
962
+ FORWARD_KILLS = new Set(["killnext", "killend"]);
963
+ });
964
+
965
+ // ../kit/src/picker/score.ts
966
+ var BOUNDARY_AFTER, NONE;
967
+ var init_score = __esm(() => {
968
+ BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
969
+ NONE = Number.NEGATIVE_INFINITY;
970
+ });
971
+
972
+ // ../kit/src/picker/state.ts
973
+ function repeat(value, count) {
974
+ return Array.from({ length: count }).fill(value);
975
+ }
976
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
977
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
978
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
979
+ const wheel = MOUSE.exec(sequence)?.[1];
980
+ if (wheel !== undefined)
981
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
982
+ const named = codes.get(sequence);
983
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
984
+ if (sequence === PASTE_START || sequence === PASTE_END) {
985
+ paste.active = sequence === PASTE_START;
986
+ return [];
987
+ }
988
+ if (paste.active && (sequence === "\r" || sequence === `
989
+ `))
990
+ return [];
991
+ if (key !== undefined)
992
+ return [key];
993
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
994
+ });
995
+ }
996
+ var IS_CONTROL, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS;
997
+ var init_state = __esm(() => {
998
+ init_text2();
999
+ init_line();
1000
+ init_score();
1001
+ IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1002
+ KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1003
+ MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1004
+ KEYS = {
1005
+ "\x1B[A": "up",
1006
+ "\x1BOA": "up",
1007
+ "\x10": "up",
1008
+ "\x1B[B": "down",
1009
+ "\x1BOB": "down",
1010
+ "\x0E": "down",
1011
+ "\x1B[5~": "pageup",
1012
+ "\x1B[6~": "pagedown",
1013
+ "\x1B[H": "home",
1014
+ "\x1B[1~": "home",
1015
+ "\x1BOH": "home",
1016
+ "\x1B[F": "end",
1017
+ "\x1B[4~": "end",
1018
+ "\x1BOF": "end",
1019
+ "\r": "enter",
1020
+ "\n": "enter",
1021
+ "\x03": "cancel",
1022
+ "\x1B": "cancel",
1023
+ "\x1B[D": "left",
1024
+ "\x1BOD": "left",
1025
+ "\x1B[C": "right",
1026
+ "\x1BOC": "right",
1027
+ "\x1B[1;5D": "wordleft",
1028
+ "\x1B[1;3D": "wordleft",
1029
+ "\x1Bb": "wordleft",
1030
+ "\x1B[1;5C": "wordright",
1031
+ "\x1B[1;3C": "wordright",
1032
+ "\x1Bf": "wordright",
1033
+ "\x01": "linestart",
1034
+ "\x05": "lineend",
1035
+ "\x7F": "erase",
1036
+ "\x1B[3~": "delete",
1037
+ "\b": "killword",
1038
+ "\x1B\x7F": "killword",
1039
+ "\x1B[3;5~": "killnext",
1040
+ "\x1Bd": "killnext",
1041
+ "\x15": "clear",
1042
+ "\v": "killend",
1043
+ "\x17": "word",
1044
+ "\x19": "yank",
1045
+ "\x1A": "suspend",
1046
+ "\t": "tab",
1047
+ "\x1F": "help",
1048
+ "\x1BOP": "help",
1049
+ "\x1B[11~": "help"
1050
+ };
1051
+ });
1052
+
1053
+ // ../kit/src/redraw.ts
1054
+ function overwrite(lines, columns) {
1055
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1056
+ `);
1057
+ }
1058
+ function rowsTaken(lines, columns) {
1059
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1060
+ }
1061
+ var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
1062
+ var init_redraw = __esm(() => {
1063
+ init_format2();
1064
+ });
1065
+
1066
+ // ../kit/src/prompt.ts
1067
+ import process25 from "process";
1068
+ function readKeys(input, paste = { active: false }) {
1069
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
1070
+ }
1071
+ async function confirm(question, { default: fallback, ...settings } = {}) {
1072
+ let answered = fallback;
1073
+ const choices = { true: "Y/n", false: "y/N", undefined: "y/n" }[String(fallback)];
1074
+ const accepted = await ask(question, settings, (colors, state) => [state === "asking" ? asking(colors, question, "", choices) : answer(colors, question, state, answered ? "yes" : "no")], (key) => {
1075
+ if (key === "cancel")
1076
+ return "cancel";
1077
+ if (key === "enter")
1078
+ return answered === undefined ? undefined : "enter";
1079
+ const letter = typeof key === "object" ? key.text.toLowerCase() : "";
1080
+ if (letter !== "y" && letter !== "n")
1081
+ return;
1082
+ answered = letter === "y";
1083
+ return "enter";
1084
+ });
1085
+ return accepted ? answered : undefined;
1086
+ }
1087
+ function asking(colors, question, typed, keys) {
1088
+ return `${colors.cyan("?")} ${question} ${typed === "" ? colors.dim(`(${keys})`) : typed}`;
1089
+ }
1090
+ function answer(colors, question, state, picked) {
1091
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1092
+ }
1093
+ async function ask(question, { hint, terminal = process25 }, render, press) {
1094
+ const { stdin, stderr } = terminal;
1095
+ if (!isInteractive(terminal))
1096
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
1097
+ const colors = paint(stderr);
1098
+ let current = "asking";
1099
+ let outcome;
1100
+ const columns = () => stderr.columns || 80;
1101
+ const draw = (state, last = false) => {
1102
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1103
+ const rows = rowsTaken(frame, columns());
1104
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
1105
+ current = state;
1106
+ };
1107
+ const redraw = () => draw(current);
1108
+ const paste = { active: false };
1109
+ const stop = terminal.stop ?? (terminal === process25 ? stopJob : undefined);
1110
+ const suspend = () => {
1111
+ if (stop === undefined)
1112
+ return;
1113
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
1114
+ stdin.setRawMode(false);
1115
+ stop();
1116
+ stdin.setRawMode(true);
1117
+ stderr.write("\x1B[?25l\x1B[?2004h");
1118
+ };
1119
+ try {
1120
+ stderr.on?.("resize", redraw);
1121
+ stdin.setRawMode(true);
1122
+ stdin.resume();
1123
+ stderr.write("\x1B[?25l\x1B[?2004h");
1124
+ draw("asking");
1125
+ return await new Promise((resolve) => {
1126
+ function onData(data) {
1127
+ for (const key of readKeys(data.toString(), paste)) {
1128
+ if (key === "suspend") {
1129
+ suspend();
1130
+ continue;
1131
+ }
1132
+ const pressed = press(key);
1133
+ if (pressed !== undefined) {
1134
+ settle(pressed);
1135
+ return;
1136
+ }
1137
+ }
1138
+ draw("asking");
1139
+ }
1140
+ function onEnd() {
1141
+ settle("cancel");
1142
+ }
1143
+ function settle(settled) {
1144
+ outcome = settled;
1145
+ stdin.off("data", onData);
1146
+ stdin.off("end", onEnd);
1147
+ resolve(settled === "enter");
1148
+ }
1149
+ stdin.on("data", onData);
1150
+ stdin.on("end", onEnd);
1151
+ });
1152
+ } finally {
1153
+ stderr.off?.("resize", redraw);
1154
+ draw(outcome ?? "cancel", true);
1155
+ stderr.write(`
1156
+ \x1B[?25h\x1B[?2004l`);
1157
+ stdin.setRawMode(false);
1158
+ stdin.pause();
1159
+ }
1160
+ }
1161
+ var PROMPT_KEYS;
1162
+ var init_prompt = __esm(() => {
1163
+ init_answers();
1164
+ init_args();
1165
+ init_format2();
1166
+ init_job();
1167
+ init_mode();
1168
+ init_line();
1169
+ init_state();
1170
+ init_redraw();
1171
+ init_style();
1172
+ PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
1173
+ });
1174
+
1175
+ // src/cli.ts
1176
+ import process26 from "process";
1177
+
1178
+ // ../kit/src/advisory.ts
1179
+ var SEVERITIES = ["low", "moderate", "high", "critical"];
1180
+ function severityRank(severity) {
1181
+ return SEVERITIES.indexOf(severity);
1182
+ }
1183
+ function isIgnored(advisory, ignore) {
1184
+ return ignore.includes(advisory.ghsa ?? "") || ignore.includes(String(advisory.id));
1185
+ }
1186
+
1187
+ // ../kit/src/index.ts
1188
+ init_args();
1189
+
831
1190
  // ../kit/src/argv.ts
832
1191
  import { readFileSync as readFileSync3, realpathSync } from "fs";
833
1192
  import { resolve as resolve3 } from "path";
@@ -852,10 +1211,24 @@ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), scr
852
1211
  const after = at === -1 ? [] : cmdline.slice(at + 1);
853
1212
  return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
854
1213
  }
1214
+ // ../kit/src/chart.ts
1215
+ init_format2();
1216
+ init_mode();
1217
+ init_style();
1218
+ init_theme();
1219
+ // ../kit/src/ci.ts
1220
+ init_args();
1221
+ init_format2();
1222
+
1223
+ // ../kit/src/progress.ts
1224
+ init_format2();
1225
+ import process12 from "process";
1226
+
855
1227
  // ../kit/src/process.ts
856
1228
  import { constants } from "os";
857
1229
  import process11 from "process";
858
1230
  var KILL_GRACE_MS = 2000;
1231
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
859
1232
  function exitCodeOf(code, signal) {
860
1233
  if (code !== null)
861
1234
  return code;
@@ -863,10 +1236,41 @@ function exitCodeOf(code, signal) {
863
1236
  return 128 + signal;
864
1237
  return signal === null ? 129 : 128 + constants.signals[signal];
865
1238
  }
866
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
1239
+ function holdSignals(cleanup) {
1240
+ let received;
1241
+ let child;
1242
+ const held = {
1243
+ get signal() {
1244
+ return received;
1245
+ },
1246
+ forward: (to) => {
1247
+ child = to;
1248
+ },
1249
+ release: () => {
1250
+ for (const signal of SIGNALS)
1251
+ process11.off(signal, onSignal);
1252
+ }
1253
+ };
1254
+ function onSignal(signal) {
1255
+ received = signal;
1256
+ if (child !== undefined) {
1257
+ child.kill(signal);
1258
+ return;
1259
+ }
1260
+ if (cleanup === undefined)
1261
+ return;
1262
+ held.release();
1263
+ cleanup(signal);
1264
+ process11.kill(process11.pid, signal);
1265
+ }
1266
+ for (const signal of SIGNALS)
1267
+ process11.on(signal, onSignal);
1268
+ return held;
1269
+ }
1270
+ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
867
1271
  const chunks = [];
868
1272
  const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
869
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
1273
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin: input === undefined ? stdin : new TextEncoder().encode(input), stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
870
1274
  const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
871
1275
  const timers = [];
872
1276
  const killGroup = (killing) => {
@@ -942,17 +1346,234 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
942
1346
  };
943
1347
  }
944
1348
 
945
- // ../kit/src/progress.ts
946
- var ESC = String.fromCharCode(27);
947
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
948
- var RESET_STYLE = `${ESC}[0m`;
949
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1349
+ // ../kit/src/progress.ts
1350
+ init_style();
1351
+ init_theme();
1352
+ var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1353
+ var FRAME_MS = 200;
1354
+ var BAR_WIDTH = 20;
1355
+ var CLEAR_BELOW = "\r\x1B[J";
1356
+ var ESC = String.fromCharCode(27);
1357
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
1358
+ var RESET_STYLE = `${ESC}[0m`;
1359
+ var CTRL_C = 3;
1360
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1361
+ var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
1362
+ function liveRegion(render, stream = process12.stderr, env = process12.env) {
1363
+ if (!takesControlCodes(stream, env))
1364
+ return { redraw: () => {
1365
+ return;
1366
+ }, print: (text) => void stream.write(`${text}
1367
+ `), stop: () => {
1368
+ return;
1369
+ }, pause: () => () => {
1370
+ return;
1371
+ } };
1372
+ const write = stream.write.bind(stream);
1373
+ let frame = 0;
1374
+ let drawn = false;
1375
+ let paused = false;
1376
+ let stopped = false;
1377
+ const columns = () => {
1378
+ const now = stream.getWindowSize?.()[0] ?? stream.columns;
1379
+ return now === undefined || now === 0 ? 80 : now;
1380
+ };
1381
+ const clear = () => {
1382
+ if (drawn)
1383
+ write(CLEAR_BELOW);
1384
+ drawn = false;
1385
+ };
1386
+ const draw = () => {
1387
+ if (paused)
1388
+ return;
1389
+ const width = columns() - 1;
1390
+ const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
1391
+ const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
1392
+ if (lines.length === 0) {
1393
+ clear();
1394
+ return;
1395
+ }
1396
+ write(`${CLEAR_BELOW}${lines.join(`
1397
+ `)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
1398
+ drawn = true;
1399
+ };
1400
+ let timer = setInterval(draw, FRAME_MS);
1401
+ stream.on?.("resize", draw);
1402
+ let restore = interceptOutput(clear);
1403
+ let release = swallowInput();
1404
+ const onExit = () => {
1405
+ clear();
1406
+ release();
1407
+ };
1408
+ const signals = holdSignals(stop);
1409
+ function stop() {
1410
+ stopped = true;
1411
+ clearInterval(timer);
1412
+ stream.off?.("resize", draw);
1413
+ clear();
1414
+ restore();
1415
+ release();
1416
+ process12.off("exit", onExit);
1417
+ signals.release();
1418
+ }
1419
+ function pause() {
1420
+ if (paused || stopped)
1421
+ return () => {
1422
+ return;
1423
+ };
1424
+ paused = true;
1425
+ clearInterval(timer);
1426
+ stream.off?.("resize", draw);
1427
+ clear();
1428
+ restore();
1429
+ release();
1430
+ return () => {
1431
+ if (!paused || stopped)
1432
+ return;
1433
+ paused = false;
1434
+ timer = setInterval(draw, FRAME_MS);
1435
+ timer.unref();
1436
+ stream.on?.("resize", draw);
1437
+ restore = interceptOutput(clear);
1438
+ release = swallowInput();
1439
+ draw();
1440
+ };
1441
+ }
1442
+ timer.unref();
1443
+ process12.on("exit", onExit);
1444
+ return {
1445
+ redraw: draw,
1446
+ print: (text) => {
1447
+ clear();
1448
+ write(`${text}
1449
+ `);
1450
+ draw();
1451
+ },
1452
+ stop,
1453
+ pause
1454
+ };
1455
+ }
1456
+ function progressLine(stream = process12.stderr, env = process12.env) {
1457
+ const colors = paint(stream, env);
1458
+ const write = stream.write.bind(stream);
1459
+ const begun = performance.now();
1460
+ let started = begun;
1461
+ let current;
1462
+ const region = liveRegion((spinner) => current === undefined ? [] : [tintedParts(progressParts(current, spinner, performance.now() - started), colors)], stream, env);
1463
+ const end = (line) => {
1464
+ region.stop();
1465
+ write(`${line}
1466
+ `);
1467
+ };
1468
+ return {
1469
+ update: (progress) => {
1470
+ const step = current?.step;
1471
+ current = progress;
1472
+ if (progress.step !== step) {
1473
+ started = performance.now();
1474
+ region.redraw();
1475
+ }
1476
+ },
1477
+ stop: region.stop,
1478
+ pause: region.pause,
1479
+ done: (text) => end(marked("ok", text, stream, formatDuration(performance.now() - begun), env)),
1480
+ failed: (text) => end(marked("problem", text, stream, undefined, env))
1481
+ };
1482
+ }
1483
+ function progressParts({ step, done, total, unit }, spinner, ms) {
1484
+ const { theme } = activeTheme();
1485
+ const parts = [{ text: spinner, tint: (colors) => tinted(colors, theme.colors.accent) }, { text: ` ${step}`, tint: () => plain }];
1486
+ if (total !== undefined && total > 0) {
1487
+ const counted = Math.min(done ?? 0, total);
1488
+ const filled = Math.round(counted / total * BAR_WIDTH);
1489
+ parts.push({ text: " ", tint: () => plain }, { text: theme.glyphs.bar.repeat(filled), tint: (colors) => () => shaded(theme, colors, theme.glyphs.bar, filled, BAR_WIDTH) }, { text: theme.glyphs.bar.repeat(BAR_WIDTH - filled), tint: (colors) => colors.dim }, { text: ` ${counted}/${total}${unit === undefined ? "" : ` ${unit}`}`, tint: (colors) => colors.dim });
1490
+ }
1491
+ parts.push({ text: ` ${formatElapsed(ms)}`, tint: (colors) => colors.dim });
1492
+ return parts;
1493
+ }
1494
+ function plain(text) {
1495
+ return text;
1496
+ }
1497
+ function tintedParts(parts, colors) {
1498
+ return parts.map(({ text, tint }) => tint(colors)(text)).join("");
1499
+ }
1500
+ function cutToWidth(line, width) {
1501
+ if (Bun.stringWidth(line) <= width)
1502
+ return line;
1503
+ let room = width;
1504
+ let kept = "";
1505
+ let index = 0;
1506
+ let linked = false;
1507
+ while (index < line.length) {
1508
+ ESCAPE_CODE.lastIndex = index;
1509
+ const escape = ESCAPE_CODE.exec(line);
1510
+ if (escape !== null) {
1511
+ kept += escape[0];
1512
+ linked ||= escape[0].startsWith(`${ESC}]`);
1513
+ index = ESCAPE_CODE.lastIndex;
1514
+ continue;
1515
+ }
1516
+ const char = String.fromCodePoint(line.codePointAt(index));
1517
+ const columns = Bun.stringWidth(char);
1518
+ if (columns > room)
1519
+ break;
1520
+ kept += char;
1521
+ room -= columns;
1522
+ index += char.length;
1523
+ }
1524
+ return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
1525
+ }
1526
+ function swallowInput() {
1527
+ const input = process12.stdin;
1528
+ if (!input.isTTY)
1529
+ return () => {
1530
+ return;
1531
+ };
1532
+ const onData = (data) => {
1533
+ if (data.includes(CTRL_C))
1534
+ process12.kill(process12.pid, "SIGINT");
1535
+ };
1536
+ input.setRawMode(true);
1537
+ input.on("data", onData);
1538
+ input.resume();
1539
+ let released = false;
1540
+ return () => {
1541
+ if (released)
1542
+ return;
1543
+ released = true;
1544
+ input.off("data", onData);
1545
+ input.pause();
1546
+ input.setRawMode(false);
1547
+ };
1548
+ }
1549
+ function interceptOutput(clear) {
1550
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
1551
+ const wrapped = targets.map(([target, name]) => {
1552
+ const original = Reflect.get(target, name);
1553
+ const wrapper = (...args) => {
1554
+ clear();
1555
+ return original.apply(target, args);
1556
+ };
1557
+ Reflect.set(target, name, wrapper);
1558
+ return { target, name, original, wrapper };
1559
+ });
1560
+ return () => {
1561
+ for (const { target, name, original, wrapper } of wrapped) {
1562
+ if (Reflect.get(target, name) === wrapper)
1563
+ Reflect.set(target, name, original);
1564
+ }
1565
+ };
1566
+ }
1567
+
1568
+ // ../kit/src/ci.ts
1569
+ init_style();
950
1570
 
951
1571
  // ../kit/src/tool.ts
952
- import process12 from "process";
1572
+ init_format2();
1573
+ import process13 from "process";
953
1574
  function cwdGone() {
954
1575
  try {
955
- process12.cwd();
1576
+ process13.cwd();
956
1577
  return false;
957
1578
  } catch {
958
1579
  return true;
@@ -971,10 +1592,10 @@ function spawnFailure(command, error) {
971
1592
  const missing = !gone && error?.code === "ENOENT";
972
1593
  return new SpawnError(`${command}: ${error instanceof Error ? error.message : String(error)}${gone ? " (the working directory was removed)" : ""}`, missing);
973
1594
  }
974
- async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
1595
+ async function runTool(label, argv, { timeoutMs, cwd, onStart, env } = {}) {
975
1596
  let ran;
976
1597
  try {
977
- ran = await runCommand(argv, { env: process12.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
1598
+ ran = await runCommand(argv, { env: { ...process13.env, ...env }, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
978
1599
  } catch (error) {
979
1600
  throw spawnFailure(label, error);
980
1601
  }
@@ -989,33 +1610,139 @@ async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
989
1610
  return { code: ran.code, ...streams };
990
1611
  }
991
1612
  // ../kit/src/cli.ts
1613
+ init_args();
992
1614
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
993
1615
  import { dirname as dirname3, join as join5 } from "path";
994
- import process15 from "process";
1616
+ import process17 from "process";
1617
+
1618
+ // ../kit/src/askpass.ts
1619
+ import process14 from "process";
1620
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1621
+ async function askpassClient(argv) {
1622
+ const socketPath = process14.env[SOCKET_VARIABLE];
1623
+ if (socketPath === undefined)
1624
+ return;
1625
+ const request = { prompt: argv[0] ?? "", ...process14.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1626
+ const { promise, resolve } = Promise.withResolvers();
1627
+ let received = "";
1628
+ try {
1629
+ await Bun.connect({
1630
+ unix: socketPath,
1631
+ socket: {
1632
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
1633
+ `),
1634
+ data: (_, chunk) => {
1635
+ received += chunk.toString();
1636
+ },
1637
+ close: () => resolve(received),
1638
+ error: () => resolve("")
1639
+ }
1640
+ });
1641
+ } catch {
1642
+ return 1;
1643
+ }
1644
+ const reply = await promise;
1645
+ if (reply === "")
1646
+ return 1;
1647
+ const { answer } = JSON.parse(reply);
1648
+ if (request.notice === true)
1649
+ return 0;
1650
+ if (answer === undefined)
1651
+ return 1;
1652
+ process14.stdout.write(`${answer}
1653
+ `);
1654
+ return 0;
1655
+ }
1656
+
1657
+ // ../kit/src/completions.ts
1658
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1659
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
1660
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1661
+ set -l current (commandline -ct)
1662
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1663
+ if test "$line" = __files__
1664
+ __fish_complete_path $current
1665
+ else
1666
+ echo $line
1667
+ end
1668
+ end
1669
+ end`;
1670
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1671
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1672
+ local -a lines
1673
+ COMPREPLY=()
1674
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1675
+ for line in "\${lines[@]}"; do
1676
+ if [[ $line == __files__ ]]; then
1677
+ COMPREPLY+=($(compgen -f -- "$cur"))
1678
+ else
1679
+ words+="\${line%%$'\\t'*}"$'\\n'
1680
+ fi
1681
+ done
1682
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1683
+ }`;
1684
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1685
+ local line
1686
+ local -a described plain
1687
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1688
+ if [[ $line == __files__ ]]; then
1689
+ _files
1690
+ elif [[ $line == *$'\\t'* ]]; then
1691
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1692
+ else
1693
+ plain+=("$line")
1694
+ fi
1695
+ done
1696
+ (( \${#described} )) && _describe -V value described
1697
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1698
+ return 0
1699
+ }`;
1700
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1701
+ if (shell === "fish")
1702
+ return `${header}
1703
+ ${FISH_FUNCTION}
1704
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1705
+ `).join("")}`;
1706
+ if (shell === "bash")
1707
+ return `${header}
1708
+ ${BASH_FUNCTION}
1709
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1710
+ `;
1711
+ return `${header}
1712
+ ${ZSH_FUNCTION}
1713
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1714
+ `;
1715
+ }
995
1716
 
996
1717
  // ../kit/src/notify.ts
997
- import process13 from "process";
1718
+ init_format2();
1719
+ init_mode();
1720
+ import process15 from "process";
998
1721
  var NOTIFY_AFTER_MS = 1e4;
999
1722
  var CANCELLED = 130;
1000
1723
  function base64(text) {
1001
1724
  return Buffer.from(text).toString("base64");
1002
1725
  }
1003
- function notification(title, body, env = process13.env) {
1004
- const id = `kit${process13.pid}`;
1726
+ function notification(title, body, env = process15.env) {
1727
+ const id = `kit${process15.pid}`;
1005
1728
  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
1729
  return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1007
1730
  }
1008
- function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1731
+ function notifyEnd(command, code, ms, { stream = process15.stderr, env = process15.env } = {}) {
1009
1732
  if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1010
1733
  return;
1011
1734
  stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1012
1735
  }
1013
1736
 
1737
+ // ../kit/src/cli.ts
1738
+ init_style();
1739
+ init_text2();
1740
+
1014
1741
  // ../kit/src/usage.ts
1015
1742
  import { appendFileSync, mkdirSync } from "fs";
1016
1743
  import { homedir as homedir3 } from "os";
1017
1744
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1018
- import process14 from "process";
1745
+ import process16 from "process";
1019
1746
 
1020
1747
  // ../kit/src/logs.ts
1021
1748
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -1029,14 +1756,14 @@ var usageError;
1029
1756
  function noteUsageError(message) {
1030
1757
  usageError = message;
1031
1758
  }
1032
- function stateHome(env = process14.env) {
1759
+ function stateHome(env = process16.env) {
1033
1760
  const dir = env.XDG_STATE_HOME;
1034
1761
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1035
1762
  }
1036
- function usagePath(env = process14.env) {
1763
+ function usagePath(env = process16.env) {
1037
1764
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1038
1765
  }
1039
- function usageRecorded(env = process14.env) {
1766
+ function usageRecorded(env = process16.env) {
1040
1767
  const off = env.KAYNOOO_CLI_NO_USAGE;
1041
1768
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1042
1769
  }
@@ -1045,12 +1772,12 @@ function flagNames(argv) {
1045
1772
  const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1046
1773
  return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1047
1774
  }
1048
- function usageEntry(bin, command, argv, code, now = new Date) {
1775
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1049
1776
  const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1050
1777
  usageError = undefined;
1051
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1778
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1052
1779
  }
1053
- function recordUsage(entry, env = process14.env) {
1780
+ function recordUsage(entry, env = process16.env) {
1054
1781
  if (!usageRecorded(env))
1055
1782
  return;
1056
1783
  try {
@@ -1066,7 +1793,11 @@ var LEVEL_OPTIONS = {
1066
1793
  ...OUTPUT_OPTIONS,
1067
1794
  help: { type: "boolean", short: "h", description: "show this help" }
1068
1795
  };
1069
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1796
+ var TOP_OPTIONS = {
1797
+ ...LEVEL_OPTIONS,
1798
+ version: { type: "boolean", short: "v", description: "print the version" },
1799
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1800
+ };
1070
1801
  async function commandRows(all, colors) {
1071
1802
  const commands = shown(all);
1072
1803
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -1140,8 +1871,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1140
1871
  `);
1141
1872
  }
1142
1873
  function printError(prefix, message, hint, cause) {
1143
- const colors = paint(process15.stderr);
1144
- const styled = takesControlCodes(process15.stderr);
1874
+ const colors = paint(process17.stderr);
1875
+ const styled = takesControlCodes(process17.stderr);
1145
1876
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1146
1877
  const under = (label, text, tint) => text === undefined ? "" : `
1147
1878
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1184,11 +1915,11 @@ async function dispatch(level, typed, { version, redact }) {
1184
1915
  }
1185
1916
  }
1186
1917
  if (name === undefined && level.path.length > 1) {
1187
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
1918
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process17.stderr));
1188
1919
  return 2;
1189
1920
  }
1190
1921
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1191
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
1922
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process17.stdout));
1192
1923
  return 0;
1193
1924
  }
1194
1925
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1299,6 +2030,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1299
2030
  }
1300
2031
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1301
2032
  }
2033
+ var COMPLETIONS = "--completions";
2034
+ function flagValue([flag = "", ...rest]) {
2035
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
2036
+ }
2037
+ function printCompletionScript(name, args) {
2038
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
2039
+ if (shell === undefined || args.length !== 1) {
2040
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
2041
+ return 2;
2042
+ }
2043
+ console.log(completionScript(shell, [name]).trimEnd());
2044
+ return 0;
2045
+ }
1302
2046
  async function printCandidates(found) {
1303
2047
  for (const line of await found)
1304
2048
  console.log(line);
@@ -1321,15 +2065,20 @@ function packageVersion(entry = Bun.main) {
1321
2065
  }
1322
2066
  async function runCli(cli, argv = scriptArgs()) {
1323
2067
  const version = cli.version ?? packageVersion();
2068
+ const answered = await askpassClient(argv);
2069
+ if (answered !== undefined)
2070
+ return answered;
1324
2071
  if (argv[0] === COMPLETE)
1325
2072
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
2073
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
2074
+ return printCompletionScript(cli.name, flagValue(argv));
1326
2075
  const started = performance.now();
1327
2076
  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
2077
  const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1329
2078
  notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1330
2079
  if (cli.usage !== false) {
1331
2080
  try {
1332
- recordUsage(usageEntry(cli.name, command, argv, code));
2081
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
1333
2082
  } catch {}
1334
2083
  }
1335
2084
  return code;
@@ -1349,43 +2098,43 @@ function commandPath(scope, argv) {
1349
2098
  }
1350
2099
  return path.length === 0 ? undefined : path.join(" ");
1351
2100
  }
1352
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1353
- if (argv[0] === COMPLETE)
1354
- return printCandidates(leafCandidates(run, argv.slice(1)));
1355
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1356
- console.log(version ?? packageVersion());
1357
- return 0;
1358
- }
1359
- let code;
1360
- const started = performance.now();
1361
- try {
1362
- code = await run(argv);
1363
- } catch (error) {
1364
- code = reportThrown(name, error, redact, wantsJson(argv));
1365
- }
1366
- notifyEnd(name, code, performance.now() - started);
1367
- if (usage !== false) {
1368
- try {
1369
- recordUsage(usageEntry(name, undefined, argv, code));
1370
- } catch {}
1371
- }
1372
- return code;
1373
- }
1374
- // ../kit/src/folders.ts
1375
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
2101
+
2102
+ // ../kit/src/index.ts
2103
+ init_config();
2104
+
2105
+ // ../kit/src/excerpt.ts
2106
+ init_text2();
2107
+
2108
+ // ../kit/src/index.ts
2109
+ init_folders();
2110
+ init_format2();
2111
+
2112
+ // ../kit/src/git.ts
2113
+ init_args();
2114
+ // ../kit/src/limit.ts
2115
+ init_args();
2116
+
2117
+ // ../kit/src/index.ts
2118
+ init_mode();
2119
+
1376
2120
  // ../kit/src/pool.ts
1377
- async function pool(items, limit, task) {
2121
+ async function pool(items, limit, task, onDone) {
1378
2122
  const results = Array.from({ length: items.length });
1379
2123
  let next = 0;
2124
+ let done = 0;
1380
2125
  async function worker() {
1381
2126
  while (next < items.length) {
1382
2127
  const index = next++;
1383
2128
  results[index] = await task(items[index]);
2129
+ onDone?.(++done, items.length);
1384
2130
  }
1385
2131
  }
1386
2132
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1387
2133
  return results;
1388
2134
  }
2135
+ // ../kit/src/report.ts
2136
+ init_style();
2137
+ init_text2();
1389
2138
  // ../kit/src/secrets.ts
1390
2139
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1391
2140
  // ../kit/src/sessions.ts
@@ -1402,8 +2151,18 @@ function parseSize(text, bareUnit = 1) {
1402
2151
  const suffix = match[2].toLowerCase();
1403
2152
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1404
2153
  }
2154
+
2155
+ // ../kit/src/index.ts
2156
+ init_style();
2157
+ init_text2();
2158
+ init_theme();
2159
+ init_user_config();
2160
+
1405
2161
  // ../kit/src/watch.ts
1406
- import process16 from "process";
2162
+ init_args();
2163
+ init_input();
2164
+ init_style();
2165
+ import process18 from "process";
1407
2166
  import { format } from "util";
1408
2167
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1409
2168
  var DEFAULT_SECONDS = 2;
@@ -1425,7 +2184,7 @@ function withoutWatch(args) {
1425
2184
  }
1426
2185
  return rest;
1427
2186
  }
1428
- async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
2187
+ async function watching(value, step, stream = process18.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1429
2188
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1430
2189
  if (!takesControlCodes(stream))
1431
2190
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1433,12 +2192,12 @@ async function watching(value, step, stream = process16.stdout, sleep = Bun.slee
1433
2192
  for (let round = 0;round < rounds; round++) {
1434
2193
  const held = [];
1435
2194
  const { log, info } = console;
1436
- const write = process16.stdout.write.bind(process16.stdout);
2195
+ const write = process18.stdout.write.bind(process18.stdout);
1437
2196
  const hold = (...parts) => void held.push(`${format(...parts)}
1438
2197
  `);
1439
2198
  console.log = hold;
1440
2199
  console.info = hold;
1441
- process16.stdout.write = (text) => {
2200
+ process18.stdout.write = (text) => {
1442
2201
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1443
2202
  return true;
1444
2203
  };
@@ -1447,7 +2206,7 @@ async function watching(value, step, stream = process16.stdout, sleep = Bun.slee
1447
2206
  } finally {
1448
2207
  console.log = log;
1449
2208
  console.info = info;
1450
- process16.stdout.write = write;
2209
+ process18.stdout.write = write;
1451
2210
  }
1452
2211
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1453
2212
  await sleep(interval);
@@ -1455,9 +2214,10 @@ async function watching(value, step, stream = process16.stdout, sleep = Bun.slee
1455
2214
  return code;
1456
2215
  }
1457
2216
  // ../kit/src/workspace-root.ts
2217
+ init_user_config();
1458
2218
  import { homedir as homedir4 } from "os";
1459
2219
  import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
1460
- import process17 from "process";
2220
+ import process19 from "process";
1461
2221
  function expandHome(path, home) {
1462
2222
  if (path === "~")
1463
2223
  return home;
@@ -1467,7 +2227,7 @@ function configured(env, home) {
1467
2227
  const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
1468
2228
  return typeof folder === "string" && folder !== "" ? folder : undefined;
1469
2229
  }
1470
- function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
2230
+ function workspaceRoot({ given, env = process19.env, home = homedir4() } = {}) {
1471
2231
  const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1472
2232
  return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1473
2233
  }
@@ -1475,7 +2235,7 @@ function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
1475
2235
  import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync7, statSync as statSync2 } from "fs";
1476
2236
  import { readdir } from "fs/promises";
1477
2237
  import { join as join9, relative, resolve as resolve5 } from "path";
1478
- import process19 from "process";
2238
+ import process21 from "process";
1479
2239
 
1480
2240
  // src/osv.ts
1481
2241
  import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
@@ -1704,7 +2464,7 @@ async function osvAudit(dir, level, ignore, fetcher = fetch) {
1704
2464
  }
1705
2465
 
1706
2466
  // src/audit.ts
1707
- var USAGE = `audit [options] [root]: the known vulnerabilities of the Bun, Composer, Cargo and uv repositories under root (the current folder by default), one table per repository
2467
+ var USAGE = `ws audit [options] [root]: the known vulnerabilities of the Bun, Composer, Cargo and uv repositories under root (the current folder by default), one table per repository
1708
2468
 
1709
2469
  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.
1710
2470
  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, and asks osv.dev about the packages of a composer.lock, Cargo.lock or uv.lock (a severity the source leaves out reads as moderate, and only composer's manifest tells direct from pulled in); the walk goes three levels deep, stops at a lockfile and skips node_modules and hidden folders.
@@ -1812,7 +2572,7 @@ function failure(ran) {
1812
2572
  `).at(-1) ?? `exit ${ran.code}`;
1813
2573
  }
1814
2574
  function tint(severity) {
1815
- const colors = paint(process19.stdout);
2575
+ const colors = paint(process21.stdout);
1816
2576
  if (severity === "critical" || severity === "high")
1817
2577
  return colors.red;
1818
2578
  return severity === "moderate" ? colors.yellow : colors.dim;
@@ -1828,15 +2588,23 @@ function rows(findings) {
1828
2588
  ]);
1829
2589
  }
1830
2590
  async function audit(args) {
1831
- 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"] });
2591
+ 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: ["ws audit", "ws audit ~/Workspace --level high --prod"] });
1832
2592
  const root = resolve5(positionals[0] ?? ".");
1833
2593
  if (!existsSync6(root) || !statSync2(root).isDirectory())
1834
2594
  fail(`no folder ${root}`);
1835
2595
  const level = oneOf(values.level, "level", SEVERITIES);
1836
- const paths = await findRepos(root);
1837
- if (paths.length === 0)
1838
- fail(`no bun.lock, composer.lock, Cargo.lock or uv.lock under ${root}`);
1839
- const audits = await pool(paths, configuredNumber("audit", "concurrency", CONCURRENCY), async (path) => audited(path, relative(root, path) || ".", level, values.ignore ?? []));
2596
+ const progress = progressLine();
2597
+ let audits;
2598
+ try {
2599
+ progress.update({ step: "finding the repositories" });
2600
+ const paths = await findRepos(root);
2601
+ if (paths.length === 0)
2602
+ fail(`no bun.lock, composer.lock, Cargo.lock or uv.lock under ${root}`);
2603
+ progress.update({ step: "auditing", done: 0, total: paths.length, unit: "repositories" });
2604
+ audits = await pool(paths, configuredNumber("audit", "concurrency", CONCURRENCY), async (path) => audited(path, relative(root, path) || ".", level, values.ignore ?? []), (done, total) => progress.update({ step: "auditing", done, total, unit: "repositories" }));
2605
+ } finally {
2606
+ progress.stop();
2607
+ }
1840
2608
  const kept = audits.map((each) => ({ ...each, findings: values.prod === true ? each.findings.filter((found) => found.scope === "prod") : each.findings }));
1841
2609
  if (values.json === true)
1842
2610
  printJson(kept);
@@ -1847,8 +2615,8 @@ async function audit(args) {
1847
2615
  return kept.some((each) => each.findings.length > 0) ? 1 : 0;
1848
2616
  }
1849
2617
  function show(audits, total) {
1850
- const label = role("label", process19.stdout);
1851
- const path = role("path", process19.stdout);
2618
+ const label = role("label", process21.stdout);
2619
+ const path = role("path", process21.stdout);
1852
2620
  const flagged = audits.filter((each) => each.error !== undefined || each.findings.length > 0);
1853
2621
  if (flagged.length === 0) {
1854
2622
  console.log(label(`no advisory in ${total} ${total === 1 ? "repository" : "repositories"}`));
@@ -1870,13 +2638,13 @@ function show(audits, total) {
1870
2638
  // src/repos.ts
1871
2639
  import { existsSync as existsSync8, statSync as statSync3 } from "fs";
1872
2640
  import { basename as basename2, relative as relative2 } from "path";
1873
- import process21 from "process";
2641
+ import process23 from "process";
1874
2642
 
1875
2643
  // src/repos-scan.ts
1876
2644
  import { existsSync as existsSync7 } from "fs";
1877
2645
  import { readdir as readdir2 } from "fs/promises";
1878
2646
  import { basename, join as join10 } from "path";
1879
- import process20 from "process";
2647
+ import process22 from "process";
1880
2648
  var MAX_DEPTH2 = 3;
1881
2649
  var CONCURRENCY2 = 8;
1882
2650
  var PACKAGE_CONCURRENCY = 4;
@@ -1923,7 +2691,7 @@ async function findRepos2(root, skip) {
1923
2691
  }
1924
2692
  async function read(path, args, timeoutMs = GIT_MS) {
1925
2693
  try {
1926
- const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...process20.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs });
2694
+ const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...process22.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs });
1927
2695
  return ran.code === 0 && !ran.timedOut ? ran.text.trim() : undefined;
1928
2696
  } catch {
1929
2697
  return;
@@ -2000,7 +2768,7 @@ function firstLine(text) {
2000
2768
  }
2001
2769
  async function fastForward(path) {
2002
2770
  try {
2003
- const ran = await runCommand(["git", "--no-optional-locks", "merge", "--ff-only", "--quiet", "@{upstream}"], { cwd: path, env: { ...process20.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs: GIT_MS });
2771
+ const ran = await runCommand(["git", "--no-optional-locks", "merge", "--ff-only", "--quiet", "@{upstream}"], { cwd: path, env: { ...process22.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs: GIT_MS });
2004
2772
  if (ran.timedOut)
2005
2773
  return "timed out";
2006
2774
  return ran.code === 0 ? undefined : firstLine(ran.text.trim()) || `exit ${ran.code}`;
@@ -2010,9 +2778,9 @@ async function fastForward(path) {
2010
2778
  }
2011
2779
 
2012
2780
  // src/repos.ts
2013
- var USAGE2 = `repos [options] [root]: the git repositories under root (the configured workspace, ~/Workspace by default) that need attention, with their branch, dirty files, ahead/behind their upstream, linked worktrees and commits since their latest tag
2781
+ var USAGE2 = `ws repos [options] [root]: the git repositories under root (the configured workspace, ~/Workspace by default) that need attention, with their branch, dirty files, ahead/behind their upstream, linked worktrees and commits since their latest tag
2014
2782
 
2015
- A repository with nothing to report is left out unless --all. A monorepo tagging its packages <folder>-v<version> counts the unreleased commits per package folder. The walk goes ${MAX_DEPTH2} levels deep, stops at a .git and skips node_modules, hidden folders and the names in "skip" of ~/.config/kaynooo-cli/repos.json.
2783
+ A repository with nothing to report, or only unreleased commits, is left out unless --all or --only unreleased. A monorepo tagging its packages <folder>-v<version> counts the unreleased commits per package folder. The walk goes ${MAX_DEPTH2} levels deep, stops at a .git and skips node_modules, hidden folders and the names in "skip" of ~/.config/kaynooo-cli/repos.json.
2016
2784
 
2017
2785
  Ahead and behind are those of the last fetch unless --fetch refreshes the upstreams first, which reaches the remote.
2018
2786
  --pull fetches, then fast-forwards the repositories listed that are clean, on a branch and only behind their upstream, and touches nothing else: a dirty, ahead, diverged or detached one is reported as skipped. A repository pulled is listed again as it now stands.
@@ -2020,7 +2788,7 @@ Ahead and behind are those of the last fetch unless --fetch refreshes the upstre
2020
2788
  var EXITS2 = [[0, "it listed the repositories, including when none needs attention"], [1, "a fast-forward --pull attempted failed"], [2, "a usage error, an unreadable config or a root that is no folder"]];
2021
2789
  var OPTIONS2 = {
2022
2790
  all: { type: "boolean", short: "a", description: "list the repositories with nothing to report too" },
2023
- only: { type: "string", choices: REASONS, description: "only the repositories with this reason: dirty, unpushed, unreleased or behind" },
2791
+ only: { type: "string", multiple: true, choices: REASONS, description: "only the repositories with this reason: dirty, unpushed, unreleased or behind, repeatable" },
2024
2792
  watch: watchOption("the repositories"),
2025
2793
  fetch: { type: "boolean", conflicts: ["watch"], description: "refresh the upstreams first (reaches the remote)" },
2026
2794
  pull: { type: "boolean", conflicts: ["watch"], description: "fetch, then fast-forward the clean repositories listed that are only behind their upstream (reaches the remote)" },
@@ -2043,7 +2811,7 @@ function releasedCell(repo) {
2043
2811
  return repo.packages.filter((release) => release.unreleased > 0).map((release) => `${release.name} ${release.unreleased}`).join(", ") || "-";
2044
2812
  return repo.tag === null || repo.unreleased === 0 ? "-" : `${repo.unreleased} since ${repo.tag}`;
2045
2813
  }
2046
- function syncCell(repo, stream = process21.stdout) {
2814
+ function syncCell(repo, stream = process23.stdout) {
2047
2815
  const colors = paint(stream);
2048
2816
  const ahead = repo.ahead ?? 0;
2049
2817
  const behind = repo.behind ?? 0;
@@ -2054,7 +2822,7 @@ function syncCell(repo, stream = process21.stdout) {
2054
2822
  return parts.length === 0 ? colors.dim("-") : `${parts.join(" ")}${diverged ? colors.yellow(" diverged") : ""}`;
2055
2823
  }
2056
2824
  var DEFAULT_BRANCHES = new Set(["main", "master"]);
2057
- function branchCell(repo, stream = process21.stdout) {
2825
+ function branchCell(repo, stream = process23.stdout) {
2058
2826
  const colors = paint(stream);
2059
2827
  if (repo.unreadable)
2060
2828
  return colors.red("? (unreadable)");
@@ -2063,8 +2831,8 @@ function branchCell(repo, stream = process21.stdout) {
2063
2831
  return DEFAULT_BRANCHES.has(repo.branch) ? repo.branch : role("accent", stream)(repo.branch);
2064
2832
  }
2065
2833
  function row(repo, shown) {
2066
- const colors = paint(process21.stdout);
2067
- const tint = role("path", process21.stdout);
2834
+ const colors = paint(process23.stdout);
2835
+ const tint = role("path", process23.stdout);
2068
2836
  const unreleased = releasedCell(repo);
2069
2837
  return [
2070
2838
  tint(shown),
@@ -2075,19 +2843,31 @@ function row(repo, shown) {
2075
2843
  unreleased === "-" ? colors.dim("-") : colors.cyan(unreleased)
2076
2844
  ];
2077
2845
  }
2078
- async function repos(args) {
2079
- const { values, positionals } = parse(args, USAGE2, OPTIONS2, { positionals: ["[root]"], exits: EXITS2, replaces: "a cd, git status, git log and git tag loop over each repository of the workspace", examples: ["repos", "repos ~/Workspace --only unreleased --fetch", ["repos --only behind --pull", "fast-forward what is behind and clean"], ["repos --only dirty --path", "the paths, for xargs"]] });
2846
+ async function repos(args, watched = false) {
2847
+ const { values, positionals } = parse(args, USAGE2, OPTIONS2, { positionals: ["[root]"], exits: EXITS2, replaces: "a cd, git status, git log and git tag loop over each repository of the workspace", examples: ["ws repos", "ws repos ~/Workspace --only unreleased --fetch", ["ws repos --only behind --pull", "fast-forward what is behind and clean"], ["ws repos --only dirty --path", "the paths, for xargs"]] });
2080
2848
  if (values.watch !== undefined)
2081
- return watching(values.watch, async () => repos(withoutWatch(args)));
2849
+ return watching(values.watch, async () => repos(withoutWatch(args), true));
2082
2850
  const root = workspaceRoot({ given: positionals[0] });
2083
2851
  if (!existsSync8(root) || !statSync3(root).isDirectory())
2084
2852
  fail(`no folder ${root}`);
2085
- const only = values.only === undefined ? undefined : oneOf(values.only, "only", REASONS);
2086
- const paths = await findRepos2(root, await skipped());
2087
- const states = await pool(paths, configuredNumber("repos", "concurrency", CONCURRENCY2), async (path) => inspect(path, values.fetch === true || values.pull === true));
2853
+ const only = values.only ?? [];
2854
+ const progress = watched ? undefined : progressLine();
2855
+ const fetching = values.fetch === true || values.pull === true;
2856
+ const step = fetching ? "fetching" : "reading";
2857
+ let states;
2858
+ try {
2859
+ progress?.update({ step: "finding the repositories" });
2860
+ const paths = await findRepos2(root, await skipped());
2861
+ progress?.update({ step, done: 0, total: paths.length, unit: "repositories" });
2862
+ states = await pool(paths, configuredNumber("repos", "concurrency", CONCURRENCY2), async (path) => inspect(path, fetching), (done, total) => progress?.update({ step, done, total, unit: "repositories" }));
2863
+ } finally {
2864
+ progress?.stop();
2865
+ }
2088
2866
  const keeps = (repo) => {
2089
2867
  const reasons = reasonsOf(repo);
2090
- return only === undefined ? values.all === true || reasons.length > 0 || repo.unreadable : reasons.includes(only);
2868
+ if (only.length > 0)
2869
+ return reasons.some((reason) => only.includes(reason));
2870
+ return values.all === true || reasons.some((reason) => reason !== "unreleased") || repo.unreadable;
2091
2871
  };
2092
2872
  let failedPulls = 0;
2093
2873
  if (values.pull === true) {
@@ -2098,12 +2878,12 @@ async function repos(args) {
2098
2878
  const blocker = pullBlocker(repo);
2099
2879
  const refused = blocker === undefined ? await fastForward(repo.path) : undefined;
2100
2880
  if (blocker !== undefined) {
2101
- log(marked("note", `${repo.name} skipped`, process21.stdout, blocker));
2881
+ log(marked("note", `${repo.name} skipped`, process23.stdout, blocker));
2102
2882
  } else if (refused !== undefined) {
2103
2883
  failedPulls++;
2104
- log(marked("problem", `${repo.name} not pulled`, process21.stdout, refused));
2884
+ log(marked("problem", `${repo.name} not pulled`, process23.stdout, refused));
2105
2885
  } else {
2106
- log(marked("ok", `${repo.name} pulled`, process21.stdout, `${repo.behind} ${repo.behind === 1 ? "commit" : "commits"}`));
2886
+ log(marked("ok", `${repo.name} pulled`, process23.stdout, `${repo.behind} ${repo.behind === 1 ? "commit" : "commits"}`));
2107
2887
  states[index] = await inspect(repo.path, false);
2108
2888
  }
2109
2889
  }
@@ -2118,7 +2898,7 @@ async function repos(args) {
2118
2898
  printJson(kept.map((repo) => ({ ...repo, reasons: reasonsOf(repo) })));
2119
2899
  return failedPulls > 0 ? 1 : 0;
2120
2900
  }
2121
- const label = role("label", process21.stdout);
2901
+ const label = role("label", process23.stdout);
2122
2902
  printHeader("repos", `${basename2(root)} \xB7 ${states.length} ${states.length === 1 ? "repository" : "repositories"}`);
2123
2903
  if (kept.length === 0) {
2124
2904
  console.log(label(`nothing needs attention in ${states.length} repositories`));
@@ -2137,212 +2917,7 @@ async function repos(args) {
2137
2917
  import { existsSync as existsSync11, statSync as statSync4 } from "fs";
2138
2918
  import { homedir as homedir6 } from "os";
2139
2919
  import { relative as relative3 } from "path";
2140
-
2141
- // ../kit/src/prompt.ts
2142
- import process23 from "process";
2143
-
2144
- // ../kit/src/job.ts
2145
- import process22 from "process";
2146
- function stopJob() {
2147
- process22.kill(0, "SIGTSTP");
2148
- }
2149
-
2150
- // ../kit/src/picker/line.ts
2151
- var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
2152
- var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
2153
- var FORWARD_KILLS = new Set(["killnext", "killend"]);
2154
- function isEditKey(key) {
2155
- return EDIT_KEYS.has(key);
2156
- }
2157
-
2158
- // ../kit/src/picker/score.ts
2159
- var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
2160
- var NONE = Number.NEGATIVE_INFINITY;
2161
-
2162
- // ../kit/src/picker/state.ts
2163
- var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
2164
- var PASTE_START = "\x1B[200~";
2165
- var PASTE_END = "\x1B[201~";
2166
- var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
2167
- var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
2168
- var WHEEL_LINES = 3;
2169
- var KEYS = {
2170
- "\x1B[A": "up",
2171
- "\x1BOA": "up",
2172
- "\x10": "up",
2173
- "\x1B[B": "down",
2174
- "\x1BOB": "down",
2175
- "\x0E": "down",
2176
- "\x1B[5~": "pageup",
2177
- "\x1B[6~": "pagedown",
2178
- "\x1B[H": "home",
2179
- "\x1B[1~": "home",
2180
- "\x1BOH": "home",
2181
- "\x1B[F": "end",
2182
- "\x1B[4~": "end",
2183
- "\x1BOF": "end",
2184
- "\r": "enter",
2185
- "\n": "enter",
2186
- "\x03": "cancel",
2187
- "\x1B": "cancel",
2188
- "\x1B[D": "left",
2189
- "\x1BOD": "left",
2190
- "\x1B[C": "right",
2191
- "\x1BOC": "right",
2192
- "\x1B[1;5D": "wordleft",
2193
- "\x1B[1;3D": "wordleft",
2194
- "\x1Bb": "wordleft",
2195
- "\x1B[1;5C": "wordright",
2196
- "\x1B[1;3C": "wordright",
2197
- "\x1Bf": "wordright",
2198
- "\x01": "linestart",
2199
- "\x05": "lineend",
2200
- "\x7F": "erase",
2201
- "\x1B[3~": "delete",
2202
- "\b": "killword",
2203
- "\x1B\x7F": "killword",
2204
- "\x1B[3;5~": "killnext",
2205
- "\x1Bd": "killnext",
2206
- "\x15": "clear",
2207
- "\v": "killend",
2208
- "\x17": "word",
2209
- "\x19": "yank",
2210
- "\x1A": "suspend",
2211
- "\t": "tab",
2212
- "\x1F": "help",
2213
- "\x1BOP": "help",
2214
- "\x1B[11~": "help"
2215
- };
2216
- function repeat(value, count) {
2217
- return Array.from({ length: count }).fill(value);
2218
- }
2219
- function parseKeys(input, paste = { active: false }, ctrls = []) {
2220
- const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
2221
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
2222
- const wheel = MOUSE.exec(sequence)?.[1];
2223
- if (wheel !== undefined)
2224
- return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
2225
- const named = codes.get(sequence);
2226
- const key = named === undefined ? KEYS[sequence] : { ctrl: named };
2227
- if (sequence === PASTE_START || sequence === PASTE_END) {
2228
- paste.active = sequence === PASTE_START;
2229
- return [];
2230
- }
2231
- if (paste.active && (sequence === "\r" || sequence === `
2232
- `))
2233
- return [];
2234
- if (key !== undefined)
2235
- return [key];
2236
- return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
2237
- });
2238
- }
2239
-
2240
- // ../kit/src/redraw.ts
2241
- var SYNC_START = "\x1B[?2026h";
2242
- var SYNC_END = "\x1B[?2026l";
2243
- function overwrite(lines, columns) {
2244
- return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
2245
- `);
2246
- }
2247
- function rowsTaken(lines, columns) {
2248
- return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
2249
- }
2250
-
2251
- // ../kit/src/prompt.ts
2252
- var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
2253
- function readKeys(input, paste = { active: false }) {
2254
- return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
2255
- }
2256
- async function confirm(question, { default: fallback, ...settings } = {}) {
2257
- let answered = fallback;
2258
- const choices = { true: "Y/n", false: "y/N", undefined: "y/n" }[String(fallback)];
2259
- const accepted = await ask(question, settings, (colors, state) => [state === "asking" ? asking(colors, question, "", choices) : answer(colors, question, state, answered ? "yes" : "no")], (key) => {
2260
- if (key === "cancel")
2261
- return "cancel";
2262
- if (key === "enter")
2263
- return answered === undefined ? undefined : "enter";
2264
- const letter = typeof key === "object" ? key.text.toLowerCase() : "";
2265
- if (letter !== "y" && letter !== "n")
2266
- return;
2267
- answered = letter === "y";
2268
- return "enter";
2269
- });
2270
- return accepted ? answered : undefined;
2271
- }
2272
- function asking(colors, question, typed, keys) {
2273
- return `${colors.cyan("?")} ${question} ${typed === "" ? colors.dim(`(${keys})`) : typed}`;
2274
- }
2275
- function answer(colors, question, state, picked) {
2276
- return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
2277
- }
2278
- async function ask(question, { hint, terminal = process23 }, render, press) {
2279
- const { stdin, stderr } = terminal;
2280
- if (!isInteractive(terminal))
2281
- fail(`cannot ask "${question}" off a terminal`, 2, hint);
2282
- const colors = paint(stderr);
2283
- let current = "asking";
2284
- let outcome;
2285
- const columns = () => stderr.columns || 80;
2286
- const draw = (state, last = false) => {
2287
- const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
2288
- const rows = rowsTaken(frame, columns());
2289
- stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
2290
- current = state;
2291
- };
2292
- const redraw = () => draw(current);
2293
- const paste = { active: false };
2294
- const stop = terminal.stop ?? (terminal === process23 ? stopJob : undefined);
2295
- const suspend = () => {
2296
- if (stop === undefined)
2297
- return;
2298
- stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
2299
- stdin.setRawMode(false);
2300
- stop();
2301
- stdin.setRawMode(true);
2302
- stderr.write("\x1B[?25l\x1B[?2004h");
2303
- };
2304
- try {
2305
- stderr.on?.("resize", redraw);
2306
- stdin.setRawMode(true);
2307
- stdin.resume();
2308
- stderr.write("\x1B[?25l\x1B[?2004h");
2309
- draw("asking");
2310
- return await new Promise((resolve) => {
2311
- function onData(data) {
2312
- for (const key of readKeys(data.toString(), paste)) {
2313
- if (key === "suspend") {
2314
- suspend();
2315
- continue;
2316
- }
2317
- const pressed = press(key);
2318
- if (pressed !== undefined) {
2319
- settle(pressed);
2320
- return;
2321
- }
2322
- }
2323
- draw("asking");
2324
- }
2325
- function onEnd() {
2326
- settle("cancel");
2327
- }
2328
- function settle(settled) {
2329
- outcome = settled;
2330
- stdin.off("data", onData);
2331
- stdin.off("end", onEnd);
2332
- resolve(settled === "enter");
2333
- }
2334
- stdin.on("data", onData);
2335
- stdin.on("end", onEnd);
2336
- });
2337
- } finally {
2338
- stderr.off?.("resize", redraw);
2339
- draw(outcome ?? "cancel", true);
2340
- stderr.write(`
2341
- \x1B[?25h\x1B[?2004l`);
2342
- stdin.setRawMode(false);
2343
- stdin.pause();
2344
- }
2345
- }
2920
+ init_prompt();
2346
2921
 
2347
2922
  // src/apply.ts
2348
2923
  import { existsSync as existsSync10 } from "fs";
@@ -2360,7 +2935,8 @@ import { lstat, readdir as readdir3 } from "fs/promises";
2360
2935
  import { join as join11 } from "path";
2361
2936
  var FS_LIMIT = 32;
2362
2937
  var FIND_MS = 60000;
2363
- var FIND_LINE = /^(\d+) (\S+) (\d+)$/gm;
2938
+ var FIND_LINE = /^(\w) (\d+) (\S+) (\d+) (\d+)$/gm;
2939
+ var OWN_UID = process.getuid?.() ?? -1;
2364
2940
  var waiting = [];
2365
2941
  var running = 0;
2366
2942
  async function gated(call) {
@@ -2374,9 +2950,10 @@ async function gated(call) {
2374
2950
  waiting.shift()?.();
2375
2951
  }
2376
2952
  }
2377
- async function walkSize(folder) {
2953
+ async function walk(folder, uid) {
2378
2954
  const seen = new Set;
2379
2955
  let total = 0;
2956
+ let foreign = 0;
2380
2957
  const visit = async (dir) => {
2381
2958
  let entries;
2382
2959
  try {
@@ -2386,10 +2963,12 @@ async function walkSize(folder) {
2386
2963
  }
2387
2964
  await Promise.all(entries.map(async (entry) => {
2388
2965
  const path = join11(dir, entry.name);
2389
- if (entry.isDirectory())
2390
- return visit(path);
2391
2966
  try {
2392
2967
  const stat = await gated(async () => lstat(path));
2968
+ if (stat.uid !== uid)
2969
+ foreign++;
2970
+ if (entry.isDirectory())
2971
+ return await visit(path);
2393
2972
  if (stat.nlink > 1) {
2394
2973
  const key = `${stat.dev}:${stat.ino}`;
2395
2974
  if (seen.has(key))
@@ -2400,18 +2979,27 @@ async function walkSize(folder) {
2400
2979
  } catch {}
2401
2980
  }));
2402
2981
  };
2982
+ try {
2983
+ if ((await lstat(folder)).uid !== uid)
2984
+ foreign++;
2985
+ } catch {}
2403
2986
  await visit(folder);
2404
- return total;
2987
+ return { bytes: total, foreign };
2405
2988
  }
2406
- async function findSize(folder) {
2989
+ async function findSize(folder, uid) {
2407
2990
  try {
2408
- const ran = await runCommand(["find", "-P", folder, "(", "-type", "f", "-o", "-type", "l", ")", "-printf", "%n %D:%i %s\\n"], { timeoutMs: FIND_MS });
2991
+ const ran = await runCommand(["find", "-P", folder, "-printf", "%y %n %D:%i %s %U\\n"], { timeoutMs: FIND_MS });
2409
2992
  const lines = [...ran.text.matchAll(FIND_LINE)];
2410
2993
  if (ran.timedOut || ran.code !== 0 && lines.length === 0)
2411
2994
  return;
2412
2995
  const seen = new Set;
2413
2996
  let total = 0;
2414
- for (const [, links, id, bytes] of lines) {
2997
+ let foreign = 0;
2998
+ for (const [, type, links, id, bytes, owner] of lines) {
2999
+ if (Number(owner) !== uid)
3000
+ foreign++;
3001
+ if (type !== "f" && type !== "l")
3002
+ continue;
2415
3003
  if (Number(links) > 1) {
2416
3004
  if (seen.has(id))
2417
3005
  continue;
@@ -2419,13 +3007,13 @@ async function findSize(folder) {
2419
3007
  }
2420
3008
  total += Number(bytes);
2421
3009
  }
2422
- return total;
3010
+ return { bytes: total, foreign };
2423
3011
  } catch {
2424
3012
  return;
2425
3013
  }
2426
3014
  }
2427
- async function sizeOf(folder) {
2428
- return await findSize(folder) ?? await walkSize(folder);
3015
+ async function measure(folder, uid = OWN_UID) {
3016
+ return await findSize(folder, uid) ?? await walk(folder, uid);
2429
3017
  }
2430
3018
 
2431
3019
  // src/sweep-scan.ts
@@ -2566,13 +3154,13 @@ async function judgeFolder(path, kind, inside) {
2566
3154
  if (existsSync9(join12(path, ".git")))
2567
3155
  return { skip: "holds a git repository" };
2568
3156
  if (located === "none")
2569
- return name === "node_modules" || inside !== undefined ? { entry: { path, kind, committedAt: undefined, action: "remove", inside } } : { skip: "not in a git repository" };
3157
+ return name === "node_modules" || inside !== undefined ? { entry: { path, kind, committedAt: undefined, action: "remove", inside, project: dirname5(inside ?? path) } } : { skip: "not in a git repository" };
2570
3158
  const tracked = await gitIn(parent, ["ls-files", "--", name]);
2571
3159
  if (tracked.code !== 0 || tracked.stdout !== "")
2572
3160
  return { skip: "tracked by git" };
2573
3161
  if (name !== "node_modules" && inside === undefined && (await gitIn(parent, ["check-ignore", "-q", "--", name])).code !== 0)
2574
3162
  return { skip: "not ignored by git" };
2575
- return { entry: { path, kind, committedAt: await lastCommitOf(located.top), action: "remove", inside } };
3163
+ return { entry: { path, kind, committedAt: await lastCommitOf(located.top), action: "remove", inside, project: located.top } };
2576
3164
  }
2577
3165
  async function judgeWorktree(path) {
2578
3166
  const located = await toplevelOf(dirname5(path));
@@ -2604,23 +3192,26 @@ async function judgeWorktree(path) {
2604
3192
  if (unique.stdout !== "")
2605
3193
  return keep(`${unique.stdout.split(`
2606
3194
  `).length} commits on no other branch or remote`);
2607
- return { entry: { path, kind: "worktree", committedAt, action: "remove", repo: top } };
3195
+ return { entry: { path, kind: "worktree", committedAt, action: "remove", repo: top, project: path } };
2608
3196
  }
2609
3197
  async function judge(candidate) {
2610
3198
  if (candidate.global === true)
2611
3199
  return { entry: { path: candidate.path, kind: candidate.kind, committedAt: undefined, action: "remove" } };
2612
3200
  return candidate.kind === "worktree" ? judgeWorktree(candidate.path) : judgeFolder(candidate.path, candidate.kind, candidate.inside);
2613
3201
  }
2614
- async function inspect2({ candidates, skipped }) {
3202
+ async function inspect2({ candidates, skipped }, onDone, uid) {
2615
3203
  const entries = [];
2616
3204
  const rejected = [...skipped];
2617
3205
  await pool(candidates, 8, async (candidate) => {
2618
3206
  const verdict = await judge(candidate);
2619
- if ("skip" in verdict)
3207
+ if ("skip" in verdict) {
2620
3208
  rejected.push({ path: candidate.path, reason: verdict.skip });
2621
- else
2622
- entries.push({ ...verdict.entry, bytes: await sizeOf(candidate.path) });
2623
- });
3209
+ return;
3210
+ }
3211
+ const { bytes, foreign } = await measure(candidate.path, uid);
3212
+ const owned = foreign > 0 && verdict.entry.action === "remove" ? { action: "keep", reason: `${foreign} ${foreign === 1 ? "entry" : "entries"} owned by another user (a container's?)` } : {};
3213
+ entries.push({ ...verdict.entry, ...owned, bytes });
3214
+ }, onDone);
2624
3215
  const listed = new Set(entries.filter((entry) => entry.action === "remove").map((entry) => entry.path));
2625
3216
  return { entries: entries.filter((entry) => entry.inside === undefined || !listed.has(entry.inside)), skipped: rejected };
2626
3217
  }
@@ -2661,12 +3252,79 @@ async function applyAll(entries, done) {
2661
3252
  return outcomes;
2662
3253
  }
2663
3254
 
3255
+ // src/busy.ts
3256
+ import { readdir as readdir5, readFile, readlink } from "fs/promises";
3257
+ import { basename as basename5, join as join14 } from "path";
3258
+ var DEV_PROGRAMS = new Set(["node", "bun", "deno", "npm", "npx", "pnpm", "yarn", "bunx", "vite", "esbuild", "ruby", "java", "cargo", "go", "php", "php-fpm"]);
3259
+ var DEV_PREFIXES = ["python", "php"];
3260
+ var DOCKER_MS = 5000;
3261
+ var PID = /^\d+$/;
3262
+ var PARENT = /^ \S+ (\d+)/;
3263
+ function isDevProgram(comm) {
3264
+ return DEV_PROGRAMS.has(comm) || DEV_PREFIXES.some((prefix) => comm.startsWith(prefix));
3265
+ }
3266
+ async function quietly(read) {
3267
+ try {
3268
+ return await read();
3269
+ } catch {
3270
+ return;
3271
+ }
3272
+ }
3273
+ async function lineage(pid, root) {
3274
+ const seen = new Set;
3275
+ for (let current = pid;current > 1 && !seen.has(current); ) {
3276
+ seen.add(current);
3277
+ const stat = await quietly(async () => readFile(join14(root, String(current), "stat"), "utf8"));
3278
+ const parent = Number(PARENT.exec(stat?.slice(stat.lastIndexOf(")") + 1) ?? "")?.[1]);
3279
+ if (!Number.isInteger(parent))
3280
+ break;
3281
+ current = parent;
3282
+ }
3283
+ return seen;
3284
+ }
3285
+ async function processPlaces(root = "/proc", self = process.pid) {
3286
+ const own = await lineage(self, root);
3287
+ const pids = (await quietly(async () => readdir5(root)) ?? []).filter((name) => PID.test(name)).map(Number).filter((pid) => !own.has(pid));
3288
+ const places = [];
3289
+ await Promise.all(pids.map(async (pid) => {
3290
+ const comm = (await quietly(async () => readFile(join14(root, String(pid), "comm"), "utf8")))?.trim();
3291
+ if (comm === undefined || !isDevProgram(comm))
3292
+ return;
3293
+ const cwd = await quietly(async () => readlink(join14(root, String(pid), "cwd")));
3294
+ const argv = (await quietly(async () => readFile(join14(root, String(pid), "cmdline"), "utf8")))?.split("\x00").filter((arg) => arg.startsWith("/")) ?? [];
3295
+ const who = `pid ${pid} ${comm}`;
3296
+ for (const path of [cwd, ...argv.slice(1)]) {
3297
+ if (path !== undefined)
3298
+ places.push({ path, who });
3299
+ }
3300
+ }));
3301
+ return places;
3302
+ }
3303
+ async function containerPlaces() {
3304
+ const ids = await quietly(async () => runCommand(["docker", "ps", "-q"], { timeoutMs: DOCKER_MS }));
3305
+ if (ids === undefined || ids.code !== 0 || ids.text.trim() === "")
3306
+ return [];
3307
+ const inspected = await quietly(async () => runCommand(["docker", "inspect", "--format", '{{.Name}}{{range .Mounts}}{{if eq .Type "bind"}}\t{{.Source}}{{end}}{{end}}', ...ids.text.trim().split(`
3308
+ `)], { timeoutMs: DOCKER_MS }));
3309
+ if (inspected === undefined || inspected.code !== 0)
3310
+ return [];
3311
+ return inspected.text.trim().split(`
3312
+ `).flatMap((line) => {
3313
+ const [name = "", ...sources] = line.split("\t");
3314
+ return sources.map((path) => ({ path, who: `container ${basename5(name)}` }));
3315
+ });
3316
+ }
3317
+ var within = (path, folder) => path === folder || path.startsWith(`${folder}/`);
3318
+ function userOf(folder, processes, containers) {
3319
+ return processes.find((place) => within(place.path, folder))?.who ?? containers.find((place) => within(place.path, folder) || within(folder, place.path))?.who;
3320
+ }
3321
+
2664
3322
  // src/sweep.ts
2665
3323
  var LARGE = 100 * 1024 ** 2;
2666
3324
  var BIG = 1024 ** 3;
2667
- var USAGE3 = `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_DEPTH3} levels down), largest first with the age of the repo's last commit; --only worktrees, folders or caches keeps one kind
3325
+ var USAGE3 = `ws 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_DEPTH3} levels down), largest first with the age of the repo's last commit; --only worktrees, folders or caches keeps one kind
2668
3326
 
2669
- 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.`;
3327
+ 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. Kept too, and named: what a running dev process (node, bun, python...) or a container's bind mount uses, which would be rebuilt at once or break the server, and a folder holding files another user owns, as a container running as root writes. With --docker the Docker usage comes after the list, left to dclean.`;
2670
3328
  var EXITS3 = [[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"]];
2671
3329
  var ONLY_KINDS = { worktrees: "worktree", folders: "folder", caches: "cache" };
2672
3330
  var OPTIONS3 = {
@@ -2674,7 +3332,7 @@ var OPTIONS3 = {
2674
3332
  yes: { type: "boolean", short: "y", description: "with --apply, skip the confirm" },
2675
3333
  older: { type: "string", description: "only the entries whose repo last committed longer ago than this (30d, 12h)" },
2676
3334
  min: { type: "string", description: "only the entries of at least this size (500K, 10M, 1G)" },
2677
- 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)" },
3335
+ only: { type: "string", choices: Object.keys(ONLY_KINDS), description: "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)" },
2678
3336
  docker: { type: "boolean", description: "add the docker system df output, which alone takes about ten seconds" },
2679
3337
  json: jsonOption("{root, entries: [{path, kind (folder, worktree or cache), bytes, committedAt, action (remove or keep), reason}], skipped: [{path, reason}], reclaimable, docker, removed?}")
2680
3338
  };
@@ -2689,22 +3347,31 @@ async function dockerUsage() {
2689
3347
  }
2690
3348
  }
2691
3349
  async function sweep(args) {
2692
- const { values, positionals } = parse(args, USAGE3, OPTIONS3, { exits: EXITS3, 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"] });
3350
+ const { values, positionals } = parse(args, USAGE3, OPTIONS3, { exits: EXITS3, positionals: ["[root]"], replaces: "find ~/Workspace -name node_modules, du -sh and rm -rf by hand", examples: ["ws sweep", "ws sweep ~/Workspace --older 30d --min 100M --apply", "ws sweep --only worktrees --apply"] });
2693
3351
  if (positionals.length > 1)
2694
3352
  badUsage("give one root");
2695
3353
  const root = workspaceRoot({ given: positionals[0] });
2696
3354
  if (!existsSync11(root) || !statSync4(root).isDirectory())
2697
3355
  fail(`${root} is not a folder`);
2698
- if (values.only !== undefined && !Object.hasOwn(ONLY_KINDS, values.only))
2699
- badUsage(`--only takes worktrees, folders or caches, not ${values.only}`);
2700
3356
  const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0);
2701
3357
  const minBytes = values.min === undefined ? 0 : parseSize(values.min);
2702
3358
  if (minBytes === undefined)
2703
3359
  badUsage(`--min takes a size such as 500K, 10M or 1G, not ${values.min}`);
2704
3360
  const now = Date.now();
2705
- const found = await findCandidates(root, homedir6(), positionals.length === 0 || values.only === "caches");
2706
- const wanted = values.only === undefined ? found.candidates : found.candidates.filter((candidate) => candidate.kind === ONLY_KINDS[values.only]);
2707
- const { entries: all, skipped } = await inspect2({ candidates: wanted, skipped: found.skipped });
3361
+ const progress = progressLine();
3362
+ let scanned;
3363
+ try {
3364
+ progress.update({ step: "finding the folders" });
3365
+ const found = await findCandidates(root, homedir6(), positionals.length === 0 || values.only === "caches");
3366
+ const wanted = values.only === undefined ? found.candidates : found.candidates.filter((candidate) => candidate.kind === ONLY_KINDS[values.only]);
3367
+ progress.update({ step: "sizing", done: 0, total: wanted.length, unit: "folders" });
3368
+ scanned = await inspect2({ candidates: wanted, skipped: found.skipped }, (done, total) => progress.update({ step: "sizing", done, total, unit: "folders" }));
3369
+ progress.update({ step: "looking for running servers and containers" });
3370
+ await keepWhatIsInUse(scanned.entries);
3371
+ } finally {
3372
+ progress.stop();
3373
+ }
3374
+ const { entries: all, skipped } = scanned;
2708
3375
  const entries = all.filter((entry) => entry.bytes >= minBytes && (olderMs === undefined || entry.committedAt !== undefined && now - entry.committedAt >= olderMs)).sort((a, b) => b.bytes - a.bytes || a.path.localeCompare(b.path));
2709
3376
  const removable = entries.filter((entry) => entry.action === "remove");
2710
3377
  const reclaimable = removable.reduce((sum, entry) => sum + entry.bytes, 0);
@@ -2749,6 +3416,19 @@ function report2(root, outcome, json) {
2749
3416
  else
2750
3417
  problem(`kept ${relative3(root, outcome.path)}`, outcome.error);
2751
3418
  }
3419
+ async function keepWhatIsInUse(entries) {
3420
+ const candidates = entries.filter((entry) => entry.action === "remove" && entry.project !== undefined);
3421
+ if (candidates.length === 0)
3422
+ return;
3423
+ const [processes, containers] = await Promise.all([processPlaces(), containerPlaces()]);
3424
+ for (const entry of candidates) {
3425
+ const who = userOf(entry.project, processes, containers);
3426
+ if (who !== undefined) {
3427
+ entry.action = "keep";
3428
+ entry.reason = `in use by ${who}`;
3429
+ }
3430
+ }
3431
+ }
2752
3432
  function print(root, entries, skipped, reclaimable, now) {
2753
3433
  if (entries.length === 0) {
2754
3434
  console.log("nothing to sweep");
@@ -2767,7 +3447,7 @@ ${tt(reclaimable)} reclaimable${skipped === 0 ? "" : `, ${skipped} skipped (syml
2767
3447
  }
2768
3448
 
2769
3449
  // src/cli.ts
2770
- process24.exitCode = await runCli({
3450
+ process26.exitCode = await runCli({
2771
3451
  name: "ws",
2772
3452
  about: "the repositories under a root: the ones needing attention, the folders worth reclaiming and their known vulnerabilities",
2773
3453
  replaces: "a cd, git status and du loop over each repository of the workspace, and a bun audit run in each",