@kaynooo/cli-workspace 0.11.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,14 +582,41 @@ 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
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
599
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
600
+ `);
601
+ const blank = lines.indexOf("");
602
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
603
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
604
+ const colon = synopses[0].indexOf(": ");
605
+ const inline = synopses[0].slice(colon + 2);
606
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
607
+ if (colon !== -1)
608
+ synopses[0] = synopses[0].slice(0, colon);
609
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
610
+ `)}`;
611
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
612
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
613
+ return [head, ...lead, ...rest].join(`
614
+ `);
615
+ }
616
+ function prose(line, colors) {
617
+ if (colors.cyan("x") === "x")
618
+ return line;
619
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
525
620
  }
526
621
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
527
622
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -556,7 +651,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
556
651
  return [];
557
652
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
558
653
  }
559
- var MAX_INLINE_CHOICES = 24;
560
654
  function optionRows(options, colors = paint(process8.stdout)) {
561
655
  const rows = Object.entries(options).map(([name, option]) => {
562
656
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -571,6 +665,15 @@ function optionRows(options, colors = paint(process8.stdout)) {
571
665
  const width = Math.max(0, ...rows.map((row) => row.width));
572
666
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
573
667
  }
668
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
669
+ var init_help = __esm(() => {
670
+ init_mode();
671
+ init_style();
672
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
673
+ USAGE_PREFIX = /^usage:\s*/i;
674
+ FULL_STOP = /\.$/;
675
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
676
+ });
574
677
 
575
678
  // ../kit/src/text.ts
576
679
  function distance(a, b) {
@@ -598,9 +701,9 @@ function closest(name, names) {
598
701
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
599
702
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
600
703
  }
704
+ var init_text2 = () => {};
705
+
601
706
  // ../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
707
  function duration(value, name, fallback, unit = "s") {
605
708
  if (value === undefined)
606
709
  return fallback;
@@ -610,40 +713,26 @@ function duration(value, name, fallback, unit = "s") {
610
713
  badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
611
714
  return ms;
612
715
  }
716
+ var DURATION, UNIT_MS;
717
+ var init_input = __esm(() => {
718
+ init_args();
719
+ DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
720
+ UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
721
+ });
613
722
 
614
723
  // ../kit/src/args.ts
615
- var DASHES = /^-+/;
724
+ import process9 from "process";
725
+ import { parseArgs } from "util";
616
726
  function jsonOption(holds) {
617
727
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
618
728
  }
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
729
  function fail(message, code = 2, hint) {
629
730
  throw new Exit(message, code, hint);
630
731
  }
631
-
632
- class UsageError extends Exit {
633
- constructor(message, hint) {
634
- super(message, 2, hint);
635
- }
636
- }
637
732
  function badUsage(message) {
638
733
  throw new UsageError(message);
639
734
  }
640
735
 
641
- class HelpShown extends Exit {
642
- constructor() {
643
- super("help shown", 0);
644
- }
645
- }
646
-
647
736
  class Completing {
648
737
  options;
649
738
  positionals;
@@ -654,11 +743,6 @@ class Completing {
654
743
  this.candidates = candidates;
655
744
  }
656
745
  }
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
746
  function applyOutput(color, plain, env = process9.env) {
663
747
  const when = plain === true ? "never" : color ?? "auto";
664
748
  if (when === "auto")
@@ -812,7 +896,6 @@ function parseError(error) {
812
896
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
813
897
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
814
898
  }
815
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
816
899
  function nearestOption(message, options, allowNegative) {
817
900
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
818
901
  if (typed === undefined)
@@ -828,6 +911,303 @@ function nearestOption(message, options, allowNegative) {
828
911
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
829
912
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
830
913
  }
914
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
915
+ var init_args = __esm(() => {
916
+ init_format2();
917
+ init_help();
918
+ init_text2();
919
+ init_help();
920
+ init_input();
921
+ DASHES = /^-+/;
922
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
923
+ Exit = class Exit extends Error {
924
+ code;
925
+ hint;
926
+ [EXIT] = true;
927
+ constructor(message, code, hint) {
928
+ super(message);
929
+ this.code = code;
930
+ this.hint = hint;
931
+ }
932
+ static [Symbol.hasInstance](value) {
933
+ if (this !== Exit)
934
+ return Function.prototype[Symbol.hasInstance].call(this, value);
935
+ return typeof value === "object" && value !== null && value[EXIT] === true;
936
+ }
937
+ };
938
+ UsageError = class UsageError extends Exit {
939
+ constructor(message, hint) {
940
+ super(message, 2, hint);
941
+ }
942
+ };
943
+ HelpShown = class HelpShown extends Exit {
944
+ constructor() {
945
+ super("help shown", 0);
946
+ }
947
+ };
948
+ completion = { active: false };
949
+ OUTPUT_OPTIONS = {
950
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
951
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
952
+ };
953
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
954
+ });
955
+
956
+ // ../kit/src/folders.ts
957
+ var SKIPPED_FOLDERS;
958
+ var init_folders = __esm(() => {
959
+ init_user_config();
960
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
961
+ });
962
+
963
+ // ../kit/src/answers.ts
964
+ var init_answers = __esm(() => {
965
+ init_folders();
966
+ });
967
+
968
+ // ../kit/src/job.ts
969
+ import process24 from "process";
970
+ function stopJob() {
971
+ process24.kill(0, "SIGTSTP");
972
+ }
973
+ var init_job = () => {};
974
+
975
+ // ../kit/src/picker/line.ts
976
+ function isEditKey(key) {
977
+ return EDIT_KEYS.has(key);
978
+ }
979
+ var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS;
980
+ var init_line = __esm(() => {
981
+ EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
982
+ BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
983
+ FORWARD_KILLS = new Set(["killnext", "killend"]);
984
+ });
985
+
986
+ // ../kit/src/picker/score.ts
987
+ var BOUNDARY_AFTER, NONE;
988
+ var init_score = __esm(() => {
989
+ BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
990
+ NONE = Number.NEGATIVE_INFINITY;
991
+ });
992
+
993
+ // ../kit/src/picker/state.ts
994
+ function repeat(value, count) {
995
+ return Array.from({ length: count }).fill(value);
996
+ }
997
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
998
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
999
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1000
+ const wheel = MOUSE.exec(sequence)?.[1];
1001
+ if (wheel !== undefined)
1002
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1003
+ const named = codes.get(sequence);
1004
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1005
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1006
+ paste.active = sequence === PASTE_START;
1007
+ return [];
1008
+ }
1009
+ if (paste.active && (sequence === "\r" || sequence === `
1010
+ `))
1011
+ return [];
1012
+ if (key !== undefined)
1013
+ return [key];
1014
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1015
+ });
1016
+ }
1017
+ var IS_CONTROL, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS;
1018
+ var init_state = __esm(() => {
1019
+ init_text2();
1020
+ init_line();
1021
+ init_score();
1022
+ IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1023
+ KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1024
+ MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1025
+ KEYS = {
1026
+ "\x1B[A": "up",
1027
+ "\x1BOA": "up",
1028
+ "\x10": "up",
1029
+ "\x1B[B": "down",
1030
+ "\x1BOB": "down",
1031
+ "\x0E": "down",
1032
+ "\x1B[5~": "pageup",
1033
+ "\x1B[6~": "pagedown",
1034
+ "\x1B[H": "home",
1035
+ "\x1B[1~": "home",
1036
+ "\x1BOH": "home",
1037
+ "\x1B[F": "end",
1038
+ "\x1B[4~": "end",
1039
+ "\x1BOF": "end",
1040
+ "\r": "enter",
1041
+ "\n": "enter",
1042
+ "\x03": "cancel",
1043
+ "\x1B": "cancel",
1044
+ "\x1B[D": "left",
1045
+ "\x1BOD": "left",
1046
+ "\x1B[C": "right",
1047
+ "\x1BOC": "right",
1048
+ "\x1B[1;5D": "wordleft",
1049
+ "\x1B[1;3D": "wordleft",
1050
+ "\x1Bb": "wordleft",
1051
+ "\x1B[1;5C": "wordright",
1052
+ "\x1B[1;3C": "wordright",
1053
+ "\x1Bf": "wordright",
1054
+ "\x01": "linestart",
1055
+ "\x05": "lineend",
1056
+ "\x7F": "erase",
1057
+ "\x1B[3~": "delete",
1058
+ "\b": "killword",
1059
+ "\x1B\x7F": "killword",
1060
+ "\x1B[3;5~": "killnext",
1061
+ "\x1Bd": "killnext",
1062
+ "\x15": "clear",
1063
+ "\v": "killend",
1064
+ "\x17": "word",
1065
+ "\x19": "yank",
1066
+ "\x1A": "suspend",
1067
+ "\t": "tab",
1068
+ "\x1F": "help",
1069
+ "\x1BOP": "help",
1070
+ "\x1B[11~": "help"
1071
+ };
1072
+ });
1073
+
1074
+ // ../kit/src/redraw.ts
1075
+ function overwrite(lines, columns) {
1076
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1077
+ `);
1078
+ }
1079
+ function rowsTaken(lines, columns) {
1080
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1081
+ }
1082
+ var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
1083
+ var init_redraw = __esm(() => {
1084
+ init_format2();
1085
+ });
1086
+
1087
+ // ../kit/src/prompt.ts
1088
+ import process25 from "process";
1089
+ function readKeys(input, paste = { active: false }) {
1090
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
1091
+ }
1092
+ async function confirm(question, { default: fallback, ...settings } = {}) {
1093
+ let answered = fallback;
1094
+ const choices = { true: "Y/n", false: "y/N", undefined: "y/n" }[String(fallback)];
1095
+ const accepted = await ask(question, settings, (colors, state) => [state === "asking" ? asking(colors, question, "", choices) : answer(colors, question, state, answered ? "yes" : "no")], (key) => {
1096
+ if (key === "cancel")
1097
+ return "cancel";
1098
+ if (key === "enter")
1099
+ return answered === undefined ? undefined : "enter";
1100
+ const letter = typeof key === "object" ? key.text.toLowerCase() : "";
1101
+ if (letter !== "y" && letter !== "n")
1102
+ return;
1103
+ answered = letter === "y";
1104
+ return "enter";
1105
+ });
1106
+ return accepted ? answered : undefined;
1107
+ }
1108
+ function asking(colors, question, typed, keys) {
1109
+ return `${colors.cyan("?")} ${question} ${typed === "" ? colors.dim(`(${keys})`) : typed}`;
1110
+ }
1111
+ function answer(colors, question, state, picked) {
1112
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1113
+ }
1114
+ async function ask(question, { hint, terminal = process25 }, render, press) {
1115
+ const { stdin, stderr } = terminal;
1116
+ if (!isInteractive(terminal))
1117
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
1118
+ const colors = paint(stderr);
1119
+ let current = "asking";
1120
+ let outcome;
1121
+ const columns = () => stderr.columns || 80;
1122
+ const draw = (state, last = false) => {
1123
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1124
+ const rows = rowsTaken(frame, columns());
1125
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
1126
+ current = state;
1127
+ };
1128
+ const redraw = () => draw(current);
1129
+ const paste = { active: false };
1130
+ const stop = terminal.stop ?? (terminal === process25 ? stopJob : undefined);
1131
+ const suspend = () => {
1132
+ if (stop === undefined)
1133
+ return;
1134
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
1135
+ stdin.setRawMode(false);
1136
+ stop();
1137
+ stdin.setRawMode(true);
1138
+ stderr.write("\x1B[?25l\x1B[?2004h");
1139
+ };
1140
+ try {
1141
+ stderr.on?.("resize", redraw);
1142
+ stdin.setRawMode(true);
1143
+ stdin.resume();
1144
+ stderr.write("\x1B[?25l\x1B[?2004h");
1145
+ draw("asking");
1146
+ return await new Promise((resolve) => {
1147
+ function onData(data) {
1148
+ for (const key of readKeys(data.toString(), paste)) {
1149
+ if (key === "suspend") {
1150
+ suspend();
1151
+ continue;
1152
+ }
1153
+ const pressed = press(key);
1154
+ if (pressed !== undefined) {
1155
+ settle(pressed);
1156
+ return;
1157
+ }
1158
+ }
1159
+ draw("asking");
1160
+ }
1161
+ function onEnd() {
1162
+ settle("cancel");
1163
+ }
1164
+ function settle(settled) {
1165
+ outcome = settled;
1166
+ stdin.off("data", onData);
1167
+ stdin.off("end", onEnd);
1168
+ resolve(settled === "enter");
1169
+ }
1170
+ stdin.on("data", onData);
1171
+ stdin.on("end", onEnd);
1172
+ });
1173
+ } finally {
1174
+ stderr.off?.("resize", redraw);
1175
+ draw(outcome ?? "cancel", true);
1176
+ stderr.write(`
1177
+ \x1B[?25h\x1B[?2004l`);
1178
+ stdin.setRawMode(false);
1179
+ stdin.pause();
1180
+ }
1181
+ }
1182
+ var PROMPT_KEYS;
1183
+ var init_prompt = __esm(() => {
1184
+ init_answers();
1185
+ init_args();
1186
+ init_format2();
1187
+ init_job();
1188
+ init_mode();
1189
+ init_line();
1190
+ init_state();
1191
+ init_redraw();
1192
+ init_style();
1193
+ PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
1194
+ });
1195
+
1196
+ // src/cli.ts
1197
+ import process26 from "process";
1198
+
1199
+ // ../kit/src/advisory.ts
1200
+ var SEVERITIES = ["low", "moderate", "high", "critical"];
1201
+ function severityRank(severity) {
1202
+ return SEVERITIES.indexOf(severity);
1203
+ }
1204
+ function isIgnored(advisory, ignore) {
1205
+ return ignore.includes(advisory.ghsa ?? "") || ignore.includes(String(advisory.id));
1206
+ }
1207
+
1208
+ // ../kit/src/index.ts
1209
+ init_args();
1210
+
831
1211
  // ../kit/src/argv.ts
