@kaynooo/cli-workspace 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,2217 @@
1
+ #!/usr/bin/env -S bun --no-env-file
2
+ // @bun
3
+
4
+ // src/cli.ts
5
+ import process16 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 process5 from "process";
17
+ import { parseArgs } from "util";
18
+
19
+ // ../kit/src/format.ts
20
+ import process3 from "process";
21
+
22
+ // ../kit/src/style.ts
23
+ import process2 from "process";
24
+
25
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
26
+ function x(s) {
27
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
28
+ if (!/^[a-f0-9]+$/.test(r))
29
+ return [0, 0, 0];
30
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
31
+ if (t === 3 || t === 4) {
32
+ let c = n(r[0] + r[0]), u = n(r[1] + r[1]), h = n(r[2] + r[2]), g = t === 4 ? n(r[3] + r[3]) : undefined;
33
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
34
+ }
35
+ if (t !== 6 && t !== 8)
36
+ throw Error(`Invalid hex color length: ${t}`);
37
+ let a = n(r.slice(0, 2)), b = n(r.slice(2, 4)), o = n(r.slice(4, 6)), y = t === 8 ? n(r.slice(6, 8)) : undefined;
38
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
39
+ throw Error(`Invalid hex color value: ${s}`);
40
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
41
+ }
42
+ function A(s) {
43
+ let [r, t, n, a] = s;
44
+ if (a)
45
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
46
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
47
+ }
48
+ function R(s, r, t) {
49
+ s = (s % 360 + 360) % 360, t /= 100;
50
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
51
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
52
+ return Math.round(255 * y);
53
+ };
54
+ return [a(0), a(8), a(4)];
55
+ }
56
+ function k(s) {
57
+ let [r, t, n] = s;
58
+ r /= 255, t /= 255, n /= 255;
59
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
60
+ if (a !== b) {
61
+ let u = a - b;
62
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
63
+ o = (t - n) / u + (t < n ? 6 : 0);
64
+ else if (a === t)
65
+ o = (n - r) / u + 2;
66
+ else
67
+ o = (r - t) / u + 4;
68
+ o /= 6;
69
+ }
70
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
71
+ }
72
+ function H(s, r, t) {
73
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
74
+ let n = (a) => {
75
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
76
+ return Math.round(255 * o);
77
+ };
78
+ return [n(5), n(3), n(1)];
79
+ }
80
+ function f(s) {
81
+ let [r, t, n] = s;
82
+ r /= 255, t /= 255, n /= 255;
83
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = a - b, y = 0, c = a === 0 ? 0 : o / a, u = a;
84
+ if (o !== 0) {
85
+ if (a === r)
86
+ y = (t - n) / o + (t < n ? 6 : 0);
87
+ else if (a === t)
88
+ y = (n - r) / o + 2;
89
+ else
90
+ y = (r - t) / o + 4;
91
+ y /= 6;
92
+ }
93
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
94
+ }
95
+ function O(s) {
96
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
97
+ if (a === 1)
98
+ return [0, 0, 0, 100];
99
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
100
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
101
+ }
102
+ function v(s, r, t, n) {
103
+ return s /= 100, r /= 100, t /= 100, n /= 100, [Math.round(255 * (1 - s) * (1 - n)), Math.round(255 * (1 - r) * (1 - n)), Math.round(255 * (1 - t) * (1 - n))];
104
+ }
105
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
106
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
107
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
108
+ function T(s) {
109
+ let r = m(s[0] / 255), t = m(s[1] / 255), n = m(s[2] / 255), a = Math.cbrt(0.4122214708 * r + 0.5363325363 * t + 0.0514459929 * n), b = Math.cbrt(0.2119034982 * r + 0.6806995451 * t + 0.1073969566 * n), o = Math.cbrt(0.0883024619 * r + 0.2817188376 * t + 0.6299787005 * n);
110
+ return [i(0.2104542553 * a + 0.793617785 * b - 0.0040720468 * o, 4), i(1.9779984951 * a - 2.428592205 * b + 0.4505937099 * o, 4), i(0.0259040371 * a + 0.7827717662 * b - 0.808675766 * o, 4)];
111
+ }
112
+ function M(s, r, t) {
113
+ let n = (s + 0.3963377774 * r + 0.2158037573 * t) ** 3, a = (s - 0.1055613458 * r - 0.0638541728 * t) ** 3, b = (s - 0.0894841775 * r - 1.291485548 * t) ** 3, o = p(4.0767416621 * n - 3.3077115913 * a + 0.2309699292 * b), y = p(-1.2684380046 * n + 2.6097574011 * a - 0.3413193965 * b), c = p(-0.0041960863 * n - 0.7034186147 * a + 1.707614701 * b), u = (h) => Math.min(255, Math.max(0, Math.round(h * 255)));
114
+ return [u(o), u(y), u(c)];
115
+ }
116
+ function d(s) {
117
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
118
+ return [i(r, 4), i(a, 4), i(b, 2)];
119
+ }
120
+ function C(s, r, t) {
121
+ let n = t * Math.PI / 180;
122
+ return M(s, r * Math.cos(n), r * Math.sin(n));
123
+ }
124
+ function l(s) {
125
+ let r = s / 255;
126
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
127
+ }
128
+
129
+ class e {
130
+ r;
131
+ g;
132
+ b;
133
+ a;
134
+ constructor(s, r, t, n = 1) {
135
+ this.r = s, this.g = r, this.b = t, this.a = n;
136
+ }
137
+ static from(s, r) {
138
+ if (s === "hex") {
139
+ let [t, n, a, b] = x(r);
140
+ return new e(t, n, a, b);
141
+ }
142
+ if (s === "rgb") {
143
+ if (Array.isArray(r)) {
144
+ let [o, y, c, u] = r;
145
+ return new e(o, y, c, u);
146
+ }
147
+ let { r: t, g: n, b: a, a: b } = r;
148
+ return new e(t, n, a, b);
149
+ }
150
+ if (s === "hsl") {
151
+ let t, n, a, b;
152
+ if (Array.isArray(r))
153
+ [t, n, a, b] = r;
154
+ else
155
+ ({ h: t, s: n, l: a, a: b } = r);
156
+ let [o, y, c] = R(t, n, a);
157
+ return new e(o, y, c, b);
158
+ }
159
+ if (s === "hsv") {
160
+ let t, n, a, b;
161
+ if (Array.isArray(r))
162
+ [t, n, a, b] = r;
163
+ else
164
+ ({ h: t, s: n, v: a, a: b } = r);
165
+ let [o, y, c] = H(t, n, a);
166
+ return new e(o, y, c, b);
167
+ }
168
+ if (s === "cmyk") {
169
+ let t, n, a, b, o;
170
+ if (Array.isArray(r))
171
+ [t, n, a, b, o] = r;
172
+ else
173
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
174
+ let [y, c, u] = v(t, n, a, b);
175
+ return new e(y, c, u, o);
176
+ }
177
+ if (s === "oklch") {
178
+ let t, n, a, b;
179
+ if (Array.isArray(r))
180
+ [t, n, a, b] = r;
181
+ else
182
+ ({ l: t, c: n, h: a, a: b } = r);
183
+ let [o, y, c] = C(t, n, a);
184
+ return new e(o, y, c, b);
185
+ }
186
+ if (s === "oklab") {
187
+ let t, n, a, b;
188
+ if (Array.isArray(r))
189
+ [t, n, a, b] = r;
190
+ else
191
+ ({ l: t, a: n, b: a, alpha: b } = r);
192
+ let [o, y, c] = M(t, n, a);
193
+ return new e(o, y, c, b);
194
+ }
195
+ throw Error("Invalid input");
196
+ }
197
+ to(s) {
198
+ switch (s) {
199
+ case "rgb":
200
+ return [this.r, this.g, this.b];
201
+ case "rgba":
202
+ return [this.r, this.g, this.b, this.a];
203
+ case "hex":
204
+ return A([this.r, this.g, this.b]);
205
+ case "hexa":
206
+ return A([this.r, this.g, this.b, this.a]);
207
+ case "hsl":
208
+ return k([this.r, this.g, this.b]);
209
+ case "hsla":
210
+ return [...k([this.r, this.g, this.b]), this.a];
211
+ case "hsv":
212
+ return f([this.r, this.g, this.b]);
213
+ case "hsva":
214
+ return [...f([this.r, this.g, this.b]), this.a];
215
+ case "cmyk":
216
+ return O([this.r, this.g, this.b]);
217
+ case "cmyka":
218
+ return [...O([this.r, this.g, this.b]), this.a];
219
+ case "oklch":
220
+ return d([this.r, this.g, this.b]);
221
+ case "oklcha":
222
+ return [...d([this.r, this.g, this.b]), this.a];
223
+ case "oklab":
224
+ return T([this.r, this.g, this.b]);
225
+ case "oklaba":
226
+ return [...T([this.r, this.g, this.b]), this.a];
227
+ default:
228
+ return [this.r, this.g, this.b];
229
+ }
230
+ }
231
+ getLuminance() {
232
+ let s = l(this.r), r = l(this.g), t = l(this.b);
233
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
234
+ }
235
+ contrastRatio(s) {
236
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
237
+ return (n + 0.05) / (a + 0.05);
238
+ }
239
+ bestContrastForeground() {
240
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
241
+ return t >= n ? s : r;
242
+ }
243
+ }
244
+
245
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
246
+ var r = 39;
247
+ var o = 49;
248
+ var f2 = "\x1B[";
249
+ var C2 = { 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, r], red: [31, r], green: [32, r], yellow: [33, r], blue: [34, r], magenta: [35, r], cyan: [36, r], white: [37, r], gray: [90, r], grey: [90, r], blackBright: [90, r], redBright: [91, r], greenBright: [92, r], yellowBright: [93, r], blueBright: [94, r], magentaBright: [95, r], cyanBright: [96, r], whiteBright: [97, r], bgBlack: [40, o], bgRed: [41, o], bgGreen: [42, o], bgYellow: [43, o], bgBlue: [44, o], bgMagenta: [45, o], bgCyan: [46, o], bgWhite: [47, o], bgBlackBright: [100, o], bgRedBright: [101, o], bgGreenBright: [102, o], bgYellowBright: [103, o], bgBlueBright: [104, o], bgMagentaBright: [105, o], bgCyanBright: [106, o], bgWhiteBright: [107, o], rgb: (i, n, a, l = "fg") => [`${l === "fg" ? 38 : 48};2;${i};${n};${a}`, l === "fg" ? r : o], hex: (i, n = "fg") => {
250
+ let [a, l, s] = e.from("hex", i).to("rgb");
251
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
252
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
253
+ var b = new Set(["", "1", "2", "3", "true"]);
254
+ function h(i, n = globalThis.process?.env ?? {}) {
255
+ if (n.FORCE_COLOR !== undefined)
256
+ return b.has(n.FORCE_COLOR);
257
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
258
+ return false;
259
+ return i?.isTTY === true;
260
+ }
261
+ function d2(i, n, a) {
262
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
263
+ return n;
264
+ let l = "", s = "";
265
+ for (let g = 0, y = i.length;g < y; g++) {
266
+ let [c, p] = i[g];
267
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
268
+ }
269
+ return l + n + s;
270
+ }
271
+ function u(i, n = []) {
272
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
273
+ let g = C2[s];
274
+ if (Array.isArray(g))
275
+ return u(i, [...n, g]);
276
+ if (typeof g === "function")
277
+ return (...y) => u(i, [...n, g(...y)]);
278
+ throw Error(`Unknown style: ${String(s)}`);
279
+ } });
280
+ }
281
+ function le(i = {}) {
282
+ return u(i);
283
+ }
284
+ var t = le();
285
+
286
+ // ../kit/src/style.ts
287
+ var MARKS = {
288
+ ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
289
+ warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
290
+ problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
291
+ note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
292
+ };
293
+ function takesControlCodes(stream, env = process2.env) {
294
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
295
+ }
296
+ function paint(stream, env = process2.env) {
297
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
298
+ }
299
+ function marked(mark, text, stream, detail, env = process2.env) {
300
+ const colors = paint(stream, env);
301
+ const { symbol, word, paint: tint } = MARKS[mark];
302
+ const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
303
+ return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
304
+ }
305
+ function ok(text, detail) {
306
+ console.log(marked("ok", text, process2.stdout, detail));
307
+ }
308
+ function note(text, detail) {
309
+ console.log(marked("note", text, process2.stdout, detail));
310
+ }
311
+ function problem(text, detail) {
312
+ console.error(marked("problem", text, process2.stderr, detail));
313
+ }
314
+ var ROLES = {
315
+ accent: (colors) => colors.cyan,
316
+ id: (colors) => colors.yellow,
317
+ path: (colors) => colors.blue,
318
+ label: (colors) => colors.dim,
319
+ value: (colors) => colors.bold
320
+ };
321
+ function role(name, stream, env = process2.env) {
322
+ return ROLES[name](paint(stream, env));
323
+ }
324
+ var STATUSES = {
325
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
326
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
327
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
328
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
329
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
330
+ };
331
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
332
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-hrsswv1w.js
333
+ function $e(t, e = false, i = 1) {
334
+ let n = typeof e === "object" ? e : { units: e ? "si" : "iec", dp: i }, { units: s = "iec", dp: u = 1 } = n, r = s === "si" ? 1000 : 1024;
335
+ if (Math.abs(t) < r)
336
+ return `${t} B`;
337
+ let c = s === "iec" ? ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] : ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], o = -1, l = 10 ** u;
338
+ do
339
+ t /= r, ++o;
340
+ while (Math.round(Math.abs(t) * l) / l >= r && o < c.length - 1);
341
+ return `${t.toFixed(u)} ${c[o]}`;
342
+ }
343
+
344
+ // ../kit/src/format.ts
345
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
346
+ function formatSeconds(total) {
347
+ let rest = Math.max(0, Math.round(total));
348
+ const amounts = UNITS.map(([unit, size]) => {
349
+ const amount = Math.floor(rest / size);
350
+ rest -= amount * size;
351
+ return `${amount}${unit}`;
352
+ });
353
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
354
+ if (first === -1)
355
+ return "0s";
356
+ const next = amounts[first + 1];
357
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
358
+ }
359
+ function formatDuration(ms) {
360
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
361
+ }
362
+ function upTo(text, separator) {
363
+ const end = text.indexOf(separator);
364
+ return end === -1 ? text : text.slice(0, end);
365
+ }
366
+ function formatAge(date, now = Date.now()) {
367
+ const at = typeof date === "number" ? date : Date.parse(date);
368
+ if (Number.isNaN(at))
369
+ return "-";
370
+ const seconds = (now - at) / 1000;
371
+ return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
372
+ }
373
+ function truncate(text, width) {
374
+ return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
375
+ }
376
+ var LINE_BREAKS = /\s*\n\s*/g;
377
+ var ESCAPE = String.fromCharCode(27);
378
+ function textWidth(text) {
379
+ return Bun.stringWidth(text);
380
+ }
381
+ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
382
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
383
+ const widths = [];
384
+ for (const row of cells) {
385
+ for (const [index, cell] of row.entries())
386
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
387
+ }
388
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
389
+ const colors = paint(process3.stdout);
390
+ const lines = shown.map((row) => row.map((cell, index) => {
391
+ const width = widths[index] ?? 0;
392
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
393
+ if (align[index] === "right")
394
+ return `${gap}${cell}`;
395
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
396
+ }).join(" ").trimEnd());
397
+ return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
398
+ `);
399
+ }
400
+ function narrow(rows, widths, limit) {
401
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
402
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
403
+ const floor = 8;
404
+ while (used() > limit) {
405
+ let widest = -1;
406
+ for (const [index, width] of widths.entries()) {
407
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
408
+ widest = index;
409
+ }
410
+ if (widest === -1)
411
+ break;
412
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
413
+ }
414
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
415
+ }
416
+ function printJson(value) {
417
+ console.log(JSON.stringify(value, undefined, 2));
418
+ }
419
+
420
+ // ../kit/src/help.ts
421
+ import process4 from "process";
422
+ var OPTIONAL = /\[[^\]]+\]/g;
423
+ var USAGE_PREFIX = /^usage:\s*/i;
424
+ var FULL_STOP = /\.$/;
425
+ function usageLine(usage, colors = paint(process4.stdout)) {
426
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
427
+ }
428
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
429
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
430
+ `);
431
+ }
432
+ function exitRows(exits, colors = paint(process4.stdout)) {
433
+ if (exits.length === 0)
434
+ return [];
435
+ const width = Math.max(...exits.map(([code]) => String(code).length));
436
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
437
+ }
438
+ function replacesRows(replaces, colors = paint(process4.stdout)) {
439
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
440
+ }
441
+ function wantsHelpJson(env = process4.env) {
442
+ return env.KIT_HELP === "json";
443
+ }
444
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
445
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
446
+ `);
447
+ const first = lines[0];
448
+ const colon = first.indexOf(": ");
449
+ const prose = lines[lines.indexOf("") + 1] ?? "";
450
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
451
+ return {
452
+ synopsis: colon === -1 ? first : first.slice(0, colon),
453
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
454
+ ...replaces === undefined ? {} : { replaces },
455
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
456
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
457
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
458
+ };
459
+ }
460
+ function exampleRows(examples, colors = paint(process4.stdout)) {
461
+ if (examples.length === 0)
462
+ return [];
463
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
464
+ }
465
+ function optionRows(options, colors = paint(process4.stdout)) {
466
+ const rows = Object.entries(options).map(([name, option]) => {
467
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
468
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
469
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
470
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
471
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
472
+ });
473
+ const width = Math.max(0, ...rows.map((row) => row.width));
474
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
475
+ }
476
+
477
+ // ../kit/src/text.ts
478
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
479
+ function distance(a, b) {
480
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
481
+ for (const [i, left] of [...a].entries()) {
482
+ const current = [i + 1];
483
+ for (const [j, right] of [...b].entries())
484
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
485
+ previous = current;
486
+ }
487
+ return previous[b.length] ?? 0;
488
+ }
489
+ function closest(name, names) {
490
+ const started = names.find((known) => known.startsWith(name));
491
+ if (started !== undefined)
492
+ return started;
493
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
494
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
495
+ }
496
+ // ../kit/src/input.ts
497
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
498
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
499
+ function duration(value, name, fallback, unit = "s") {
500
+ if (value === undefined)
501
+ return fallback;
502
+ const match = DURATION.exec(value.trim());
503
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
504
+ if (ms < 1)
505
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
506
+ return ms;
507
+ }
508
+
509
+ // ../kit/src/args.ts
510
+ var DASHES = /^-+/;
511
+ function jsonOption(holds) {
512
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
513
+ }
514
+
515
+ class Exit extends Error {
516
+ code;
517
+ hint;
518
+ constructor(message, code, hint) {
519
+ super(message);
520
+ this.code = code;
521
+ this.hint = hint;
522
+ }
523
+ }
524
+ function fail(message, code = 2, hint) {
525
+ throw new Exit(message, code, hint);
526
+ }
527
+
528
+ class UsageError extends Exit {
529
+ constructor(message, hint) {
530
+ super(message, 2, hint);
531
+ }
532
+ }
533
+ function badUsage(message) {
534
+ throw new UsageError(message);
535
+ }
536
+
537
+ class HelpShown extends Exit {
538
+ constructor() {
539
+ super("help shown", 0);
540
+ }
541
+ }
542
+
543
+ class Completing {
544
+ options;
545
+ positionals;
546
+ candidates;
547
+ constructor(options, positionals = [], candidates = {}) {
548
+ this.options = options;
549
+ this.positionals = positionals;
550
+ this.candidates = candidates;
551
+ }
552
+ }
553
+ var completion = { active: false };
554
+ var OUTPUT_OPTIONS = {
555
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
556
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
557
+ };
558
+ function applyOutput(color, plain, env = process5.env) {
559
+ const when = plain === true ? "never" : color ?? "auto";
560
+ if (when === "auto")
561
+ return;
562
+ if (when !== "always" && when !== "never")
563
+ badUsage(`--color takes auto, always or never, not ${when}`);
564
+ if (when === "always") {
565
+ env.FORCE_COLOR = "1";
566
+ delete env.NO_COLOR;
567
+ } else {
568
+ env.NO_COLOR = "1";
569
+ delete env.FORCE_COLOR;
570
+ }
571
+ }
572
+ function parse(args, usage, options, settings = {}) {
573
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
574
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
575
+ const listing = listed(all, settings.allowNegative === true);
576
+ if (completion.active)
577
+ throw new Completing(listing, settings.positionals, settings.candidates);
578
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
579
+ let parsed;
580
+ try {
581
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
582
+ } catch (error) {
583
+ const message = parseError(error);
584
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
585
+ }
586
+ const values = parsed.values;
587
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
588
+ if (values.help === true) {
589
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
590
+ throw new HelpShown;
591
+ }
592
+ checkChoices(parsed.values, all);
593
+ checkConflicts(parsed.values, all);
594
+ if (settings.positionals !== undefined)
595
+ checkPositionals(parsed.positionals, settings.positionals);
596
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
597
+ }
598
+ function splitRest(args, passes) {
599
+ const separator = passes ? args.indexOf("--") : -1;
600
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
601
+ }
602
+ function splitTrailing(args, options, count) {
603
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
604
+ let seen = 0;
605
+ if (count === 0)
606
+ return { own: args, rest: undefined };
607
+ for (let at = 0;at < args.length; at++) {
608
+ const word = args[at];
609
+ if (word === "--")
610
+ break;
611
+ if (word.startsWith("-")) {
612
+ if (takesValue(word))
613
+ at++;
614
+ continue;
615
+ }
616
+ seen++;
617
+ if (seen === count)
618
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
619
+ }
620
+ return { own: args, rest: undefined };
621
+ }
622
+ function listed(options, allowNegative) {
623
+ if (!allowNegative)
624
+ return options;
625
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
626
+ if (option.type !== "boolean" || option.negative === undefined)
627
+ return [[name, option]];
628
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
629
+ }));
630
+ }
631
+ function withAliases(args, options) {
632
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
633
+ if (named.size === 0)
634
+ return args;
635
+ const separator = args.indexOf("--");
636
+ const own = separator === -1 ? args : args.slice(0, separator);
637
+ return [...own.map((arg) => {
638
+ const at = arg.indexOf("=");
639
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
640
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
641
+ }), ...separator === -1 ? [] : args.slice(separator)];
642
+ }
643
+ function withBare(args, options) {
644
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
645
+ if (bare.size === 0)
646
+ return args;
647
+ const separator = args.indexOf("--");
648
+ const own = separator === -1 ? args : args.slice(0, separator);
649
+ return [...own.flatMap((arg, index) => {
650
+ const optional = bare.get(arg);
651
+ const next = own[index + 1];
652
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
653
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
654
+ }), ...separator === -1 ? [] : args.slice(separator)];
655
+ }
656
+ function checkConflicts(values, options) {
657
+ const given = (name) => values[name] !== undefined && values[name] !== false;
658
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
659
+ const other = given(name) ? conflicts.find(given) : undefined;
660
+ if (other !== undefined)
661
+ badUsage(`--${name} cannot be used with --${other}`);
662
+ }
663
+ }
664
+ function checkChoices(values, options) {
665
+ for (const [name, option] of Object.entries(options)) {
666
+ if (option.choices === undefined)
667
+ continue;
668
+ const given = values[name];
669
+ for (const value of Array.isArray(given) ? given : [given]) {
670
+ if (typeof value === "string")
671
+ oneOf(value, name, option.choices);
672
+ }
673
+ }
674
+ }
675
+ function oneOf(value, name, choices) {
676
+ if (!choices.includes(value))
677
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
678
+ return value;
679
+ }
680
+ function checkPositionals(given, names) {
681
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
682
+ const required = names.filter((name) => !name.startsWith("[")).length;
683
+ if (given.length < required)
684
+ badUsage(`missing ${names[given.length]}`);
685
+ if (!variadic && given.length > names.length)
686
+ badUsage(`unexpected argument ${given[names.length]}`);
687
+ }
688
+ function joinDashValues(args, options) {
689
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
690
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
691
+ const joined = [];
692
+ for (let i = 0;i < args.length; i++) {
693
+ const arg = args[i] ?? "";
694
+ if (arg === "--")
695
+ return [...joined, ...args.slice(i)];
696
+ const name = longOf.get(arg);
697
+ const next = args[i + 1];
698
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
699
+ joined.push(`--${name}=${next}`);
700
+ i++;
701
+ } else {
702
+ joined.push(arg);
703
+ }
704
+ }
705
+ return joined;
706
+ }
707
+ function parseError(error) {
708
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
709
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
710
+ }
711
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
712
+ function nearestOption(message, options, allowNegative) {
713
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
714
+ if (typed === undefined)
715
+ return;
716
+ const word = typed.replace(DASHES, "");
717
+ if (word.length < 2 && !typed.startsWith("--"))
718
+ return;
719
+ const known = Object.entries(options).flatMap(([name, option]) => [
720
+ ...option.short === undefined ? [] : [`-${option.short}`],
721
+ `--${name}`,
722
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
723
+ ]);
724
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
725
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
726
+ }
727
+ // ../kit/src/process.ts
728
+ import { constants } from "os";
729
+ import process6 from "process";
730
+ var KILL_GRACE_MS = 2000;
731
+ function exitCodeOf(code, signal) {
732
+ if (code !== null)
733
+ return code;
734
+ if (typeof signal === "number")
735
+ return 128 + signal;
736
+ return signal === null ? 129 : 128 + constants.signals[signal];
737
+ }
738
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
739
+ const chunks = [];
740
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
741
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
742
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
743
+ const timers = [];
744
+ const killGroup = (killing) => {
745
+ if (state.done)
746
+ return;
747
+ try {
748
+ if (grouped)
749
+ process6.kill(-proc.pid, killing);
750
+ else
751
+ proc.kill(killing);
752
+ } catch {}
753
+ };
754
+ const stop = () => {
755
+ killGroup("SIGTERM");
756
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
757
+ };
758
+ const onAbort = () => stop();
759
+ if (timeoutMs !== undefined) {
760
+ timers.push(setTimeout(() => {
761
+ state.timedOut = true;
762
+ stop();
763
+ }, timeoutMs));
764
+ }
765
+ if (signal?.aborted === true)
766
+ onAbort();
767
+ else
768
+ signal?.addEventListener("abort", onAbort, { once: true });
769
+ onStart?.({ kill: (killing) => killGroup(killing) });
770
+ const drain = async (stream, name) => {
771
+ for await (const data of stream) {
772
+ if (state.failure !== undefined)
773
+ continue;
774
+ try {
775
+ onChunk?.({ stream: name, data });
776
+ } catch (error) {
777
+ state.failure = error;
778
+ stop();
779
+ continue;
780
+ }
781
+ if (state.kept + data.length > maxBytes) {
782
+ state.truncated = true;
783
+ continue;
784
+ }
785
+ state.kept += data.length;
786
+ chunks.push({ stream: name, data });
787
+ }
788
+ };
789
+ try {
790
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
791
+ await proc.exited;
792
+ } finally {
793
+ state.done = true;
794
+ for (const timer of timers)
795
+ clearTimeout(timer);
796
+ signal?.removeEventListener("abort", onAbort);
797
+ }
798
+ if (state.failure !== undefined)
799
+ throw state.failure;
800
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
801
+ let output;
802
+ let text;
803
+ return {
804
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
805
+ chunks,
806
+ timedOut: state.timedOut,
807
+ truncated: state.truncated,
808
+ get output() {
809
+ return output ??= joined();
810
+ },
811
+ get text() {
812
+ return text ??= (output ??= joined()).toString();
813
+ }
814
+ };
815
+ }
816
+
817
+ // ../kit/src/progress.ts
818
+ var ESC = String.fromCharCode(27);
819
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
820
+ var RESET_STYLE = `${ESC}[0m`;
821
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
822
+
823
+ // ../kit/src/tool.ts
824
+ import process7 from "process";
825
+ function cwdGone() {
826
+ try {
827
+ process7.cwd();
828
+ return false;
829
+ } catch {
830
+ return true;
831
+ }
832
+ }
833
+
834
+ class SpawnError extends Error {
835
+ missing;
836
+ constructor(message, missing) {
837
+ super(message);
838
+ this.missing = missing;
839
+ }
840
+ }
841
+ function spawnFailure(command, error) {
842
+ const gone = cwdGone();
843
+ const missing = !gone && error?.code === "ENOENT";
844
+ return new SpawnError(`${command}: ${error instanceof Error ? error.message : String(error)}${gone ? " (the working directory was removed)" : ""}`, missing);
845
+ }
846
+ async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
847
+ let ran;
848
+ try {
849
+ ran = await runCommand(argv, { env: process7.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
850
+ } catch (error) {
851
+ throw spawnFailure(label, error);
852
+ }
853
+ if (ran.timedOut)
854
+ throw new Error(`${label}: no answer in ${formatDuration(timeoutMs ?? 0)}`);
855
+ const decoders = { stdout: new TextDecoder, stderr: new TextDecoder };
856
+ const streams = { stdout: "", stderr: "" };
857
+ for (const { stream, data } of ran.chunks)
858
+ streams[stream] += decoders[stream].decode(data, { stream: true });
859
+ streams.stdout += decoders.stdout.decode();
860
+ streams.stderr += decoders.stderr.decode();
861
+ return { code: ran.code, ...streams };
862
+ }
863
+ // ../kit/src/cli.ts
864
+ import { readFileSync, realpathSync } from "fs";
865
+ import { dirname as dirname2, join as join2 } from "path";
866
+ import process9 from "process";
867
+
868
+ // ../kit/src/usage.ts
869
+ import { appendFileSync, mkdirSync } from "fs";
870
+ import { homedir } from "os";
871
+ import { dirname, isAbsolute, join } from "path";
872
+ import process8 from "process";
873
+
874
+ // ../kit/src/logs.ts
875
+ var DAY_MS = 24 * 60 * 60 * 1000;
876
+ var CLI_FOLDER = "kaynooo-cli";
877
+
878
+ // ../kit/src/usage.ts
879
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
880
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
881
+ var LONGEST_NAME = 40;
882
+ var usageError;
883
+ function noteUsageError(message) {
884
+ usageError = message;
885
+ }
886
+ function stateHome(env = process8.env) {
887
+ const dir = env.XDG_STATE_HOME;
888
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
889
+ }
890
+ function usagePath(env = process8.env) {
891
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
892
+ }
893
+ function usageRecorded(env = process8.env) {
894
+ const off = env.KAYNOOO_CLI_NO_USAGE;
895
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
896
+ }
897
+ function flagNames(argv) {
898
+ const end = argv.indexOf("--");
899
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
900
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
901
+ }
902
+ function usageEntry(bin, command, argv, code, now = new Date) {
903
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
904
+ usageError = undefined;
905
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
906
+ }
907
+ function recordUsage(entry, env = process8.env) {
908
+ if (!usageRecorded(env))
909
+ return;
910
+ try {
911
+ const path = usagePath(env);
912
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
913
+ appendFileSync(path, `${JSON.stringify(entry)}
914
+ `, { mode: 384 });
915
+ } catch {}
916
+ }
917
+
918
+ // ../kit/src/cli.ts
919
+ var LEVEL_OPTIONS = {
920
+ ...OUTPUT_OPTIONS,
921
+ help: { type: "boolean", short: "h", description: "show this help" }
922
+ };
923
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
924
+ async function commandRows(all, colors) {
925
+ const commands = shown(all);
926
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
927
+ const groups = new Map([["Commands:", []]]);
928
+ const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
929
+ for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
930
+ const heading = group === undefined ? "Commands:" : `${group}:`;
931
+ const rows = groups.get(heading) ?? [];
932
+ rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
933
+ groups.set(heading, rows);
934
+ }
935
+ return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
936
+ }
937
+ function shown(commands) {
938
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
939
+ }
940
+ function takeOutputFlags(argv) {
941
+ let index = 0;
942
+ for (;index < argv.length; index++) {
943
+ const word = argv[index];
944
+ if (word === "--plain")
945
+ applyOutput(undefined, true);
946
+ else if (word.startsWith("--color="))
947
+ applyOutput(word.slice("--color=".length), undefined);
948
+ else if (word === "--color" && argv[index + 1] !== undefined)
949
+ applyOutput(argv[++index], undefined);
950
+ else
951
+ break;
952
+ }
953
+ return argv.slice(index);
954
+ }
955
+ async function resolveSummary(summary) {
956
+ return typeof summary === "string" ? summary : summary();
957
+ }
958
+ function scopeOf(commands, extra, aliases) {
959
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
960
+ }
961
+ async function expand(scope, words) {
962
+ if (scope.lazy.length === 0)
963
+ return scope;
964
+ const commands = { ...scope.commands };
965
+ for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
966
+ for (const [name, command] of Object.entries(added))
967
+ commands[name] ??= command;
968
+ }
969
+ return { ...scope, commands, lazy: [] };
970
+ }
971
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
972
+ const colors = paint(stream);
973
+ const prefix = path.join(" ");
974
+ const summary = await resolveSummary(lazySummary);
975
+ if (wantsHelpJson())
976
+ return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
977
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
978
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
979
+ const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
980
+ return [
981
+ header(colors, summary),
982
+ "",
983
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
984
+ ...replacesRows(replaces, colors),
985
+ "",
986
+ ...await commandRows(commands, colors),
987
+ ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
988
+ "",
989
+ colors.bold("Options:"),
990
+ ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
991
+ ...exampleRows(examples ?? [], colors),
992
+ "",
993
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
994
+ ].join(`
995
+ `);
996
+ }
997
+ function printError(prefix, message, hint, cause) {
998
+ const colors = paint(process9.stderr);
999
+ const styled = takesControlCodes(process9.stderr);
1000
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1001
+ const under = (label, text, tint) => text === undefined ? "" : `
1002
+ ${styled ? tint(label) : `${label}:`} ${text}`;
1003
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1004
+ }
1005
+ function printJsonError(message, hint, cause) {
1006
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1007
+ }
1008
+ function wantsJson(argv) {
1009
+ const end = argv.indexOf("--");
1010
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1011
+ }
1012
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
1013
+ if (error instanceof HelpShown)
1014
+ return 0;
1015
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1016
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1017
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1018
+ if (error instanceof Exit && error.code === 2)
1019
+ noteUsageError(error.message);
1020
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1021
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1022
+ return error instanceof Exit ? error.code : 1;
1023
+ }
1024
+ async function dispatch(level, typed, { version, redact }) {
1025
+ const prefix = level.path.join(" ");
1026
+ let argv;
1027
+ try {
1028
+ argv = takeOutputFlags(typed);
1029
+ } catch (error) {
1030
+ return reportThrown(prefix, error);
1031
+ }
1032
+ const [name, ...args] = argv;
1033
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
1034
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
1035
+ try {
1036
+ return await fallback.run([]);
1037
+ } catch (error) {
1038
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
1039
+ }
1040
+ }
1041
+ if (name === undefined && level.path.length > 1) {
1042
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
1043
+ return 2;
1044
+ }
1045
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1046
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
1047
+ return 0;
1048
+ }
1049
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
1050
+ console.log(version);
1051
+ return 0;
1052
+ }
1053
+ let command = level.commands[level.aliases?.[name] ?? name];
1054
+ let rest = args;
1055
+ let ran = name;
1056
+ if (command === undefined && level.lazy.length > 0) {
1057
+ level = await expand(level, [...level.path.slice(1), ...argv]);
1058
+ command = level.commands[level.aliases?.[name] ?? name];
1059
+ }
1060
+ if (command === undefined && level.defaultCommand !== undefined) {
1061
+ command = level.commands[level.defaultCommand];
1062
+ rest = argv;
1063
+ ran = level.defaultCommand;
1064
+ }
1065
+ if (command === undefined) {
1066
+ const meant = closest(name, Object.keys(shown(level.commands)));
1067
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
1068
+ return 2;
1069
+ }
1070
+ if ("commands" in command) {
1071
+ const { summary } = command;
1072
+ return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
1073
+ }
1074
+ try {
1075
+ return await command.run(rest);
1076
+ } catch (error) {
1077
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
1078
+ }
1079
+ }
1080
+ var COMPLETE = "__complete";
1081
+ var FILES = "__files__";
1082
+ async function completingOf(run) {
1083
+ completion.active = true;
1084
+ try {
1085
+ await run([]);
1086
+ } catch (error) {
1087
+ if (error instanceof Completing)
1088
+ return error;
1089
+ } finally {
1090
+ completion.active = false;
1091
+ }
1092
+ return new Completing({});
1093
+ }
1094
+ async function optionsOf(run) {
1095
+ return (await completingOf(run)).options;
1096
+ }
1097
+ function candidateLine(candidate) {
1098
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
1099
+ }
1100
+ function positionalBeingTyped(before, { options, positionals }) {
1101
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1102
+ let index = 0;
1103
+ let at = 0;
1104
+ while (at < before.length) {
1105
+ const word = before[at];
1106
+ if (word === "--") {
1107
+ index += before.length - at - 1;
1108
+ break;
1109
+ }
1110
+ if (!word.startsWith("-"))
1111
+ index++;
1112
+ else if (takesValue(word))
1113
+ at++;
1114
+ at++;
1115
+ }
1116
+ const last = positionals.at(-1);
1117
+ if (index < positionals.length)
1118
+ return positionals[index];
1119
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1120
+ }
1121
+ async function leafCandidates(run, words) {
1122
+ const completing = await completingOf(run);
1123
+ if ((words.at(-1) ?? "").startsWith("-"))
1124
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1125
+ const flag = words.at(-2);
1126
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1127
+ if (option?.type === "string") {
1128
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1129
+ return values === undefined ? [FILES] : values.map(candidateLine);
1130
+ }
1131
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
1132
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
1133
+ return values === undefined ? [FILES] : values.map(candidateLine);
1134
+ }
1135
+ async function candidates(scope, defaultCommand, words, before = []) {
1136
+ const [word = "", ...rest] = words;
1137
+ const listing = rest.length === 0 && !word.startsWith("-");
1138
+ let { commands, aliases } = scope;
1139
+ let command = commands[aliases?.[word] ?? word];
1140
+ if (listing || command === undefined) {
1141
+ ({ commands, aliases } = await expand(scope, [...before, ...words]));
1142
+ command = commands[aliases?.[word] ?? word];
1143
+ }
1144
+ if (listing) {
1145
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1146
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1147
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1148
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1149
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
1150
+ }
1151
+ if (command === undefined) {
1152
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1153
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
1154
+ }
1155
+ return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1156
+ }
1157
+ async function printCandidates(found) {
1158
+ for (const line of await found)
1159
+ console.log(line);
1160
+ return 0;
1161
+ }
1162
+ function packageVersion(entry = Bun.main) {
1163
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1164
+ try {
1165
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
1166
+ if (typeof version === "string")
1167
+ return version;
1168
+ } catch {}
1169
+ if (dirname2(dir) === dir)
1170
+ return "0.0.0";
1171
+ }
1172
+ }
1173
+ async function runCli(cli, argv = process9.argv.slice(2)) {
1174
+ const version = cli.version ?? packageVersion();
1175
+ if (argv[0] === COMPLETE)
1176
+ return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1177
+ 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 });
1178
+ if (cli.usage !== false) {
1179
+ try {
1180
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1181
+ } catch {}
1182
+ }
1183
+ return code;
1184
+ }
1185
+ function commandPath(scope, argv) {
1186
+ const path = [];
1187
+ let level = scope;
1188
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
1189
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1190
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1191
+ if (command === undefined)
1192
+ break;
1193
+ path.push(word);
1194
+ if (!("commands" in command))
1195
+ break;
1196
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
1197
+ }
1198
+ return path.length === 0 ? undefined : path.join(" ");
1199
+ }
1200
+ async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
1201
+ if (argv[0] === COMPLETE)
1202
+ return printCandidates(leafCandidates(run, argv.slice(1)));
1203
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1204
+ console.log(version ?? packageVersion());
1205
+ return 0;
1206
+ }
1207
+ let code;
1208
+ try {
1209
+ code = await run(argv);
1210
+ } catch (error) {
1211
+ code = reportThrown(name, error, redact, wantsJson(argv));
1212
+ }
1213
+ if (usage !== false) {
1214
+ try {
1215
+ recordUsage(usageEntry(name, undefined, argv, code));
1216
+ } catch {}
1217
+ }
1218
+ return code;
1219
+ }
1220
+ // ../kit/src/secrets.ts
1221
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1222
+ // ../kit/src/sessions.ts
1223
+ var {Glob } = globalThis.Bun;
1224
+ var SESSION_FILES = new Glob("*.json");
1225
+ var ACCOUNT_DIRS = new Glob("*/sessions");
1226
+ // ../kit/src/size.ts
1227
+ var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
1228
+ var POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
1229
+ function parseSize(text, bareUnit = 1) {
1230
+ const match = SIZE.exec(text.trim());
1231
+ if (match === null)
1232
+ return;
1233
+ const suffix = match[2].toLowerCase();
1234
+ return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1235
+ }
1236
+ // ../kit/src/user-config.ts
1237
+ import { existsSync } from "fs";
1238
+ import { homedir as homedir2 } from "os";
1239
+ import { join as join3 } from "path";
1240
+ import process10 from "process";
1241
+ function configBase(where = {}) {
1242
+ const xdg = where.xdg ?? (where.home === undefined ? process10.env.XDG_CONFIG_HOME : undefined);
1243
+ return xdg !== undefined && xdg !== "" ? xdg : join3(where.home ?? homedir2(), ".config");
1244
+ }
1245
+ function userConfigPath(bin, where = {}) {
1246
+ return join3(configBase(where), "kaynooo-cli", `${bin}.json`);
1247
+ }
1248
+ function userConfigReadPath(bin, legacy = [], where = {}) {
1249
+ const current = userConfigPath(bin, where);
1250
+ if (existsSync(current))
1251
+ return current;
1252
+ const base = configBase(where);
1253
+ return legacy.map((parts) => join3(base, ...parts)).find((path) => existsSync(path)) ?? current;
1254
+ }
1255
+ // src/audit.ts
1256
+ import { existsSync as existsSync3, readdirSync, statSync } from "fs";
1257
+ import { readdir } from "fs/promises";
1258
+ import { join as join5, relative, resolve } from "path";
1259
+ import process12 from "process";
1260
+
1261
+ // src/report.ts
1262
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
1263
+ import { join as join4 } from "path";
1264
+ var UPPER_BOUND = /<\s*(\d[\w.+-]*)/;
1265
+ var DEPENDENCY_KINDS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
1266
+ var GHSA = /GHSA-[\w-]+$/;
1267
+ function parseAudit(text) {
1268
+ try {
1269
+ const parsed = JSON.parse(text);
1270
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : undefined;
1271
+ } catch {
1272
+ return;
1273
+ }
1274
+ }
1275
+ function fixedAt(range) {
1276
+ const bounds = range.split("||").map((part) => UPPER_BOUND.exec(part)?.[1]);
1277
+ if (bounds.length === 0 || bounds.includes(undefined))
1278
+ return;
1279
+ return bounds.reduce((highest, bound) => Bun.semver.order(bound, highest) > 0 ? bound : highest);
1280
+ }
1281
+ function fixFor(advisories) {
1282
+ const fixes = advisories.map((advisory) => fixedAt(advisory.vulnerable_versions));
1283
+ if (fixes.length === 0 || fixes.includes(undefined))
1284
+ return;
1285
+ return fixes.reduce((highest, fix) => Bun.semver.order(fix, highest) > 0 ? fix : highest);
1286
+ }
1287
+ function findingsOf(audit, reaching, direct, level, ignore = []) {
1288
+ const found = [];
1289
+ for (const [name, all] of Object.entries(audit)) {
1290
+ const kept = all.filter((advisory) => severityRank(advisory.severity) >= severityRank(level) && !isIgnored({ id: advisory.id, ghsa: GHSA.exec(advisory.url)?.[0] }, ignore));
1291
+ if (kept.length === 0)
1292
+ continue;
1293
+ const advisories = kept.map((advisory) => ({ id: advisory.id, ghsa: GHSA.exec(advisory.url)?.[0], url: advisory.url, title: advisory.title, severity: advisory.severity, fixed: fixedAt(advisory.vulnerable_versions) }));
1294
+ found.push({
1295
+ package: name,
1296
+ severity: advisories.reduce((worst, advisory) => severityRank(advisory.severity) > severityRank(worst) ? advisory.severity : worst, advisories[0].severity),
1297
+ advisories,
1298
+ scope: reaching.has(name) ? "prod" : "dev",
1299
+ direct: direct.has(name),
1300
+ fix: fixFor(kept)
1301
+ });
1302
+ }
1303
+ return found.toSorted((a, b) => severityRank(b.severity) - severityRank(a.severity) || Number(b.scope === "prod") - Number(a.scope === "prod") || a.package.localeCompare(b.package));
1304
+ }
1305
+ function readManifest(path) {
1306
+ try {
1307
+ return existsSync2(path) ? JSON.parse(readFileSync2(path, "utf8")) : {};
1308
+ } catch {
1309
+ return {};
1310
+ }
1311
+ }
1312
+ function namesIn(manifest) {
1313
+ return DEPENDENCY_KINDS.flatMap((kind) => {
1314
+ const section = manifest[kind];
1315
+ return typeof section === "object" && section !== null ? Object.keys(section) : [];
1316
+ });
1317
+ }
1318
+ function directDependencies(root, workspaces) {
1319
+ const names = new Set(namesIn(readManifest(join4(root, "package.json"))));
1320
+ for (const workspace of workspaces) {
1321
+ for (const name of namesIn(readManifest(join4(root, workspace, "package.json"))))
1322
+ names.add(name);
1323
+ }
1324
+ return names;
1325
+ }
1326
+ function workspacePatterns(field) {
1327
+ if (Array.isArray(field))
1328
+ return field;
1329
+ const packages = typeof field === "object" && field !== null ? field.packages : undefined;
1330
+ return Array.isArray(packages) ? packages : [];
1331
+ }
1332
+ function workspaceFolders(root, children) {
1333
+ const patterns = workspacePatterns(readManifest(join4(root, "package.json")).workspaces);
1334
+ return patterns.filter((pattern) => typeof pattern === "string").flatMap((pattern) => pattern.endsWith("/*") ? children(pattern.slice(0, -2)).map((name) => join4(pattern.slice(0, -2), name)) : [pattern]);
1335
+ }
1336
+
1337
+ // src/audit.ts
1338
+ var USAGE = `audit [options] [root]: the known vulnerabilities of the Bun repositories under root (the current folder by default), one table per repository
1339
+
1340
+ Each package with an advisory is one row: its worst severity, how many advisories, whether a production dependency needs it (prod) or only a development one (dev), whether the repository asks for it itself (direct) or a dependency does (the row then says via), and the version that fixes every advisory at once, "-" when an advisory names none. The worst and the production ones come first.
1341
+ It runs \`bun audit --json\` in each repository holding a bun.lock, which reaches the registry; the walk goes three levels deep, stops at a bun.lock and skips node_modules and hidden folders.
1342
+
1343
+ 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.`;
1344
+ var EXITS = [[0, "no repository has an advisory at the level asked"], [1, "one has"], [2, "a repository's audit failed, no bun.lock sits under root, a usage error or a root that is no folder"]];
1345
+ var OPTIONS = {
1346
+ level: { type: "string", choices: SEVERITIES, default: "moderate", description: "only the advisories at least this severe: low, moderate, high or critical" },
1347
+ prod: { type: "boolean", description: "only the packages a production dependency needs" },
1348
+ ignore: { type: "string", multiple: true, description: "an advisory skipped by GHSA or numeric id, repeatable" },
1349
+ json: jsonOption("[{repo, path, findings: [{package, severity, scope, direct, fix, advisories: [{id, ghsa, url, title, severity, fixed}]}], error}]")
1350
+ };
1351
+ var MAX_DEPTH = 3;
1352
+ var CONCURRENCY = 4;
1353
+ var AUDIT_MS = 60000;
1354
+ function holdsLock(dir) {
1355
+ return existsSync3(join5(dir, "bun.lock")) || existsSync3(join5(dir, "bun.lockb"));
1356
+ }
1357
+ async function findRepos(root) {
1358
+ if (holdsLock(root))
1359
+ return [root];
1360
+ const found = [];
1361
+ async function walk(dir, depth) {
1362
+ let entries;
1363
+ try {
1364
+ entries = await readdir(dir, { withFileTypes: true });
1365
+ } catch {
1366
+ return;
1367
+ }
1368
+ for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
1369
+ if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith("."))
1370
+ continue;
1371
+ const path = join5(dir, entry.name);
1372
+ if (holdsLock(path))
1373
+ found.push(path);
1374
+ else if (depth < MAX_DEPTH)
1375
+ await walk(path, depth + 1);
1376
+ }
1377
+ }
1378
+ await walk(root, 1);
1379
+ return found;
1380
+ }
1381
+ async function pool(items, limit, task) {
1382
+ const results = Array.from({ length: items.length });
1383
+ let next = 0;
1384
+ async function worker() {
1385
+ while (next < items.length) {
1386
+ const index = next++;
1387
+ results[index] = await task(items[index]);
1388
+ }
1389
+ }
1390
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1391
+ return results;
1392
+ }
1393
+ function children(root) {
1394
+ return (folder) => {
1395
+ try {
1396
+ return readdirSync(join5(root, folder), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
1397
+ } catch {
1398
+ return [];
1399
+ }
1400
+ };
1401
+ }
1402
+ async function audited(path, shown, level, ignore) {
1403
+ const [all, production] = await Promise.all([
1404
+ runCommand(["bun", "audit", "--json"], { cwd: path, timeoutMs: AUDIT_MS }),
1405
+ runCommand(["bun", "audit", "--json", "--prod"], { cwd: path, timeoutMs: AUDIT_MS })
1406
+ ]);
1407
+ const audit = parseAudit(stdoutOf(all));
1408
+ const reached = parseAudit(stdoutOf(production));
1409
+ if (audit === undefined || reached === undefined)
1410
+ return { repo: shown, path, findings: [], error: failure(audit === undefined ? all : production) };
1411
+ const reaching = new Set(Object.keys(reached));
1412
+ const direct = directDependencies(path, workspaceFolders(path, children(path)));
1413
+ return { repo: shown, path, findings: findingsOf(audit, reaching, direct, level, ignore), error: undefined };
1414
+ }
1415
+ function stdoutOf(ran) {
1416
+ return Buffer.concat(ran.chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
1417
+ }
1418
+ function failure(ran) {
1419
+ return ran.timedOut ? `timed out after ${AUDIT_MS / 1000}s` : ran.text.trim().split(`
1420
+ `).at(-1) ?? `exit ${ran.code}`;
1421
+ }
1422
+ function tint(severity) {
1423
+ const colors = paint(process12.stdout);
1424
+ if (severity === "critical" || severity === "high")
1425
+ return colors.red;
1426
+ return severity === "moderate" ? colors.yellow : colors.dim;
1427
+ }
1428
+ function rows(findings) {
1429
+ return findings.map((found) => [
1430
+ found.package,
1431
+ tint(found.severity)(found.severity),
1432
+ String(found.advisories.length),
1433
+ found.scope,
1434
+ found.direct ? "direct" : "via",
1435
+ found.fix ?? "-"
1436
+ ]);
1437
+ }
1438
+ async function audit(args) {
1439
+ 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"] });
1440
+ const root = resolve(positionals[0] ?? ".");
1441
+ if (!existsSync3(root) || !statSync(root).isDirectory())
1442
+ fail(`no folder ${root}`);
1443
+ const level = oneOf(values.level, "level", SEVERITIES);
1444
+ const paths = await findRepos(root);
1445
+ if (paths.length === 0)
1446
+ fail(`no bun.lock under ${root}`);
1447
+ const audits = await pool(paths, CONCURRENCY, async (path) => audited(path, relative(root, path) || ".", level, values.ignore ?? []));
1448
+ const kept = audits.map((each) => ({ ...each, findings: values.prod === true ? each.findings.filter((found) => found.scope === "prod") : each.findings }));
1449
+ if (values.json === true)
1450
+ printJson(kept);
1451
+ else
1452
+ show(kept, audits.length);
1453
+ if (kept.some((each) => each.error !== undefined))
1454
+ return 2;
1455
+ return kept.some((each) => each.findings.length > 0) ? 1 : 0;
1456
+ }
1457
+ function show(audits, total) {
1458
+ const label = role("label", process12.stdout);
1459
+ const path = role("path", process12.stdout);
1460
+ const flagged = audits.filter((each) => each.error !== undefined || each.findings.length > 0);
1461
+ if (flagged.length === 0) {
1462
+ console.log(label(`no advisory in ${total} ${total === 1 ? "repository" : "repositories"}`));
1463
+ return;
1464
+ }
1465
+ for (const each of flagged) {
1466
+ console.log(`${path(each.repo)} ${label(each.error === undefined ? `${each.findings.length} ${each.findings.length === 1 ? "package" : "packages"}` : `audit failed: ${each.error}`)}`);
1467
+ if (each.findings.length > 0)
1468
+ console.log(table([["package", "severity", "advisories", "scope", "origin", "fix"], ...rows(each.findings)], { header: true, align: ["left", "left", "right", "left", "left", "left"] }));
1469
+ }
1470
+ }
1471
+
1472
+ // src/repos.ts
1473
+ import { existsSync as existsSync5, statSync as statSync2 } from "fs";
1474
+ import { homedir as homedir3 } from "os";
1475
+ import { join as join7, relative as relative2, resolve as resolve2 } from "path";
1476
+ import process14 from "process";
1477
+
1478
+ // src/repos-scan.ts
1479
+ import { existsSync as existsSync4 } from "fs";
1480
+ import { readdir as readdir2 } from "fs/promises";
1481
+ import { basename, join as join6 } from "path";
1482
+ import process13 from "process";
1483
+ var MAX_DEPTH2 = 3;
1484
+ var CONCURRENCY2 = 8;
1485
+ var GIT_MS = 1e4;
1486
+ var FETCH_MS = 30000;
1487
+ var AHEAD_BEHIND = /\+(\d+) -(\d+)/;
1488
+ var PACKAGE_TAG = /^(.+)-v\d/;
1489
+ var REASONS = ["dirty", "unpushed", "unreleased", "behind"];
1490
+ function reasonsOf(repo) {
1491
+ const reasons = [];
1492
+ if (repo.dirty > 0)
1493
+ reasons.push("dirty");
1494
+ if ((repo.ahead ?? 0) > 0)
1495
+ reasons.push("unpushed");
1496
+ if ((repo.behind ?? 0) > 0)
1497
+ reasons.push("behind");
1498
+ if ((repo.unreleased ?? 0) > 0)
1499
+ reasons.push("unreleased");
1500
+ return reasons;
1501
+ }
1502
+ async function findRepos2(root, skip) {
1503
+ if (existsSync4(join6(root, ".git")))
1504
+ return [root];
1505
+ const found = [];
1506
+ async function walk(dir, depth) {
1507
+ let entries;
1508
+ try {
1509
+ entries = await readdir2(dir, { withFileTypes: true });
1510
+ } catch {
1511
+ return;
1512
+ }
1513
+ for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
1514
+ if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith(".") || skip.has(entry.name))
1515
+ continue;
1516
+ const path = join6(dir, entry.name);
1517
+ if (existsSync4(join6(path, ".git")))
1518
+ found.push(path);
1519
+ else if (depth < MAX_DEPTH2)
1520
+ await walk(path, depth + 1);
1521
+ }
1522
+ }
1523
+ await walk(root, 1);
1524
+ return found;
1525
+ }
1526
+ async function read(path, args, timeoutMs = GIT_MS) {
1527
+ try {
1528
+ const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...process13.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs });
1529
+ return ran.code === 0 && !ran.timedOut ? ran.text.trim() : undefined;
1530
+ } catch {
1531
+ return;
1532
+ }
1533
+ }
1534
+ async function commitsSince(path, tag, folder) {
1535
+ const count = await read(path, ["rev-list", "--count", `${tag}..HEAD`, ...folder === undefined ? [] : ["--", folder]]);
1536
+ return Number(count ?? 0);
1537
+ }
1538
+ async function packageReleases(path) {
1539
+ const names = new Set;
1540
+ for (const tag of (await read(path, ["tag", "--list"]) ?? "").split(`
1541
+ `)) {
1542
+ const name = PACKAGE_TAG.exec(tag)?.[1];
1543
+ if (name !== undefined)
1544
+ names.add(name);
1545
+ }
1546
+ const releases = [];
1547
+ for (const name of [...names].toSorted()) {
1548
+ const folder = [join6("packages", name), name].find((candidate) => existsSync4(join6(path, candidate)));
1549
+ const tag = folder === undefined ? undefined : await read(path, ["describe", "--tags", "--abbrev=0", "--match", `${name}-v*`]);
1550
+ if (folder !== undefined && tag !== undefined && tag !== "")
1551
+ releases.push({ name, tag, unreleased: await commitsSince(path, tag, folder) });
1552
+ }
1553
+ return releases;
1554
+ }
1555
+ async function inspect(path, fetch) {
1556
+ const fetched = fetch ? await read(path, ["fetch", "--quiet"], FETCH_MS) : "";
1557
+ const [status, worktrees, packages] = await Promise.all([
1558
+ read(path, ["status", "--porcelain=v2", "--branch"]),
1559
+ read(path, ["worktree", "list", "--porcelain"]),
1560
+ packageReleases(path)
1561
+ ]);
1562
+ const state = { name: basename(path), path, branch: "?", upstream: null, dirty: 0, ahead: null, behind: null, worktrees: 0, tag: null, unreleased: null, packages, fetchFailed: fetched === undefined, unreadable: status === undefined };
1563
+ for (const line of (status ?? "").split(`
1564
+ `)) {
1565
+ if (line.startsWith("# branch.head "))
1566
+ state.branch = line.slice("# branch.head ".length);
1567
+ else if (line.startsWith("# branch.upstream "))
1568
+ state.upstream = line.slice("# branch.upstream ".length);
1569
+ else if (line.startsWith("# branch.ab "))
1570
+ [state.ahead, state.behind] = AHEAD_BEHIND.exec(line)?.slice(1).map(Number);
1571
+ else if (line !== "" && !line.startsWith("#"))
1572
+ state.dirty++;
1573
+ }
1574
+ state.worktrees = Math.max(0, (worktrees ?? "").split(`
1575
+ `).filter((line) => line.startsWith("worktree ")).length - 1);
1576
+ if (packages.length > 0) {
1577
+ state.unreleased = packages.reduce((sum, release) => sum + release.unreleased, 0);
1578
+ } else {
1579
+ const tag = await read(path, ["describe", "--tags", "--abbrev=0"]);
1580
+ if (tag !== undefined && tag !== "") {
1581
+ state.tag = tag;
1582
+ state.unreleased = await commitsSince(path, tag);
1583
+ }
1584
+ }
1585
+ return state;
1586
+ }
1587
+ function pullBlocker(repo) {
1588
+ if (repo.unreadable)
1589
+ return "unreadable";
1590
+ if (repo.fetchFailed)
1591
+ return "fetch failed";
1592
+ if (repo.branch === "(detached)")
1593
+ return "detached HEAD";
1594
+ if (repo.upstream === null)
1595
+ return "no upstream";
1596
+ if (repo.dirty > 0)
1597
+ return `${repo.dirty} dirty ${repo.dirty === 1 ? "file" : "files"}`;
1598
+ return (repo.ahead ?? 0) > 0 ? `diverged, ${repo.ahead} ahead` : undefined;
1599
+ }
1600
+ function firstLine(text) {
1601
+ const end = text.indexOf(`
1602
+ `);
1603
+ return end === -1 ? text : text.slice(0, end);
1604
+ }
1605
+ async function fastForward(path) {
1606
+ try {
1607
+ const ran = await runCommand(["git", "--no-optional-locks", "merge", "--ff-only", "--quiet", "@{upstream}"], { cwd: path, env: { ...process13.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs: GIT_MS });
1608
+ if (ran.timedOut)
1609
+ return "timed out";
1610
+ return ran.code === 0 ? undefined : firstLine(ran.text.trim()) || `exit ${ran.code}`;
1611
+ } catch (error) {
1612
+ return error instanceof Error ? error.message : String(error);
1613
+ }
1614
+ }
1615
+ async function pool2(items, limit, task) {
1616
+ const results = new Array(items.length);
1617
+ let next = 0;
1618
+ async function worker() {
1619
+ while (next < items.length) {
1620
+ const index = next++;
1621
+ results[index] = await task(items[index]);
1622
+ }
1623
+ }
1624
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1625
+ return results;
1626
+ }
1627
+
1628
+ // src/repos.ts
1629
+ var USAGE2 = `repos [options] [root]: the git repositories under root (~/Workspace by default) that need attention, with their branch, dirty files, ahead/behind their upstream, linked worktrees and commits since their latest tag
1630
+
1631
+ 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.
1632
+
1633
+ Ahead and behind are those of the last fetch unless --fetch refreshes the upstreams first, which reaches the remote.
1634
+ --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.
1635
+ --path prints only the paths of the repositories listed, one per line, for xargs -d '\\n'.`;
1636
+ 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"]];
1637
+ var OPTIONS2 = {
1638
+ all: { type: "boolean", short: "a", description: "list the repositories with nothing to report too" },
1639
+ only: { type: "string", choices: REASONS, description: "only the repositories with this reason: dirty, unpushed, unreleased or behind" },
1640
+ fetch: { type: "boolean", description: "refresh the upstreams first (reaches the remote)" },
1641
+ pull: { type: "boolean", description: "fetch, then fast-forward the clean repositories listed that are only behind their upstream (reaches the remote)" },
1642
+ path: { type: "boolean", conflicts: ["json"], description: "print only the paths of the repositories listed, one per line" },
1643
+ json: jsonOption("[{name, path, branch, upstream, dirty, ahead, behind, worktrees, tag, unreleased, packages, reasons, fetchFailed, unreadable}]")
1644
+ };
1645
+ async function skipped() {
1646
+ const file = userConfigReadPath("repos");
1647
+ if (!existsSync5(file))
1648
+ return new Set;
1649
+ try {
1650
+ const config = await Bun.file(file).json();
1651
+ return new Set(Array.isArray(config.skip) ? config.skip.filter((name) => typeof name === "string") : []);
1652
+ } catch (error) {
1653
+ fail(`${file} does not parse: ${error instanceof Error ? error.message : String(error)}`);
1654
+ }
1655
+ }
1656
+ function releasedCell(repo) {
1657
+ if (repo.packages.length > 0)
1658
+ return repo.packages.filter((release) => release.unreleased > 0).map((release) => `${release.name} ${release.unreleased}`).join(", ") || "-";
1659
+ return repo.tag === null || repo.unreleased === 0 ? "-" : `${repo.unreleased} since ${repo.tag}`;
1660
+ }
1661
+ function row(repo, shown) {
1662
+ const tint = role("path", process14.stdout);
1663
+ const ahead = repo.ahead ?? 0;
1664
+ const behind = repo.behind ?? 0;
1665
+ const sync = repo.upstream === null ? "no upstream" : [ahead > 0 ? `+${ahead}` : "", behind > 0 ? `-${behind}` : ""].filter(Boolean).join(" ") || "-";
1666
+ return [tint(shown), repo.unreadable ? "? (unreadable)" : repo.branch, repo.dirty === 0 ? "-" : String(repo.dirty), sync, repo.worktrees === 0 ? "-" : String(repo.worktrees), releasedCell(repo)];
1667
+ }
1668
+ async function repos(args) {
1669
+ 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"]] });
1670
+ const root = resolve2(positionals[0] ?? join7(homedir3(), "Workspace"));
1671
+ if (!existsSync5(root) || !statSync2(root).isDirectory())
1672
+ fail(`no folder ${root}`);
1673
+ const only = values.only === undefined ? undefined : oneOf(values.only, "only", REASONS);
1674
+ const paths = await findRepos2(root, await skipped());
1675
+ const states = await pool2(paths, CONCURRENCY2, async (path) => inspect(path, values.fetch === true || values.pull === true));
1676
+ const keeps = (repo) => {
1677
+ const reasons = reasonsOf(repo);
1678
+ return only === undefined ? values.all === true || reasons.length > 0 || repo.unreadable : reasons.includes(only);
1679
+ };
1680
+ let failedPulls = 0;
1681
+ if (values.pull === true) {
1682
+ const log = values.json === true || values.path === true ? console.error : console.log;
1683
+ for (const [index, repo] of states.entries()) {
1684
+ if (!keeps(repo) || (repo.behind ?? 0) === 0)
1685
+ continue;
1686
+ const blocker = pullBlocker(repo);
1687
+ const refused = blocker === undefined ? await fastForward(repo.path) : undefined;
1688
+ if (blocker !== undefined) {
1689
+ log(marked("note", `${repo.name} skipped`, process14.stdout, blocker));
1690
+ } else if (refused !== undefined) {
1691
+ failedPulls++;
1692
+ log(marked("problem", `${repo.name} not pulled`, process14.stdout, refused));
1693
+ } else {
1694
+ log(marked("ok", `${repo.name} pulled`, process14.stdout, `${repo.behind} ${repo.behind === 1 ? "commit" : "commits"}`));
1695
+ states[index] = await inspect(repo.path, false);
1696
+ }
1697
+ }
1698
+ }
1699
+ const kept = states.filter(keeps);
1700
+ if (values.path === true) {
1701
+ for (const repo of kept)
1702
+ console.log(repo.path);
1703
+ return failedPulls > 0 ? 1 : 0;
1704
+ }
1705
+ if (values.json === true) {
1706
+ printJson(kept.map((repo) => ({ ...repo, reasons: reasonsOf(repo) })));
1707
+ return failedPulls > 0 ? 1 : 0;
1708
+ }
1709
+ const label = role("label", process14.stdout);
1710
+ if (kept.length === 0) {
1711
+ console.log(label(`nothing needs attention in ${states.length} repositories`));
1712
+ return failedPulls > 0 ? 1 : 0;
1713
+ }
1714
+ console.log(table([["repo", "branch", "dirty", "ahead/behind", "worktrees", "unreleased"], ...kept.map((repo) => row(repo, relative2(root, repo.path) || repo.name))], { header: true, align: ["left", "left", "right", "left", "right", "left"] }));
1715
+ const failed = kept.filter((repo) => repo.fetchFailed).map((repo) => repo.name);
1716
+ if (failed.length > 0)
1717
+ console.log(label(`fetch failed for ${failed.join(", ")}`));
1718
+ if (values.fetch !== true)
1719
+ console.log(label("ahead/behind as of the last fetch, --fetch refreshes them"));
1720
+ return failedPulls > 0 ? 1 : 0;
1721
+ }
1722
+
1723
+ // src/sweep.ts
1724
+ import { existsSync as existsSync8, statSync as statSync3 } from "fs";
1725
+ import { homedir as homedir5 } from "os";
1726
+ import { join as join11, relative as relative3, resolve as resolve3 } from "path";
1727
+
1728
+ // ../kit/src/prompt.ts
1729
+ import process15 from "process";
1730
+ var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|[\s\S]/giu;
1731
+ var CONTROL = /^[\x00-\x1F\x7F]/;
1732
+ var KEYS = { "\x1B[A": "up", "\x1BOA": "up", "\x1B[B": "down", "\x1BOB": "down", "\r": "enter", "\n": "enter", "\x03": "cancel", "\x1B": "cancel", "\x7F": "erase", "\b": "erase" };
1733
+ function readKeys(input) {
1734
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => KEYS[sequence] ?? (CONTROL.test(sequence) ? [] : [{ text: sequence }]));
1735
+ }
1736
+ async function confirm(question, { default: fallback, ...settings } = {}) {
1737
+ let answered = fallback;
1738
+ const choices = { true: "Y/n", false: "y/N", undefined: "y/n" }[String(fallback)];
1739
+ const accepted = await ask(question, settings, (colors, state) => [state === "asking" ? asking(colors, question, "", choices) : answer(colors, question, state, answered ? "yes" : "no")], (key) => {
1740
+ if (key === "cancel")
1741
+ return "cancel";
1742
+ if (key === "enter")
1743
+ return answered === undefined ? undefined : "enter";
1744
+ const letter = typeof key === "object" ? key.text.toLowerCase() : "";
1745
+ if (letter !== "y" && letter !== "n")
1746
+ return;
1747
+ answered = letter === "y";
1748
+ return "enter";
1749
+ });
1750
+ return accepted ? answered : undefined;
1751
+ }
1752
+ function asking(colors, question, typed, keys) {
1753
+ return `${colors.cyan("?")} ${question} ${typed === "" ? colors.dim(`(${keys})`) : typed}`;
1754
+ }
1755
+ function answer(colors, question, state, picked) {
1756
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1757
+ }
1758
+ async function ask(question, { hint, terminal = process15 }, render, press) {
1759
+ const { stdin, stderr } = terminal;
1760
+ if (stdin.isTTY !== true || stderr.isTTY !== true)
1761
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
1762
+ const colors = paint(stderr);
1763
+ let drawn = 0;
1764
+ let outcome;
1765
+ const draw = (state) => {
1766
+ const frame = render(colors, state, { columns: stderr.columns || 80, rows: stderr.rows || 24 });
1767
+ stderr.write(`${drawn > 1 ? `\x1B[${drawn - 1}A` : ""}\r\x1B[0J${frame.join(`
1768
+ `)}`);
1769
+ drawn = frame.length;
1770
+ };
1771
+ try {
1772
+ stdin.setRawMode(true);
1773
+ stdin.resume();
1774
+ stderr.write("\x1B[?25l");
1775
+ draw("asking");
1776
+ return await new Promise((resolve) => {
1777
+ function onData(data) {
1778
+ for (const key of readKeys(data.toString())) {
1779
+ const pressed = press(key);
1780
+ if (pressed !== undefined) {
1781
+ settle(pressed);
1782
+ return;
1783
+ }
1784
+ }
1785
+ draw("asking");
1786
+ }
1787
+ function onEnd() {
1788
+ settle("cancel");
1789
+ }
1790
+ function settle(settled) {
1791
+ outcome = settled;
1792
+ stdin.off("data", onData);
1793
+ stdin.off("end", onEnd);
1794
+ resolve(settled === "enter");
1795
+ }
1796
+ stdin.on("data", onData);
1797
+ stdin.on("end", onEnd);
1798
+ });
1799
+ } finally {
1800
+ draw(outcome ?? "cancel");
1801
+ stderr.write(`
1802
+ \x1B[?25h`);
1803
+ stdin.setRawMode(false);
1804
+ stdin.pause();
1805
+ }
1806
+ }
1807
+
1808
+ // src/apply.ts
1809
+ import { existsSync as existsSync7 } from "fs";
1810
+ import { lstat as lstat3, rm } from "fs/promises";
1811
+ import { basename as basename3, join as join10 } from "path";
1812
+
1813
+ // src/sweep-scan.ts
1814
+ import { existsSync as existsSync6 } from "fs";
1815
+ import { lstat as lstat2, readdir as readdir4, realpath } from "fs/promises";
1816
+ import { homedir as homedir4 } from "os";
1817
+ import { basename as basename2, dirname as dirname3, join as join9 } from "path";
1818
+
1819
+ // src/size.ts
1820
+ import { lstat, readdir as readdir3 } from "fs/promises";
1821
+ import { join as join8 } from "path";
1822
+ async function pooled(items, limit, work) {
1823
+ const results = Array.from({ length: items.length });
1824
+ let next = 0;
1825
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
1826
+ while (next < items.length) {
1827
+ const index = next++;
1828
+ results[index] = await work(items[index]);
1829
+ }
1830
+ }));
1831
+ return results;
1832
+ }
1833
+ var FS_LIMIT = 32;
1834
+ var waiting = [];
1835
+ var running = 0;
1836
+ async function gated(call) {
1837
+ if (running >= FS_LIMIT)
1838
+ await new Promise((resolve) => waiting.push(resolve));
1839
+ running++;
1840
+ try {
1841
+ return await call();
1842
+ } finally {
1843
+ running--;
1844
+ waiting.shift()?.();
1845
+ }
1846
+ }
1847
+ async function sizeOf(folder) {
1848
+ const seen = new Set;
1849
+ let total = 0;
1850
+ const visit = async (dir) => {
1851
+ let entries;
1852
+ try {
1853
+ entries = await gated(async () => readdir3(dir, { withFileTypes: true }));
1854
+ } catch {
1855
+ return;
1856
+ }
1857
+ await Promise.all(entries.map(async (entry) => {
1858
+ const path = join8(dir, entry.name);
1859
+ if (entry.isDirectory())
1860
+ return visit(path);
1861
+ try {
1862
+ const stat = await gated(async () => lstat(path));
1863
+ if (stat.nlink > 1) {
1864
+ const key = `${stat.dev}:${stat.ino}`;
1865
+ if (seen.has(key))
1866
+ return;
1867
+ seen.add(key);
1868
+ }
1869
+ total += stat.size;
1870
+ } catch {}
1871
+ }));
1872
+ };
1873
+ await visit(folder);
1874
+ return total;
1875
+ }
1876
+
1877
+ // src/sweep-scan.ts
1878
+ var FOLDER_NAMES = new Set(["node_modules", ".nuxt", ".next", ".output", "dist", "build", ".turbo", ".svelte-kit", "target"]);
1879
+ var MAX_DEPTH3 = 3;
1880
+ var PROJECT_CACHE_NAMES = new Set([".turbo", ".nuxt", ".next", ".svelte-kit"]);
1881
+ var GLOBAL_CACHES = [".bun/install/cache", ".npm/_cacache", ".cache/pip", ".cache/uv", ".cache/ms-playwright", ".cache/puppeteer", ".cache/go-build", ".cache/typescript", ".cargo/registry"];
1882
+ function isCachePath(path, home = homedir4()) {
1883
+ return GLOBAL_CACHES.some((cache) => join9(home, cache) === path) || basename2(path) === ".cache" && basename2(dirname3(path)) === "node_modules";
1884
+ }
1885
+ async function listing(dir) {
1886
+ try {
1887
+ return await readdir4(dir, { withFileTypes: true });
1888
+ } catch {
1889
+ return [];
1890
+ }
1891
+ }
1892
+ async function addGlobalCaches(found, home) {
1893
+ for (const cache of GLOBAL_CACHES) {
1894
+ const path = join9(home, cache);
1895
+ try {
1896
+ const stat = await lstat2(path);
1897
+ if (stat.isSymbolicLink())
1898
+ found.skipped.push({ path, reason: "symlink" });
1899
+ else if (stat.isDirectory())
1900
+ found.candidates.push({ path, kind: "cache", global: true });
1901
+ } catch {}
1902
+ }
1903
+ }
1904
+ async function findCandidates(root, home = homedir4(), withGlobal = true) {
1905
+ const found = { candidates: [], skipped: [] };
1906
+ const visit = async (dir, depth) => {
1907
+ const entries = await listing(dir);
1908
+ for (const entry of entries) {
1909
+ const path = join9(dir, entry.name);
1910
+ if (entry.name === ".git")
1911
+ continue;
1912
+ if (entry.name === ".worktrees" || entry.name === "worktrees" && basename2(dir) === ".claude") {
1913
+ if (!entry.isDirectory()) {
1914
+ found.skipped.push({ path, reason: "symlink" });
1915
+ continue;
1916
+ }
1917
+ for (const worktree of await listing(path)) {
1918
+ if (worktree.isDirectory())
1919
+ found.candidates.push({ path: join9(path, worktree.name), kind: "worktree" });
1920
+ else if (worktree.isSymbolicLink())
1921
+ found.skipped.push({ path: join9(path, worktree.name), reason: "symlink" });
1922
+ }
1923
+ continue;
1924
+ }
1925
+ if (FOLDER_NAMES.has(entry.name) && (entry.name !== "target" || existsSync6(join9(dir, "Cargo.toml")))) {
1926
+ if (entry.isSymbolicLink()) {
1927
+ found.skipped.push({ path, reason: "symlink" });
1928
+ } else if (entry.isDirectory()) {
1929
+ found.candidates.push({ path, kind: PROJECT_CACHE_NAMES.has(entry.name) ? "cache" : "folder" });
1930
+ if (entry.name === "node_modules") {
1931
+ const cache = (await listing(path)).find((inner) => inner.name === ".cache");
1932
+ if (cache?.isSymbolicLink())
1933
+ found.skipped.push({ path: join9(path, ".cache"), reason: "symlink" });
1934
+ else if (cache?.isDirectory())
1935
+ found.candidates.push({ path: join9(path, ".cache"), kind: "cache", inside: path });
1936
+ }
1937
+ }
1938
+ continue;
1939
+ }
1940
+ if (entry.isDirectory() && depth < MAX_DEPTH3)
1941
+ await visit(path, depth + 1);
1942
+ }
1943
+ };
1944
+ await visit(root, 0);
1945
+ if (withGlobal)
1946
+ await addGlobalCaches(found, home);
1947
+ return found;
1948
+ }
1949
+ async function realOf(path) {
1950
+ try {
1951
+ return await realpath(path);
1952
+ } catch {
1953
+ return;
1954
+ }
1955
+ }
1956
+ var HEADS_PREFIX = /^refs\/heads\//;
1957
+ var TRAILING_SLASH = /\/$/;
1958
+ async function gitIn(cwd, args) {
1959
+ try {
1960
+ const { code, stdout, stderr } = await runTool(`git ${args.join(" ")}`, ["git", "-C", cwd, ...args], { timeoutMs: 30000 });
1961
+ return { code, stdout: stdout.trim(), stderr };
1962
+ } catch (error) {
1963
+ return { code: -1, stdout: "", stderr: String(error) };
1964
+ }
1965
+ }
1966
+ function memo(make) {
1967
+ const cache = new Map;
1968
+ return async (key) => {
1969
+ let value = cache.get(key);
1970
+ if (value === undefined) {
1971
+ value = make(key);
1972
+ cache.set(key, value);
1973
+ }
1974
+ return value;
1975
+ };
1976
+ }
1977
+ var NOT_A_REPO = /not a git repository/i;
1978
+ var toplevelOf = memo(async (dir) => {
1979
+ const { code, stdout, stderr } = await gitIn(dir, ["rev-parse", "--show-toplevel"]);
1980
+ if (code === 0 && stdout !== "")
1981
+ return { top: stdout };
1982
+ return NOT_A_REPO.test(stderr) ? "none" : "failed";
1983
+ });
1984
+ var lastCommitOf = memo(async (top) => {
1985
+ const { code, stdout } = await gitIn(top, ["log", "-1", "--format=%ct"]);
1986
+ return code === 0 && stdout !== "" ? Number(stdout) * 1000 : undefined;
1987
+ });
1988
+ var worktreesOf = memo(async (repo) => {
1989
+ const { code, stdout } = await gitIn(repo, ["worktree", "list", "--porcelain"]);
1990
+ const branches = new Map;
1991
+ if (code !== 0)
1992
+ return branches;
1993
+ for (const block of stdout.split(`
1994
+
1995
+ `)) {
1996
+ const lines = block.split(`
1997
+ `);
1998
+ const path = lines.find((line) => line.startsWith("worktree "))?.slice("worktree ".length);
1999
+ const branch = lines.find((line) => line.startsWith("branch "))?.slice("branch ".length);
2000
+ if (path !== undefined)
2001
+ branches.set(await realOf(path) ?? path, branch);
2002
+ }
2003
+ return branches;
2004
+ });
2005
+ async function judgeFolder(path, kind, inside) {
2006
+ const parent = dirname3(path);
2007
+ const name = basename2(path);
2008
+ const located = await toplevelOf(parent);
2009
+ if (located === "failed")
2010
+ return { skip: "git failed" };
2011
+ if (existsSync6(join9(path, ".git")))
2012
+ return { skip: "holds a git repository" };
2013
+ if (located === "none")
2014
+ return name === "node_modules" || inside !== undefined ? { entry: { path, kind, committedAt: undefined, action: "remove", inside } } : { skip: "not in a git repository" };
2015
+ const tracked = await gitIn(parent, ["ls-files", "--", name]);
2016
+ if (tracked.code !== 0 || tracked.stdout !== "")
2017
+ return { skip: "tracked by git" };
2018
+ if (name !== "node_modules" && inside === undefined && (await gitIn(parent, ["check-ignore", "-q", "--", name])).code !== 0)
2019
+ return { skip: "not ignored by git" };
2020
+ return { entry: { path, kind, committedAt: await lastCommitOf(located.top), action: "remove", inside } };
2021
+ }
2022
+ async function judgeWorktree(path) {
2023
+ const located = await toplevelOf(dirname3(path));
2024
+ if (located === "failed")
2025
+ return { skip: "git failed" };
2026
+ if (located === "none")
2027
+ return { skip: "not in a git repository" };
2028
+ const { top } = located;
2029
+ const real = await realOf(path);
2030
+ const branches = await worktreesOf(top);
2031
+ if (real === undefined || !branches.has(real))
2032
+ return { skip: "not a worktree of this repo" };
2033
+ const committedAt = await lastCommitOf(top);
2034
+ const keep = (reason) => ({ entry: { path, kind: "worktree", committedAt, action: "keep", reason, repo: top } });
2035
+ const branch = branches.get(real);
2036
+ if (branch === undefined)
2037
+ return keep("detached HEAD");
2038
+ const status = await gitIn(path, ["status", "--porcelain", "-z", "--ignored=matching"]);
2039
+ if (status.code !== 0)
2040
+ return keep("status failed");
2041
+ const changes = status.stdout.split("\x00").filter((line) => line !== "");
2042
+ if (changes.some((line) => !line.startsWith("!! ")))
2043
+ return keep("uncommitted changes");
2044
+ if (changes.some((line) => !line.endsWith("/") || !FOLDER_NAMES.has(basename2(line.slice(3).replace(TRAILING_SLASH, "")))))
2045
+ return keep("ignored files (.env, local data) that removing would delete");
2046
+ const unique = await gitIn(path, ["log", "--format=%h", branch, "--not", "--remotes", `--exclude=${branch.replace(HEADS_PREFIX, "")}`, "--branches"]);
2047
+ if (unique.code !== 0)
2048
+ return keep("log failed");
2049
+ if (unique.stdout !== "")
2050
+ return keep(`${unique.stdout.split(`
2051
+ `).length} commits on no other branch or remote`);
2052
+ return { entry: { path, kind: "worktree", committedAt, action: "remove", repo: top } };
2053
+ }
2054
+ async function judge(candidate) {
2055
+ if (candidate.global === true)
2056
+ return { entry: { path: candidate.path, kind: candidate.kind, committedAt: undefined, action: "remove" } };
2057
+ return candidate.kind === "worktree" ? judgeWorktree(candidate.path) : judgeFolder(candidate.path, candidate.kind, candidate.inside);
2058
+ }
2059
+ async function inspect2({ candidates, skipped }) {
2060
+ const entries = [];
2061
+ const rejected = [...skipped];
2062
+ await pooled(candidates, 8, async (candidate) => {
2063
+ const verdict = await judge(candidate);
2064
+ if ("skip" in verdict)
2065
+ rejected.push({ path: candidate.path, reason: verdict.skip });
2066
+ else
2067
+ entries.push({ ...verdict.entry, bytes: await sizeOf(candidate.path) });
2068
+ });
2069
+ const listed = new Set(entries.filter((entry) => entry.action === "remove").map((entry) => entry.path));
2070
+ return { entries: entries.filter((entry) => entry.inside === undefined || !listed.has(entry.inside)), skipped: rejected };
2071
+ }
2072
+
2073
+ // src/apply.ts
2074
+ async function removeFolder(entry) {
2075
+ try {
2076
+ const stat = await lstat3(entry.path);
2077
+ if (stat.isSymbolicLink() || !stat.isDirectory() || !(FOLDER_NAMES.has(basename3(entry.path)) || entry.kind === "cache" && isCachePath(entry.path)))
2078
+ return { path: entry.path, removed: false, error: "no longer a plain folder" };
2079
+ if (existsSync7(join10(entry.path, ".git")))
2080
+ return { path: entry.path, removed: false, error: "holds a git repository" };
2081
+ await rm(entry.path, { recursive: true, force: true });
2082
+ return { path: entry.path, removed: true };
2083
+ } catch (error) {
2084
+ return { path: entry.path, removed: false, error: error instanceof Error ? error.message : String(error) };
2085
+ }
2086
+ }
2087
+ async function removeWorktree(entry) {
2088
+ if (entry.repo === undefined)
2089
+ return { path: entry.path, removed: false, error: "no repository known" };
2090
+ try {
2091
+ const ran = await runTool("git worktree remove", ["git", "-C", entry.repo, "worktree", "remove", entry.path]);
2092
+ return ran.code === 0 ? { path: entry.path, removed: true } : { path: entry.path, removed: false, error: ran.stderr.trim() };
2093
+ } catch (error) {
2094
+ return { path: entry.path, removed: false, error: String(error) };
2095
+ }
2096
+ }
2097
+ async function applyAll(entries, done) {
2098
+ const outcomes = [];
2099
+ for (const entry of entries) {
2100
+ if (entry.action !== "remove")
2101
+ continue;
2102
+ const outcome = await (entry.kind === "worktree" ? removeWorktree(entry) : removeFolder(entry));
2103
+ outcomes.push(outcome);
2104
+ done(outcome);
2105
+ }
2106
+ return outcomes;
2107
+ }
2108
+
2109
+ // src/sweep.ts
2110
+ var USAGE3 = `sweep [options] [root]: lists the regenerable folders (node_modules, .output, dist, build, target beside a Cargo.toml), the caches (.nuxt, .next, .turbo, .svelte-kit and node_modules/.cache per project; ~/.bun/install/cache, ~/.npm/_cacache, ~/.cache/{pip,uv,ms-playwright,puppeteer,go-build,typescript} and ~/.cargo/registry, exact paths only, listed only when no root is given or with --only caches) and the .worktrees/* and .claude/worktrees/* entries under root (~/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
2111
+
2112
+ 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.
2113
+
2114
+ Exits 0 when it listed, or removed every entry it was allowed to, 1 when a removal failed or the confirm was declined, 2 on a usage error, a missing root, or --apply off a terminal without --yes.`;
2115
+ var ONLY_KINDS = { worktrees: "worktree", folders: "folder", caches: "cache" };
2116
+ var OPTIONS3 = {
2117
+ apply: { type: "boolean", description: "delete what is listed as removable, after the confirm" },
2118
+ yes: { type: "boolean", short: "y", description: "with --apply, skip the confirm" },
2119
+ older: { type: "string", description: "only the entries whose repo last committed longer ago than this (30d, 12h)" },
2120
+ min: { type: "string", description: "only the entries of at least this size (500K, 10M, 1G)" },
2121
+ only: { type: "string", description: "worktrees, folders or caches: leave the other kinds out (.nuxt, .next, .turbo and .svelte-kit are caches; the global caches are listed with no root or with caches)" },
2122
+ docker: { type: "boolean", description: "add the docker system df output, which alone takes about ten seconds" },
2123
+ json: jsonOption("{root, entries: [{path, kind (folder, worktree or cache), bytes, committedAt, action (remove or keep), reason}], skipped: [{path, reason}], reclaimable, docker, removed?}")
2124
+ };
2125
+ async function dockerUsage() {
2126
+ if (Bun.which("docker") === null)
2127
+ return;
2128
+ try {
2129
+ const { code, stdout } = await runTool("docker system df", ["docker", "system", "df"], { timeoutMs: 1e4 });
2130
+ return code === 0 ? stdout.trimEnd() : undefined;
2131
+ } catch {
2132
+ return;
2133
+ }
2134
+ }
2135
+ async function sweep(args) {
2136
+ const { values, positionals } = parse(args, USAGE3, OPTIONS3, { 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"] });
2137
+ if (positionals.length > 1)
2138
+ badUsage("give one root");
2139
+ const root = resolve3(positionals[0] ?? join11(homedir5(), "Workspace"));
2140
+ if (!existsSync8(root) || !statSync3(root).isDirectory())
2141
+ fail(`${root} is not a folder`);
2142
+ if (values.only !== undefined && !Object.hasOwn(ONLY_KINDS, values.only))
2143
+ badUsage(`--only takes worktrees, folders or caches, not ${values.only}`);
2144
+ const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0);
2145
+ const minBytes = values.min === undefined ? 0 : parseSize(values.min);
2146
+ if (minBytes === undefined)
2147
+ badUsage(`--min takes a size such as 500K, 10M or 1G, not ${values.min}`);
2148
+ const now = Date.now();
2149
+ const found = await findCandidates(root, homedir5(), positionals.length === 0 || values.only === "caches");
2150
+ const wanted = values.only === undefined ? found.candidates : found.candidates.filter((candidate) => candidate.kind === ONLY_KINDS[values.only]);
2151
+ const { entries: all, skipped } = await inspect2({ candidates: wanted, skipped: found.skipped });
2152
+ 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));
2153
+ const removable = entries.filter((entry) => entry.action === "remove");
2154
+ const reclaimable = removable.reduce((sum, entry) => sum + entry.bytes, 0);
2155
+ const docker = values.docker === true ? await dockerUsage() : undefined;
2156
+ const json = values.json === true;
2157
+ if (values.apply === true && removable.length > 0 && values.yes !== true) {
2158
+ if (!json)
2159
+ print(root, entries, skipped.length, reclaimable, now);
2160
+ const agreed = await confirm(`Delete ${removable.length} ${removable.length === 1 ? "entry" : "entries"} (${$e(reclaimable)})?`, { default: false, hint: "pass --yes to skip the confirm" });
2161
+ if (agreed !== true) {
2162
+ if (json)
2163
+ fail("nothing deleted: the confirm was declined", 1, "pass --yes to skip the confirm");
2164
+ note("nothing deleted");
2165
+ return 1;
2166
+ }
2167
+ }
2168
+ const outcomes = values.apply === true ? await applyAll(removable, (outcome) => report(root, outcome, json)) : undefined;
2169
+ const failed = outcomes?.filter((outcome) => !outcome.removed).length ?? 0;
2170
+ if (json) {
2171
+ printJson({ root, entries: entries.map((entry) => ({ path: entry.path, kind: entry.kind, bytes: entry.bytes, committedAt: entry.committedAt === undefined ? null : new Date(entry.committedAt).toISOString(), action: entry.action, reason: entry.reason ?? null })), skipped, reclaimable, docker: docker ?? null, ...outcomes === undefined ? {} : { removed: outcomes } });
2172
+ return failed === 0 ? 0 : 1;
2173
+ }
2174
+ if (outcomes === undefined) {
2175
+ print(root, entries, skipped.length, reclaimable, now);
2176
+ if (removable.length > 0)
2177
+ console.log("dry run, pass --apply to delete");
2178
+ } else {
2179
+ const bytes = new Map(removable.map((entry) => [entry.path, entry.bytes]));
2180
+ note(`freed ${$e(outcomes.reduce((sum, outcome) => sum + (outcome.removed ? bytes.get(outcome.path) ?? 0 : 0), 0))}`);
2181
+ }
2182
+ if (docker !== undefined)
2183
+ console.log(`
2184
+ docker (left to dclean):
2185
+ ${docker}`);
2186
+ return failed === 0 ? 0 : 1;
2187
+ }
2188
+ function report(root, outcome, json) {
2189
+ if (json)
2190
+ return;
2191
+ if (outcome.removed)
2192
+ ok(`removed ${relative3(root, outcome.path)}`);
2193
+ else
2194
+ problem(`kept ${relative3(root, outcome.path)}`, outcome.error);
2195
+ }
2196
+ function print(root, entries, skipped, reclaimable, now) {
2197
+ if (entries.length === 0) {
2198
+ console.log("nothing to sweep");
2199
+ return;
2200
+ }
2201
+ console.log(table([["size", "age", "what", "path", "note"], ...entries.map((entry) => [$e(entry.bytes), entry.committedAt === undefined ? "-" : formatAge(entry.committedAt, now), entry.kind, relative3(root, entry.path), entry.action === "keep" ? `kept: ${entry.reason}` : ""])], { header: true, align: ["right", "right", "left", "left", "left"] }));
2202
+ console.log(`
2203
+ ${$e(reclaimable)} reclaimable${skipped === 0 ? "" : `, ${skipped} skipped (symlinks, tracked or not ignored by git)`}`);
2204
+ }
2205
+
2206
+ // src/cli.ts
2207
+ process16.exitCode = await runCli({
2208
+ name: "ws",
2209
+ about: "the repositories under a root: the ones needing attention, the folders worth reclaiming and their known vulnerabilities",
2210
+ replaces: "a cd, git status and du loop over each repository of the workspace, and a bun audit run in each",
2211
+ examples: ["ws repos", ["ws sweep --older 30d", "what a month of idle repos weighs"], "ws audit"],
2212
+ commands: {
2213
+ repos: { summary: "the git repositories that need attention: dirty, ahead or behind, worktrees, unreleased commits", run: repos },
2214
+ sweep: { summary: "the regenerable folders, caches and clean worktrees, largest first, deleted only on --apply", run: sweep },
2215
+ audit: { summary: "the known vulnerabilities of the Bun repositories, one table per repository", run: audit }
2216
+ }
2217
+ });