832
1212
  import { readFileSync as readFileSync3, realpathSync } from "fs";
833
1213
  import { resolve as resolve3 } from "path";
@@ -852,10 +1232,24 @@ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), scr
852
1232
  const after = at === -1 ? [] : cmdline.slice(at + 1);
853
1233
  return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
854
1234
  }
1235
+ // ../kit/src/chart.ts
1236
+ init_format2();
1237
+ init_mode();
1238
+ init_style();
1239
+ init_theme();
1240
+ // ../kit/src/ci.ts
1241
+ init_args();
1242
+ init_format2();
1243
+
1244
+ // ../kit/src/progress.ts
1245
+ init_format2();
1246
+ import process12 from "process";
1247
+
855
1248
  // ../kit/src/process.ts
856
1249
  import { constants } from "os";
857
1250
  import process11 from "process";
858
1251
  var KILL_GRACE_MS = 2000;
1252
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
859
1253
  function exitCodeOf(code, signal) {
860
1254
  if (code !== null)
861
1255
  return code;
@@ -863,10 +1257,41 @@ function exitCodeOf(code, signal) {
863
1257
  return 128 + signal;
864
1258
  return signal === null ? 129 : 128 + constants.signals[signal];
865
1259
  }
866
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
1260
+ function holdSignals(cleanup) {
1261
+ let received;
1262
+ let child;
1263
+ const held = {
1264
+ get signal() {
1265
+ return received;
1266
+ },
1267
+ forward: (to) => {
1268
+ child = to;
1269
+ },
1270
+ release: () => {
1271
+ for (const signal of SIGNALS)
1272
+ process11.off(signal, onSignal);
1273
+ }
1274
+ };
1275
+ function onSignal(signal) {
1276
+ received = signal;
1277
+ if (child !== undefined) {
1278
+ child.kill(signal);
1279
+ return;
1280
+ }
1281
+ if (cleanup === undefined)
1282
+ return;
1283
+ held.release();
1284
+ cleanup(signal);
1285
+ process11.kill(process11.pid, signal);
1286
+ }
1287
+ for (const signal of SIGNALS)
1288
+ process11.on(signal, onSignal);
1289
+ return held;
1290
+ }
1291
+ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
867
1292
  const chunks = [];
868
1293
  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 } : {} });
1294
+ 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
1295
  const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
871
1296
  const timers = [];
872
1297
  const killGroup = (killing) => {
@@ -942,17 +1367,234 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
942
1367
  };
943
1368
  }
944
1369
 
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}\\`;
1370
+ // ../kit/src/progress.ts
1371
+ init_style();
1372
+ init_theme();
1373
+ var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1374
+ var FRAME_MS = 200;
1375
+ var BAR_WIDTH = 20;
1376
+ var CLEAR_BELOW = "\r\x1B[J";
1377
+ var ESC = String.fromCharCode(27);
1378
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
1379
+ var RESET_STYLE = `${ESC}[0m`;
1380
+ var CTRL_C = 3;
1381
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1382
+ var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
1383
+ function liveRegion(render, stream = process12.stderr, env = process12.env) {
1384
+ if (!takesControlCodes(stream, env))
1385
+ return { redraw: () => {
1386
+ return;
1387
+ }, print: (text) => void stream.write(`${text}
1388
+ `), stop: () => {
1389
+ return;
1390
+ }, pause: () => () => {
1391
+ return;
1392
+ } };
1393
+ const write = stream.write.bind(stream);
1394
+ let frame = 0;
1395
+ let drawn = false;
1396
+ let paused = false;
1397
+ let stopped = false;
1398
+ const columns = () => {
1399
+ const now = stream.getWindowSize?.()[0] ?? stream.columns;
1400
+ return now === undefined || now === 0 ? 80 : now;
1401
+ };
1402
+ const clear = () => {
1403
+ if (drawn)
1404
+ write(CLEAR_BELOW);
1405
+ drawn = false;
1406
+ };
1407
+ const draw = () => {
1408
+ if (paused)
1409
+ return;
1410
+ const width = columns() - 1;
1411
+ const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
1412
+ const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
1413
+ if (lines.length === 0) {
1414
+ clear();
1415
+ return;
1416
+ }
1417
+ write(`${CLEAR_BELOW}${lines.join(`
1418
+ `)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
1419
+ drawn = true;
1420
+ };
1421
+ let timer = setInterval(draw, FRAME_MS);
1422
+ stream.on?.("resize", draw);
1423
+ let restore = interceptOutput(clear);
1424
+ let release = swallowInput();
1425
+ const onExit = () => {
1426
+ clear();
1427
+ release();
1428
+ };
1429
+ const signals = holdSignals(stop);
1430
+ function stop() {
1431
+ stopped = true;
1432
+ clearInterval(timer);
1433
+ stream.off?.("resize", draw);
1434
+ clear();
1435
+ restore();
1436
+ release();
1437
+ process12.off("exit", onExit);
1438
+ signals.release();
1439
+ }
1440
+ function pause() {
1441
+ if (paused || stopped)
1442
+ return () => {
1443
+ return;
1444
+ };
1445
+ paused = true;
1446
+ clearInterval(timer);
1447
+ stream.off?.("resize", draw);
1448
+ clear();
1449
+ restore();
1450
+ release();
1451
+ return () => {
1452
+ if (!paused || stopped)
1453
+ return;
1454
+ paused = false;
1455
+ timer = setInterval(draw, FRAME_MS);
1456
+ timer.unref();
1457
+ stream.on?.("resize", draw);
1458
+ restore = interceptOutput(clear);
1459
+ release = swallowInput();
1460
+ draw();
1461
+ };
1462
+ }
1463
+ timer.unref();
1464
+ process12.on("exit", onExit);
1465
+ return {
1466
+ redraw: draw,
1467
+ print: (text) => {
1468
+ clear();
1469
+ write(`${text}
1470
+ `);
1471
+ draw();
1472
+ },
1473
+ stop,
1474
+ pause
1475
+ };
1476
+ }
1477
+ function progressLine(stream = process12.stderr, env = process12.env) {
1478
+ const colors = paint(stream, env);
1479
+ const write = stream.write.bind(stream);
1480
+ const begun = performance.now();
1481
+ let started = begun;
1482
+ let current;
1483
+ const region = liveRegion((spinner) => current === undefined ? [] : [tintedParts(progressParts(current, spinner, performance.now() - started), colors)], stream, env);
1484
+ const end = (line) => {
1485
+ region.stop();
1486
+ write(`${line}
1487
+ `);
1488
+ };
1489
+ return {
1490
+ update: (progress) => {
1491
+ const step = current?.step;
1492
+ current = progress;
1493
+ if (progress.step !== step) {
1494
+ started = performance.now();
1495
+ region.redraw();
1496
+ }
1497
+ },
1498
+ stop: region.stop,
1499
+ pause: region.pause,
1500
+ done: (text) => end(marked("ok", text, stream, formatDuration(performance.now() - begun), env)),
1501
+ failed: (text) => end(marked("problem", text, stream, undefined, env))
1502
+ };
1503
+ }
1504
+ function progressParts({ step, done, total, unit }, spinner, ms) {
1505
+ const { theme } = activeTheme();
1506
+ const parts = [{ text: spinner, tint: (colors) => tinted(colors, theme.colors.accent) }, { text: ` ${step}`, tint: () => plain }];
1507
+ if (total !== undefined && total > 0) {
1508
+ const counted = Math.min(done ?? 0, total);
1509
+ const filled = Math.round(counted / total * BAR_WIDTH);
1510
+ 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 });
1511
+ }
1512
+ parts.push({ text: ` ${formatElapsed(ms)}`, tint: (colors) => colors.dim });
1513
+ return parts;
1514
+ }
1515
+ function plain(text) {
1516
+ return text;
1517
+ }
1518
+ function tintedParts(parts, colors) {
1519
+ return parts.map(({ text, tint }) => tint(colors)(text)).join("");
1520
+ }
1521
+ function cutToWidth(line, width) {
1522
+ if (Bun.stringWidth(line) <= width)
1523
+ return line;
1524
+ let room = width;
1525
+ let kept = "";
1526
+ let index = 0;
1527
+ let linked = false;
1528
+ while (index < line.length) {
1529
+ ESCAPE_CODE.lastIndex = index;
1530
+ const escape = ESCAPE_CODE.exec(line);
1531
+ if (escape !== null) {
1532
+ kept += escape[0];
1533
+ linked ||= escape[0].startsWith(`${ESC}]`);
1534
+ index = ESCAPE_CODE.lastIndex;
1535
+ continue;
1536
+ }
1537
+ const char = String.fromCodePoint(line.codePointAt(index));
1538
+ const columns = Bun.stringWidth(char);
1539
+ if (columns > room)
1540
+ break;
1541
+ kept += char;
1542
+ room -= columns;
1543
+ index += char.length;
1544
+ }
1545
+ return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
1546
+ }
1547
+ function swallowInput() {
1548
+ const input = process12.stdin;
1549
+ if (!input.isTTY)
1550
+ return () => {
1551
+ return;
1552
+ };
1553
+ const onData = (data) => {
1554
+ if (data.includes(CTRL_C))
1555
+ process12.kill(process12.pid, "SIGINT");
1556
+ };
1557
+ input.setRawMode(true);
1558
+ input.on("data", onData);
1559
+ input.resume();
1560
+ let released = false;
1561
+ return () => {
1562
+ if (released)
1563
+ return;
1564
+ released = true;
1565
+ input.off("data", onData);
1566
+ input.pause();
1567
+ input.setRawMode(false);
1568
+ };
1569
+ }
1570
+ function interceptOutput(clear) {
1571
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
1572
+ const wrapped = targets.map(([target, name]) => {
1573
+ const original = Reflect.get(target, name);
1574
+ const wrapper = (...args) => {
1575
+ clear();
1576
+ return original.apply(target, args);
1577
+ };
1578
+ Reflect.set(target, name, wrapper);
1579
+ return { target, name, original, wrapper };
1580
+ });
1581
+ return () => {
1582
+ for (const { target, name, original, wrapper } of wrapped) {
1583
+ if (Reflect.get(target, name) === wrapper)
1584
+ Reflect.set(target, name, original);
1585
+ }
1586
+ };
1587
+ }
1588
+
1589
+ // ../kit/src/ci.ts
1590
+ init_style();
950
1591
 
951
1592
  // ../kit/src/tool.ts
952
- import process12 from "process";
1593
+ init_format2();
1594
+ import process13 from "process";
953
1595
  function cwdGone() {
954
1596
  try {
955
- process12.cwd();
1597
+ process13.cwd();
956
1598
  return false;
957
1599
  } catch {
958
1600
  return true;
@@ -971,10 +1613,10 @@ function spawnFailure(command, error) {
971
1613
  const missing = !gone && error?.code === "ENOENT";
972
1614
  return new SpawnError(`${command}: ${error instanceof Error ? error.message : String(error)}${gone ? " (the working directory was removed)" : ""}`, missing);
973
1615
  }
974
- async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
1616
+ async function runTool(label, argv, { timeoutMs, cwd, onStart, env } = {}) {
975
1617
  let ran;
976
1618
  try {
977
- ran = await runCommand(argv, { env: process12.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
1619
+ ran = await runCommand(argv, { env: { ...process13.env, ...env }, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
978
1620
  } catch (error) {
979
1621
  throw spawnFailure(label, error);
980
1622
  }
@@ -989,33 +1631,139 @@ async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
989
1631
  return { code: ran.code, ...streams };
990
1632
  }
991
1633
  // ../kit/src/cli.ts
1634
+ init_args();
992
1635
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
993
1636
  import { dirname as dirname3, join as join5 } from "path";
994
- import process15 from "process";
1637
+ import process17 from "process";
1638
+
1639
+ // ../kit/src/askpass.ts
1640
+ import process14 from "process";
1641
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1642
+ async function askpassClient(argv) {
1643
+ const socketPath = process14.env[SOCKET_VARIABLE];
1644
+ if (socketPath === undefined)
1645
+ return;
1646
+ const request = { prompt: argv[0] ?? "", ...process14.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1647
+ const { promise, resolve } = Promise.withResolvers();
1648
+ let received = "";
1649
+ try {
1650
+ await Bun.connect({
1651
+ unix: socketPath,
1652
+ socket: {
1653
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
1654
+ `),
1655
+ data: (_, chunk) => {
1656
+ received += chunk.toString();
1657
+ },
1658
+ close: () => resolve(received),
1659
+ error: () => resolve("")
1660
+ }
1661
+ });
1662
+ } catch {
1663
+ return 1;
1664
+ }
1665
+ const reply = await promise;
1666
+ if (reply === "")
1667
+ return 1;
1668
+ const { answer } = JSON.parse(reply);
1669
+ if (request.notice === true)
1670
+ return 0;
1671
+ if (answer === undefined)
1672
+ return 1;
1673
+ process14.stdout.write(`${answer}
1674
+ `);
1675
+ return 0;
1676
+ }
1677
+
1678
+ // ../kit/src/completions.ts
1679
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1680
+ 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'
1681
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1682
+ set -l current (commandline -ct)
1683
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1684
+ if test "$line" = __files__
1685
+ __fish_complete_path $current
1686
+ else
1687
+ echo $line
1688
+ end
1689
+ end
1690
+ end`;
1691
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1692
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1693
+ local -a lines
1694
+ COMPREPLY=()
1695
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1696
+ for line in "\${lines[@]}"; do
1697
+ if [[ $line == __files__ ]]; then
1698
+ COMPREPLY+=($(compgen -f -- "$cur"))
1699
+ else
1700
+ words+="\${line%%$'\\t'*}"$'\\n'
1701
+ fi
1702
+ done
1703
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1704
+ }`;
1705
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1706
+ local line
1707
+ local -a described plain
1708
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1709
+ if [[ $line == __files__ ]]; then
1710
+ _files
1711
+ elif [[ $line == *$'\\t'* ]]; then
1712
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1713
+ else
1714
+ plain+=("$line")
1715
+ fi
1716
+ done
1717
+ (( \${#described} )) && _describe -V value described
1718
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1719
+ return 0
1720
+ }`;
1721
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1722
+ if (shell === "fish")
1723
+ return `${header}
1724
+ ${FISH_FUNCTION}
1725
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1726
+ `).join("")}`;
1727
+ if (shell === "bash")
1728
+ return `${header}
1729
+ ${BASH_FUNCTION}
1730
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1731
+ `;
1732
+ return `${header}
1733
+ ${ZSH_FUNCTION}
1734
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1735
+ `;
1736
+ }
995
1737
 
996
1738
  // ../kit/src/notify.ts
997
- import process13 from "process";
1739
+ init_format2();
1740
+ init_mode();
1741
+ import process15 from "process";
998
1742
  var NOTIFY_AFTER_MS = 1e4;
999
1743
  var CANCELLED = 130;
1000
1744
  function base64(text) {
1001
1745
  return Buffer.from(text).toString("base64");
1002
1746
  }
1003
- function notification(title, body, env = process13.env) {
1004
- const id = `kit${process13.pid}`;
1747
+ function notification(title, body, env = process15.env) {
1748
+ const id = `kit${process15.pid}`;
1005
1749
  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
1750
  return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1007
1751
  }
1008
- function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1752
+ function notifyEnd(command, code, ms, { stream = process15.stderr, env = process15.env } = {}) {
1009
1753
  if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1010
1754
  return;
1011
1755
  stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1012
1756
  }
1013
1757
 
1758
+ // ../kit/src/cli.ts
1759
+ init_style();
1760
+ init_text2();
1761
+
1014
1762
  // ../kit/src/usage.ts
1015
1763
  import { appendFileSync, mkdirSync } from "fs";
1016
1764
  import { homedir as homedir3 } from "os";
1017
1765
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1018
- import process14 from "process";
1766
+ import process16 from "process";
1019
1767
 
1020
1768
  // ../kit/src/logs.ts
1021
1769
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -1029,14 +1777,14 @@ var usageError;
1029
1777
  function noteUsageError(message) {
1030
1778
  usageError = message;
1031
1779
  }
1032
- function stateHome(env = process14.env) {
1780
+ function stateHome(env = process16.env) {
1033
1781
  const dir = env.XDG_STATE_HOME;
1034
1782
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1035
1783
  }
1036
- function usagePath(env = process14.env) {
1784
+ function usagePath(env = process16.env) {
1037
1785
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1038
1786
  }
1039
- function usageRecorded(env = process14.env) {
1787
+ function usageRecorded(env = process16.env) {
1040
1788
  const off = env.KAYNOOO_CLI_NO_USAGE;
1041
1789
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1042
1790
  }
@@ -1045,12 +1793,12 @@ function flagNames(argv) {
1045
1793
  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
1794
  return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1047
1795
  }
1048
- function usageEntry(bin, command, argv, code, now = new Date) {
1796
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1049
1797
  const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1050
1798
  usageError = undefined;
1051
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1799
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1052
1800
  }
1053
- function recordUsage(entry, env = process14.env) {
1801
+ function recordUsage(entry, env = process16.env) {
1054
1802
  if (!usageRecorded(env))
1055
1803
  return;
1056
1804
  try {
@@ -1066,7 +1814,11 @@ var LEVEL_OPTIONS = {
1066
1814
  ...OUTPUT_OPTIONS,
1067
1815
  help: { type: "boolean", short: "h", description: "show this help" }
1068
1816
  };
1069
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1817
+ var TOP_OPTIONS = {
1818
+ ...LEVEL_OPTIONS,
1819
+ version: { type: "boolean", short: "v", description: "print the version" },
1820
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1821
+ };
1070
1822
  async function commandRows(all, colors) {
1071
1823
  const commands = shown(all);
1072
1824
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -1140,8 +1892,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1140
1892
  `);
1141
1893
  }
1142
1894
  function printError(prefix, message, hint, cause) {
1143
- const colors = paint(process15.stderr);
1144
- const styled = takesControlCodes(process15.stderr);
1895
+ const colors = paint(process17.stderr);
1896
+ const styled = takesControlCodes(process17.stderr);
1145
1897
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1146
1898
  const under = (label, text, tint) => text === undefined ? "" : `
1147
1899
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1184,11 +1936,11 @@ async function dispatch(level, typed, { version, redact }) {
1184
1936
  }
1185
1937
  }
1186
1938
  if (name === undefined && level.path.length > 1) {
1187
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
1939
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process17.stderr));
1188
1940
  return 2;
1189
1941
  }
1190
1942
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1191
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
1943
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process17.stdout));
1192
1944
  return 0;
1193
1945
  }
1194
1946
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1299,6 +2051,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1299
2051
  }
1300
2052
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1301
2053
  }
2054
+ var COMPLETIONS = "--completions";
2055
+ function flagValue([flag = "", ...rest]) {
2056
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
2057
+ }
2058
+ function printCompletionScript(name, args) {
2059
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
2060
+ if (shell === undefined || args.length !== 1) {
2061
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
2062
+ return 2;
2063
+ }
2064
+ console.log(completionScript(shell, [name]).trimEnd());
2065
+ return 0;
2066
+ }
1302
2067
  async function printCandidates(found) {
1303
2068
  for (const line of await found)
1304
2069
  console.log(line);
@@ -1321,15 +2086,20 @@ function packageVersion(entry = Bun.main) {
1321
2086
  }
1322
2087
  async function runCli(cli, argv = scriptArgs()) {
1323
2088
  const version = cli.version ?? packageVersion();
2089
+ const answered = await askpassClient(argv);
2090
+ if (answered !== undefined)
2091
+ return answered;
1324
2092
  if (argv[0] === COMPLETE)
1325
2093
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
2094
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
2095
+ return printCompletionScript(cli.name, flagValue(argv));
1326
2096
  const started = performance.now();
1327
2097
  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
2098
  const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1329
2099
  notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1330
2100
  if (cli.usage !== false) {
1331
2101
  try {
1332
- recordUsage(usageEntry(cli.name, command, argv, code));
2102
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
1333
2103
  } catch {}
1334
2104
  }
1335
2105
  return code;
@@ -1349,43 +2119,43 @@ function commandPath(scope, argv) {
1349
2119
  }
1350
2120
  return path.length === 0 ? undefined : path.join(" ");
1351
2121
  }
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__"]);
2122
+
2123
+ // ../kit/src/index.ts
2124
+ init_config();
2125
+
2126
+ // ../kit/src/excerpt.ts
2127
+ init_text2();
2128
+
2129
+ // ../kit/src/index.ts
2130
+ init_folders();
2131
+ init_format2();
2132
+
2133
+ // ../kit/src/git.ts
2134
+ init_args();
2135
+ // ../kit/src/limit.ts
2136
+ init_args();
2137
+
2138
+ // ../kit/src/index.ts
2139
+ init_mode();
2140
+
1376
2141
  // ../kit/src/pool.ts
1377
- async function pool(items, limit, task) {
2142
+ async function pool(items, limit, task, onDone) {
1378
2143
  const results = Array.from({ length: items.length });
1379
2144
  let next = 0;
2145
+ let done = 0;
1380
2146
  async function worker() {
1381
2147
  while (next < items.length) {
1382
2148
  const index = next++;
1383
2149
  results[index] = await task(items[index]);
2150
+ onDone?.(++done, items.length);
1384
2151
  }
1385
2152
  }
1386
2153
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1387
2154
  return results;
1388
2155
  }
2156
+ // ../kit/src/report.ts
2157
+ init_style();
2158
+ init_text2();
1389
2159
  // ../kit/src/secrets.ts
1390
2160
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1391
2161
  // ../kit/src/sessions.ts
@@ -1402,8 +2172,18 @@ function parseSize(text, bareUnit = 1) {
1402
2172
  const suffix = match[2].toLowerCase();
1403
2173
  return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1404
2174
  }
2175
+
2176
+ // ../kit/src/index.ts
2177
+ init_style();
2178
+ init_text2();
2179
+ init_theme();
2180
+ init_user_config();
2181
+
1405
2182
  // ../kit/src/watch.ts
1406
- import process16 from "process";
2183
+ init_args();
2184
+ init_input();
2185
+ init_style();
2186
+ import process18 from "process";
1407
2187
  import { format } from "util";
1408
2188
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1409
2189
  var DEFAULT_SECONDS = 2;
@@ -1425,7 +2205,7 @@ function withoutWatch(args) {
1425
2205
  }
1426
2206
  return rest;
1427
2207
  }
1428
- async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
2208
+ async function watching(value, step, stream = process18.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1429
2209
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1430
2210
  if (!takesControlCodes(stream))
1431
2211
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1433,12 +2213,12 @@ async function watching(value, step, stream = process16.stdout, sleep = Bun.slee
1433
2213
  for (let round = 0;round < rounds; round++) {
1434
2214
  const held = [];
1435
2215
  const { log, info } = console;
1436
- const write = process16.stdout.write.bind(process16.stdout);
2216
+ const write = process18.stdout.write.bind(process18.stdout);
1437
2217
  const hold = (...parts) => void held.push(`${format(...parts)}
1438
2218
  `);
1439
2219
  console.log = hold;
1440
2220
  console.info = hold;
1441
- process16.stdout.write = (text) => {
2221
+ process18.stdout.write = (text) => {
1442
2222
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1443
2223
  return true;
1444
2224
  };
@@ -1447,7 +2227,7 @@ async function watching(value, step, stream = process16.stdout, sleep = Bun.slee
1447
2227
  } finally {
1448
2228
  console.log = log;
1449
2229
  console.info = info;
1450
- process16.stdout.write = write;
2230
+ process18.stdout.write = write;
1451
2231
  }
1452
2232
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1453
2233
  await sleep(interval);
@@ -1455,9 +2235,10 @@ async function watching(value, step, stream = process16.stdout, sleep = Bun.slee
1455
2235
  return code;
1456
2236
  }
1457
2237
  // ../kit/src/workspace-root.ts
2238
+ init_user_config();
1458
2239
  import { homedir as homedir4 } from "os";
1459
2240
  import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
1460
- import process17 from "process";
2241
+ import process19 from "process";
1461
2242
  function expandHome(path, home) {
1462
2243
  if (path === "~")
1463
2244
  return home;
@@ -1467,7 +2248,7 @@ function configured(env, home) {
1467
2248
  const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
1468
2249
  return typeof folder === "string" && folder !== "" ? folder : undefined;
1469
2250
  }
1470
- function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
2251
+ function workspaceRoot({ given, env = process19.env, home = homedir4() } = {}) {
1471
2252
  const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1472
2253
  return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1473
2254
  }
@@ -1475,7 +2256,7 @@ function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
1475
2256
  import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync7, statSync as statSync2 } from "fs";
1476
2257
  import { readdir } from "fs/promises";
1477
2258
  import { join as join9, relative, resolve as resolve5 } from "path";
1478
- import process19 from "process";
2259
+ import process21 from "process";
1479
2260
 
1480
2261
  // src/osv.ts
1481
2262
  import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
@@ -1704,12 +2485,11 @@ async function osvAudit(dir, level, ignore, fetcher = fetch) {
1704
2485
  }
1705
2486
 
1706
2487
  // 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
1708
-
1709
- 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
- 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.
2488
+ 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
1711
2489
 
1712
- Reach for it to sweep many repositories at once; \`pkg audit\` vets the one repository in a folder (package age, install scripts, licences) as well as its advisories, and shares --level, --prod and --ignore.`;
2490
+ Each package with an advisory is one row: its worst severity, advisory count, prod or dev, direct or via the direct dependencies leading to it, and the version that fixes every advisory at once.
2491
+ It reaches the network: \`bun audit --json\` for a bun.lock, osv.dev for a composer.lock, Cargo.lock or uv.lock; the walk goes three levels deep and stops at a lockfile.
2492
+ To sweep many repositories at once; \`pkg audit\` vets the one repository in depth.`;
1713
2493
  var EXITS = [[0, "no repository has an advisory at the level asked"], [1, "one has"], [2, "a repository's audit failed, no lockfile sits under root, a usage error or a root that is no folder"]];
1714
2494
  var OPTIONS = {
1715
2495
  level: { type: "string", choices: SEVERITIES, default: "moderate", description: "only the advisories at least this severe: low, moderate, high or critical" },
@@ -1812,7 +2592,7 @@ function failure(ran) {
1812
2592
  `).at(-1) ?? `exit ${ran.code}`;
1813
2593
  }
1814
2594
  function tint(severity) {
1815
- const colors = paint(process19.stdout);
2595
+ const colors = paint(process21.stdout);
1816
2596
  if (severity === "critical" || severity === "high")
1817
2597
  return colors.red;
1818
2598
  return severity === "moderate" ? colors.yellow : colors.dim;
@@ -1828,15 +2608,23 @@ function rows(findings) {
1828
2608
  ]);
1829
2609
  }
1830
2610
  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"] });
2611
+ 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
2612
  const root = resolve5(positionals[0] ?? ".");
1833
2613
  if (!existsSync6(root) || !statSync2(root).isDirectory())
1834
2614
  fail(`no folder ${root}`);
1835
2615
  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 ?? []));
2616
+ const progress = progressLine();
2617
+ let audits;
2618
+ try {
2619
+ progress.update({ step: "finding the repositories" });
2620
+ const paths = await findRepos(root);
2621
+ if (paths.length === 0)
2622
+ fail(`no bun.lock, composer.lock, Cargo.lock or uv.lock under ${root}`);
2623
+ progress.update({ step: "auditing", done: 0, total: paths.length, unit: "repositories" });
2624
+ 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" }));
2625
+ } finally {
2626
+ progress.stop();
2627
+ }
1840
2628
  const kept = audits.map((each) => ({ ...each, findings: values.prod === true ? each.findings.filter((found) => found.scope === "prod") : each.findings }));
1841
2629
  if (values.json === true)
1842
2630
  printJson(kept);
@@ -1847,8 +2635,8 @@ async function audit(args) {
1847
2635
  return kept.some((each) => each.findings.length > 0) ? 1 : 0;
1848
2636
  }
1849
2637
  function show(audits, total) {
1850
- const label = role("label", process19.stdout);
1851
- const path = role("path", process19.stdout);
2638
+ const label = role("label", process21.stdout);
2639
+ const path = role("path", process21.stdout);
1852
2640
  const flagged = audits.filter((each) => each.error !== undefined || each.findings.length > 0);
1853
2641
  if (flagged.length === 0) {
1854
2642
  console.log(label(`no advisory in ${total} ${total === 1 ? "repository" : "repositories"}`));
@@ -1870,13 +2658,13 @@ function show(audits, total) {
1870
2658
  // src/repos.ts
1871
2659
  import { existsSync as existsSync8, statSync as statSync3 } from "fs";
1872
2660
  import { basename as basename2, relative as relative2 } from "path";
1873
- import process21 from "process";
2661
+ import process23 from "process";
1874
2662
 
1875
2663
  // src/repos-scan.ts
1876
2664
  import { existsSync as existsSync7 } from "fs";
1877
2665
  import { readdir as readdir2 } from "fs/promises";
1878
2666
  import { basename, join as join10 } from "path";
1879
- import process20 from "process";
2667
+ import process22 from "process";
1880
2668
  var MAX_DEPTH2 = 3;
1881
2669
  var CONCURRENCY2 = 8;
1882
2670
  var PACKAGE_CONCURRENCY = 4;
@@ -1923,7 +2711,7 @@ async function findRepos2(root, skip) {
1923
2711
  }
1924
2712
  async function read(path, args, timeoutMs = GIT_MS) {
1925
2713
  try {
1926
- const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...process20.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs });
2714
+ const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...process22.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs });
1927
2715
  return ran.code === 0 && !ran.timedOut ? ran.text.trim() : undefined;
1928
2716
  } catch {
1929
2717
  return;
@@ -2000,7 +2788,7 @@ function firstLine(text) {
2000
2788
  }
2001
2789
  async function fastForward(path) {
2002
2790
  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 });
2791
+ 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
2792
  if (ran.timedOut)
2005
2793
  return "timed out";
2006
2794
  return ran.code === 0 ? undefined : firstLine(ran.text.trim()) || `exit ${ran.code}`;
@@ -2010,17 +2798,14 @@ async function fastForward(path) {
2010
2798
  }
2011
2799
 
2012
2800
  // 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
2801
+ var USAGE2 = `ws repos [options] [root]: the git repositories under root (the configured workspace by default) that need attention: dirty files, commits not pushed, an upstream ahead, commits since the latest tag
2014
2802
 
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.
2016
-
2017
- Ahead and behind are those of the last fetch unless --fetch refreshes the upstreams first, which reaches the remote.
2018
- --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.
2019
- --path prints only the paths of the repositories listed, one per line, for xargs -d '\\n'.`;
2803
+ A clean repository, or one with only unreleased commits, is left out unless --all or --only unreleased. The walk goes ${MAX_DEPTH2} levels deep and skips the names in "skip" of \`~/.config/kaynooo-cli/repos.json\`; ahead and behind are those of the last fetch unless --fetch reaches the remote.
2804
+ --pull fetches, then fast-forwards only the repositories listed that are clean, on a branch and only behind their upstream; the others are reported as skipped.`;
2020
2805
  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
2806
  var OPTIONS2 = {
2022
2807
  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" },
2808
+ only: { type: "string", multiple: true, choices: REASONS, description: "only the repositories with this reason: dirty, unpushed, unreleased or behind, repeatable" },
2024
2809
  watch: watchOption("the repositories"),
2025
2810
  fetch: { type: "boolean", conflicts: ["watch"], description: "refresh the upstreams first (reaches the remote)" },
2026
2811
  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 +2828,7 @@ function releasedCell(repo) {
2043
2828
  return repo.packages.filter((release) => release.unreleased > 0).map((release) => `${release.name} ${release.unreleased}`).join(", ") || "-";
2044
2829
  return repo.tag === null || repo.unreleased === 0 ? "-" : `${repo.unreleased} since ${repo.tag}`;
2045
2830
  }
2046
- function syncCell(repo, stream = process21.stdout) {
2831
+ function syncCell(repo, stream = process23.stdout) {
2047
2832
  const colors = paint(stream);
2048
2833
  const ahead = repo.ahead ?? 0;
2049
2834
  const behind = repo.behind ?? 0;
@@ -2054,7 +2839,7 @@ function syncCell(repo, stream = process21.stdout) {
2054
2839
  return parts.length === 0 ? colors.dim("-") : `${parts.join(" ")}${diverged ? colors.yellow(" diverged") : ""}`;
2055
2840
  }
2056
2841
  var DEFAULT_BRANCHES = new Set(["main", "master"]);
2057
- function branchCell(repo, stream = process21.stdout) {
2842
+ function branchCell(repo, stream = process23.stdout) {
2058
2843
  const colors = paint(stream);
2059
2844
  if (repo.unreadable)
2060
2845
  return colors.red("? (unreadable)");
@@ -2063,8 +2848,8 @@ function branchCell(repo, stream = process21.stdout) {
2063
2848
  return DEFAULT_BRANCHES.has(repo.branch) ? repo.branch : role("accent", stream)(repo.branch);
2064
2849
  }
2065
2850
  function row(repo, shown) {
2066
- const colors = paint(process21.stdout);
2067
- const tint = role("path", process21.stdout);
2851
+ const colors = paint(process23.stdout);
2852
+ const tint = role("path", process23.stdout);
2068
2853
  const unreleased = releasedCell(repo);
2069
2854
  return [
2070
2855
  tint(shown),
@@ -2075,19 +2860,31 @@ function row(repo, shown) {
2075
2860
  unreleased === "-" ? colors.dim("-") : colors.cyan(unreleased)
2076
2861
  ];
2077
2862
  }
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"]] });
2863
+ async function repos(args, watched = false) {
2864
+ 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
2865
  if (values.watch !== undefined)
2081
- return watching(values.watch, async () => repos(withoutWatch(args)));
2866
+ return watching(values.watch, async () => repos(withoutWatch(args), true));
2082
2867
  const root = workspaceRoot({ given: positionals[0] });
2083
2868
  if (!existsSync8(root) || !statSync3(root).isDirectory())
2084
2869
  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));
2870
+ const only = values.only ?? [];
2871
+ const progress = watched ? undefined : progressLine();
2872
+ const fetching = values.fetch === true || values.pull === true;
2873
+ const step = fetching ? "fetching" : "reading";
2874
+ let states;
2875
+ try {
2876
+ progress?.update({ step: "finding the repositories" });
2877
+ const paths = await findRepos2(root, await skipped());
2878
+ progress?.update({ step, done: 0, total: paths.length, unit: "repositories" });
2879
+ states = await pool(paths, configuredNumber("repos", "concurrency", CONCURRENCY2), async (path) => inspect(path, fetching), (done, total) => progress?.update({ step, done, total, unit: "repositories" }));
2880
+ } finally {
2881
+ progress?.stop();
2882
+ }
2088
2883
  const keeps = (repo) => {
2089
2884
  const reasons = reasonsOf(repo);
2090
- return only === undefined ? values.all === true || reasons.length > 0 || repo.unreadable : reasons.includes(only);
2885
+ if (only.length > 0)
2886
+ return reasons.some((reason) => only.includes(reason));
2887
+ return values.all === true || reasons.some((reason) => reason !== "unreleased") || repo.unreadable;
2091
2888
  };
2092
2889
  let failedPulls = 0;
2093
2890
  if (values.pull === true) {
@@ -2098,12 +2895,12 @@ async function repos(args) {
2098
2895
  const blocker = pullBlocker(repo);
2099
2896
  const refused = blocker === undefined ? await fastForward(repo.path) : undefined;
2100
2897
  if (blocker !== undefined) {
2101
- log(marked("note", `${repo.name} skipped`, process21.stdout, blocker));
2898
+ log(marked("note", `${repo.name} skipped`, process23.stdout, blocker));
2102
2899
  } else if (refused !== undefined) {
2103
2900
  failedPulls++;
2104
- log(marked("problem", `${repo.name} not pulled`, process21.stdout, refused));
2901
+ log(marked("problem", `${repo.name} not pulled`, process23.stdout, refused));
2105
2902
  } else {
2106
- log(marked("ok", `${repo.name} pulled`, process21.stdout, `${repo.behind} ${repo.behind === 1 ? "commit" : "commits"}`));
2903
+ log(marked("ok", `${repo.name} pulled`, process23.stdout, `${repo.behind} ${repo.behind === 1 ? "commit" : "commits"}`));
2107
2904
  states[index] = await inspect(repo.path, false);
2108
2905
  }
2109
2906
  }
@@ -2118,7 +2915,7 @@ async function repos(args) {
2118
2915
  printJson(kept.map((repo) => ({ ...repo, reasons: reasonsOf(repo) })));
2119
2916
  return failedPulls > 0 ? 1 : 0;
2120
2917
  }
2121
- const label = role("label", process21.stdout);
2918
+ const label = role("label", process23.stdout);
2122
2919
  printHeader("repos", `${basename2(root)} \xB7 ${states.length} ${states.length === 1 ? "repository" : "repositories"}`);
2123
2920
  if (kept.length === 0) {
2124
2921
  console.log(label(`nothing needs attention in ${states.length} repositories`));
@@ -2137,212 +2934,7 @@ async function repos(args) {
2137
2934
  import { existsSync as existsSync11, statSync as statSync4 } from "fs";
2138
2935
  import { homedir as homedir6 } from "os";
2139
2936
  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
- }
2937
+ init_prompt();
2346
2938
 
2347
2939
  // src/apply.ts
2348
2940
  import { existsSync as existsSync10 } from "fs";
@@ -2360,7 +2952,8 @@ import { lstat, readdir as readdir3 } from "fs/promises";
2360
2952
  import { join as join11 } from "path";
2361
2953
  var FS_LIMIT = 32;
2362
2954
  var FIND_MS = 60000;
2363
- var FIND_LINE = /^(\d+) (\S+) (\d+)$/gm;
2955
+ var FIND_LINE = /^(\w) (\d+) (\S+) (\d+) (\d+)$/gm;
2956
+ var OWN_UID = process.getuid?.() ?? -1;
2364
2957
  var waiting = [];
2365
2958
  var running = 0;
2366
2959
  async function gated(call) {
@@ -2374,9 +2967,10 @@ async function gated(call) {
2374
2967
  waiting.shift()?.();
2375
2968
  }
2376
2969
  }
2377
- async function walkSize(folder) {
2970
+ async function walk(folder, uid) {
2378
2971
  const seen = new Set;
2379
2972
  let total = 0;
2973
+ let foreign = 0;
2380
2974
  const visit = async (dir) => {
2381
2975
  let entries;
2382
2976
  try {
@@ -2386,10 +2980,12 @@ async function walkSize(folder) {
2386
2980
  }
2387
2981
  await Promise.all(entries.map(async (entry) => {
2388
2982
  const path = join11(dir, entry.name);
2389
- if (entry.isDirectory())
2390
- return visit(path);
2391
2983
  try {
2392
2984
  const stat = await gated(async () => lstat(path));
2985
+ if (stat.uid !== uid)
2986
+ foreign++;
2987
+ if (entry.isDirectory())
2988
+ return await visit(path);
2393
2989
  if (stat.nlink > 1) {
2394
2990
  const key = `${stat.dev}:${stat.ino}`;
2395
2991
  if (seen.has(key))
@@ -2400,18 +2996,27 @@ async function walkSize(folder) {
2400
2996
  } catch {}
2401
2997
  }));
2402
2998
  };
2999
+ try {
3000
+ if ((await lstat(folder)).uid !== uid)
3001
+ foreign++;
3002
+ } catch {}
2403
3003
  await visit(folder);
2404
- return total;
3004
+ return { bytes: total, foreign };
2405
3005
  }
2406
- async function findSize(folder) {
3006
+ async function findSize(folder, uid) {
2407
3007
  try {
2408
- const ran = await runCommand(["find", "-P", folder, "(", "-type", "f", "-o", "-type", "l", ")", "-printf", "%n %D:%i %s\\n"], { timeoutMs: FIND_MS });
3008
+ const ran = await runCommand(["find", "-P", folder, "-printf", "%y %n %D:%i %s %U\\n"], { timeoutMs: FIND_MS });
2409
3009
  const lines = [...ran.text.matchAll(FIND_LINE)];
2410
3010
  if (ran.timedOut || ran.code !== 0 && lines.length === 0)
2411
3011
  return;
2412
3012
  const seen = new Set;
2413
3013
  let total = 0;
2414
- for (const [, links, id, bytes] of lines) {
3014
+ let foreign = 0;
3015
+ for (const [, type, links, id, bytes, owner] of lines) {
3016
+ if (Number(owner) !== uid)
3017
+ foreign++;
3018
+ if (type !== "f" && type !== "l")
3019
+ continue;
2415
3020
  if (Number(links) > 1) {
2416
3021
  if (seen.has(id))
2417
3022
  continue;
@@ -2419,13 +3024,13 @@ async function findSize(folder) {
2419
3024
  }
2420
3025
  total += Number(bytes);
2421
3026
  }
2422
- return total;
3027
+ return { bytes: total, foreign };
2423
3028
  } catch {
2424
3029
  return;
2425
3030
  }
2426
3031
  }
2427
- async function sizeOf(folder) {
2428
- return await findSize(folder) ?? await walkSize(folder);
3032
+ async function measure(folder, uid = OWN_UID) {
3033
+ return await findSize(folder, uid) ?? await walk(folder, uid);
2429
3034
  }
2430
3035
 
2431
3036
  // src/sweep-scan.ts
@@ -2566,13 +3171,13 @@ async function judgeFolder(path, kind, inside) {
2566
3171
  if (existsSync9(join12(path, ".git")))
2567
3172
  return { skip: "holds a git repository" };
2568
3173
  if (located === "none")
2569
- return name === "node_modules" || inside !== undefined ? { entry: { path, kind, committedAt: undefined, action: "remove", inside } } : { skip: "not in a git repository" };
3174
+ 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
3175
  const tracked = await gitIn(parent, ["ls-files", "--", name]);
2571
3176
  if (tracked.code !== 0 || tracked.stdout !== "")
2572
3177
  return { skip: "tracked by git" };
2573
3178
  if (name !== "node_modules" && inside === undefined && (await gitIn(parent, ["check-ignore", "-q", "--", name])).code !== 0)
2574
3179
  return { skip: "not ignored by git" };
2575
- return { entry: { path, kind, committedAt: await lastCommitOf(located.top), action: "remove", inside } };
3180
+ return { entry: { path, kind, committedAt: await lastCommitOf(located.top), action: "remove", inside, project: located.top } };
2576
3181
  }
2577
3182
  async function judgeWorktree(path) {
2578
3183
  const located = await toplevelOf(dirname5(path));
@@ -2604,23 +3209,26 @@ async function judgeWorktree(path) {
2604
3209
  if (unique.stdout !== "")
2605
3210
  return keep(`${unique.stdout.split(`
2606
3211
  `).length} commits on no other branch or remote`);
2607
- return { entry: { path, kind: "worktree", committedAt, action: "remove", repo: top } };
3212
+ return { entry: { path, kind: "worktree", committedAt, action: "remove", repo: top, project: path } };
2608
3213
  }
2609
3214
  async function judge(candidate) {
2610
3215
  if (candidate.global === true)
2611
3216
  return { entry: { path: candidate.path, kind: candidate.kind, committedAt: undefined, action: "remove" } };
2612
3217
  return candidate.kind === "worktree" ? judgeWorktree(candidate.path) : judgeFolder(candidate.path, candidate.kind, candidate.inside);
2613
3218
  }
2614
- async function inspect2({ candidates, skipped }) {
3219
+ async function inspect2({ candidates, skipped }, onDone, uid) {
2615
3220
  const entries = [];
2616
3221
  const rejected = [...skipped];
2617
3222
  await pool(candidates, 8, async (candidate) => {
2618
3223
  const verdict = await judge(candidate);
2619
- if ("skip" in verdict)
3224
+ if ("skip" in verdict) {
2620
3225
  rejected.push({ path: candidate.path, reason: verdict.skip });
2621
- else
2622
- entries.push({ ...verdict.entry, bytes: await sizeOf(candidate.path) });
2623
- });
3226
+ return;
3227
+ }
3228
+ const { bytes, foreign } = await measure(candidate.path, uid);
3229
+ const owned = foreign > 0 && verdict.entry.action === "remove" ? { action: "keep", reason: `${foreign} ${foreign === 1 ? "entry" : "entries"} owned by another user (a container's?)` } : {};
3230
+ entries.push({ ...verdict.entry, ...owned, bytes });
3231
+ }, onDone);
2624
3232
  const listed = new Set(entries.filter((entry) => entry.action === "remove").map((entry) => entry.path));
2625
3233
  return { entries: entries.filter((entry) => entry.inside === undefined || !listed.has(entry.inside)), skipped: rejected };
2626
3234
  }
@@ -2661,12 +3269,81 @@ async function applyAll(entries, done) {
2661
3269
  return outcomes;
2662
3270
  }
2663
3271
 
3272
+ // src/busy.ts
3273
+ import { readdir as readdir5, readFile, readlink } from "fs/promises";
3274
+ import { basename as basename5, join as join14 } from "path";
3275
+ var DEV_PROGRAMS = new Set(["node", "bun", "deno", "npm", "npx", "pnpm", "yarn", "bunx", "vite", "esbuild", "ruby", "java", "cargo", "go", "php", "php-fpm"]);
3276
+ var DEV_PREFIXES = ["python", "php"];
3277
+ var DOCKER_MS = 5000;
3278
+ var PID = /^\d+$/;
3279
+ var PARENT = /^ \S+ (\d+)/;
3280
+ function isDevProgram(comm) {
3281
+ return DEV_PROGRAMS.has(comm) || DEV_PREFIXES.some((prefix) => comm.startsWith(prefix));
3282
+ }
3283
+ async function quietly(read) {
3284
+ try {
3285
+ return await read();
3286
+ } catch {
3287
+ return;
3288
+ }
3289
+ }
3290
+ async function lineage(pid, root) {
3291
+ const seen = new Set;
3292
+ for (let current = pid;current > 1 && !seen.has(current); ) {
3293
+ seen.add(current);
3294
+ const stat = await quietly(async () => readFile(join14(root, String(current), "stat"), "utf8"));
3295
+ const parent = Number(PARENT.exec(stat?.slice(stat.lastIndexOf(")") + 1) ?? "")?.[1]);
3296
+ if (!Number.isInteger(parent))
3297
+ break;
3298
+ current = parent;
3299
+ }
3300
+ return seen;
3301
+ }
3302
+ async function processPlaces(root = "/proc", self = process.pid) {
3303
+ const own = await lineage(self, root);
3304
+ const pids = (await quietly(async () => readdir5(root)) ?? []).filter((name) => PID.test(name)).map(Number).filter((pid) => !own.has(pid));
3305
+ const places = [];
3306
+ await Promise.all(pids.map(async (pid) => {
3307
+ const comm = (await quietly(async () => readFile(join14(root, String(pid), "comm"), "utf8")))?.trim();
3308
+ if (comm === undefined || !isDevProgram(comm))
3309
+ return;
3310
+ const cwd = await quietly(async () => readlink(join14(root, String(pid), "cwd")));
3311
+ const argv = (await quietly(async () => readFile(join14(root, String(pid), "cmdline"), "utf8")))?.split("\x00").filter((arg) => arg.startsWith("/")) ?? [];
3312
+ const who = `pid ${pid} ${comm}`;
3313
+ for (const path of [cwd, ...argv.slice(1)]) {
3314
+ if (path !== undefined)
3315
+ places.push({ path, who });
3316
+ }
3317
+ }));
3318
+ return places;
3319
+ }
3320
+ async function containerPlaces() {
3321
+ const ids = await quietly(async () => runCommand(["docker", "ps", "-q"], { timeoutMs: DOCKER_MS }));
3322
+ if (ids === undefined || ids.code !== 0 || ids.text.trim() === "")
3323
+ return [];
3324
+ const inspected = await quietly(async () => runCommand(["docker", "inspect", "--format", '{{.Name}}{{range .Mounts}}{{if eq .Type "bind"}}\t{{.Source}}{{end}}{{end}}', ...ids.text.trim().split(`
3325
+ `)], { timeoutMs: DOCKER_MS }));
3326
+ if (inspected === undefined || inspected.code !== 0)
3327
+ return [];
3328
+ return inspected.text.trim().split(`
3329
+ `).flatMap((line) => {
3330
+ const [name = "", ...sources] = line.split("\t");
3331
+ return sources.map((path) => ({ path, who: `container ${basename5(name)}` }));
3332
+ });
3333
+ }
3334
+ var within = (path, folder) => path === folder || path.startsWith(`${folder}/`);
3335
+ function userOf(folder, processes, containers) {
3336
+ return processes.find((place) => within(place.path, folder))?.who ?? containers.find((place) => within(place.path, folder) || within(folder, place.path))?.who;
3337
+ }
3338
+
2664
3339
  // src/sweep.ts
2665
3340
  var LARGE = 100 * 1024 ** 2;
2666
3341
  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
3342
+ var USAGE3 = `ws sweep [options] [root]: lists the regenerable folders, caches and worktrees under root (the configured workspace by default, ${MAX_DEPTH3} levels down), largest first with the age of the repo's last commit
2668
3343
 
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.`;
3344
+ Dry unless --apply, which deletes for good, not trashed, after a confirm showing the total (off a terminal, pass --yes).
3345
+ 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.
3346
+ What a running dev process or container uses, a folder holding files another user owns and a worktree that is not removable stay listed as kept, with the reason, and count for nothing in the total.`;
2670
3347
  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
3348
  var ONLY_KINDS = { worktrees: "worktree", folders: "folder", caches: "cache" };
2672
3349
  var OPTIONS3 = {
@@ -2674,7 +3351,7 @@ var OPTIONS3 = {
2674
3351
  yes: { type: "boolean", short: "y", description: "with --apply, skip the confirm" },
2675
3352
  older: { type: "string", description: "only the entries whose repo last committed longer ago than this (30d, 12h)" },
2676
3353
  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)" },
3354
+ 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
3355
  docker: { type: "boolean", description: "add the docker system df output, which alone takes about ten seconds" },
2679
3356
  json: jsonOption("{root, entries: [{path, kind (folder, worktree or cache), bytes, committedAt, action (remove or keep), reason}], skipped: [{path, reason}], reclaimable, docker, removed?}")
2680
3357
  };
@@ -2689,22 +3366,31 @@ async function dockerUsage() {
2689
3366
  }
2690
3367
  }
2691
3368
  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"] });
3369
+ 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
3370
  if (positionals.length > 1)
2694
3371
  badUsage("give one root");
2695
3372
  const root = workspaceRoot({ given: positionals[0] });
2696
3373
  if (!existsSync11(root) || !statSync4(root).isDirectory())
2697
3374
  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
3375
  const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0);
2701
3376
  const minBytes = values.min === undefined ? 0 : parseSize(values.min);
2702
3377
  if (minBytes === undefined)
2703
3378
  badUsage(`--min takes a size such as 500K, 10M or 1G, not ${values.min}`);
2704
3379
  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 });
3380
+ const progress = progressLine();
3381
+ let scanned;
3382
+ try {
3383
+ progress.update({ step: "finding the folders" });
3384
+ const found = await findCandidates(root, homedir6(), positionals.length === 0 || values.only === "caches");
3385
+ const wanted = values.only === undefined ? found.candidates : found.candidates.filter((candidate) => candidate.kind === ONLY_KINDS[values.only]);
3386
+ progress.update({ step: "sizing", done: 0, total: wanted.length, unit: "folders" });
3387
+ scanned = await inspect2({ candidates: wanted, skipped: found.skipped }, (done, total) => progress.update({ step: "sizing", done, total, unit: "folders" }));
3388
+ progress.update({ step: "looking for running servers and containers" });
3389
+ await keepWhatIsInUse(scanned.entries);
3390
+ } finally {
3391
+ progress.stop();
3392
+ }
3393
+ const { entries: all, skipped } = scanned;
2708
3394
  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
3395
  const removable = entries.filter((entry) => entry.action === "remove");
2710
3396
  const reclaimable = removable.reduce((sum, entry) => sum + entry.bytes, 0);
@@ -2749,6 +3435,19 @@ function report2(root, outcome, json) {
2749
3435
  else
2750
3436
  problem(`kept ${relative3(root, outcome.path)}`, outcome.error);
2751
3437
  }
3438
+ async function keepWhatIsInUse(entries) {
3439
+ const candidates = entries.filter((entry) => entry.action === "remove" && entry.project !== undefined);
3440
+ if (candidates.length === 0)
3441
+ return;
3442
+ const [processes, containers] = await Promise.all([processPlaces(), containerPlaces()]);
3443
+ for (const entry of candidates) {
3444
+ const who = userOf(entry.project, processes, containers);
3445
+ if (who !== undefined) {
3446
+ entry.action = "keep";
3447
+ entry.reason = `in use by ${who}`;
3448
+ }
3449
+ }
3450
+ }
2752
3451
  function print(root, entries, skipped, reclaimable, now) {
2753
3452
  if (entries.length === 0) {
2754
3453
  console.log("nothing to sweep");
@@ -2767,7 +3466,7 @@ ${tt(reclaimable)} reclaimable${skipped === 0 ? "" : `, ${skipped} skipped (syml
2767
3466
  }
2768
3467
 
2769
3468
  // src/cli.ts
2770
- process24.exitCode = await runCli({
3469
+ process26.exitCode = await runCli({
2771
3470
  name: "ws",
2772
3471
  about: "the repositories under a root: the ones needing attention, the folders worth reclaiming and their known vulnerabilities",
2773
3472
  replaces: "a cd, git status and du loop over each repository of the workspace, and a bun audit run in each",