@kaynooo/cli-proc 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1502 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/procs-cli.ts
5
+ import process11 from "process";
6
+
7
+ // ../kit/src/args.ts
8
+ import process5 from "process";
9
+ import { parseArgs } from "util";
10
+
11
+ // ../kit/src/format.ts
12
+ import process3 from "process";
13
+
14
+ // ../kit/src/style.ts
15
+ import process2 from "process";
16
+
17
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
+ function x(s) {
19
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
20
+ if (!/^[a-f0-9]+$/.test(r))
21
+ return [0, 0, 0];
22
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
23
+ if (t === 3 || t === 4) {
24
+ 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;
25
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
26
+ }
27
+ if (t !== 6 && t !== 8)
28
+ throw Error(`Invalid hex color length: ${t}`);
29
+ 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;
30
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
31
+ throw Error(`Invalid hex color value: ${s}`);
32
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
33
+ }
34
+ function A(s) {
35
+ let [r, t, n, a] = s;
36
+ if (a)
37
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
38
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
39
+ }
40
+ function R(s, r, t) {
41
+ s = (s % 360 + 360) % 360, t /= 100;
42
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
43
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
44
+ return Math.round(255 * y);
45
+ };
46
+ return [a(0), a(8), a(4)];
47
+ }
48
+ function k(s) {
49
+ let [r, t, n] = s;
50
+ r /= 255, t /= 255, n /= 255;
51
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
52
+ if (a !== b) {
53
+ let u = a - b;
54
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
55
+ o = (t - n) / u + (t < n ? 6 : 0);
56
+ else if (a === t)
57
+ o = (n - r) / u + 2;
58
+ else
59
+ o = (r - t) / u + 4;
60
+ o /= 6;
61
+ }
62
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
63
+ }
64
+ function H(s, r, t) {
65
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
66
+ let n = (a) => {
67
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
68
+ return Math.round(255 * o);
69
+ };
70
+ return [n(5), n(3), n(1)];
71
+ }
72
+ function f(s) {
73
+ let [r, t, n] = s;
74
+ r /= 255, t /= 255, n /= 255;
75
+ 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;
76
+ if (o !== 0) {
77
+ if (a === r)
78
+ y = (t - n) / o + (t < n ? 6 : 0);
79
+ else if (a === t)
80
+ y = (n - r) / o + 2;
81
+ else
82
+ y = (r - t) / o + 4;
83
+ y /= 6;
84
+ }
85
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
86
+ }
87
+ function O(s) {
88
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
89
+ if (a === 1)
90
+ return [0, 0, 0, 100];
91
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
92
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
93
+ }
94
+ function v(s, r, t, n) {
95
+ 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))];
96
+ }
97
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
98
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
99
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
100
+ function T(s) {
101
+ 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);
102
+ 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)];
103
+ }
104
+ function M(s, r, t) {
105
+ 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)));
106
+ return [u(o), u(y), u(c)];
107
+ }
108
+ function d(s) {
109
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
110
+ return [i(r, 4), i(a, 4), i(b, 2)];
111
+ }
112
+ function C(s, r, t) {
113
+ let n = t * Math.PI / 180;
114
+ return M(s, r * Math.cos(n), r * Math.sin(n));
115
+ }
116
+ function l(s) {
117
+ let r = s / 255;
118
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
119
+ }
120
+
121
+ class e {
122
+ r;
123
+ g;
124
+ b;
125
+ a;
126
+ constructor(s, r, t, n = 1) {
127
+ this.r = s, this.g = r, this.b = t, this.a = n;
128
+ }
129
+ static from(s, r) {
130
+ if (s === "hex") {
131
+ let [t, n, a, b] = x(r);
132
+ return new e(t, n, a, b);
133
+ }
134
+ if (s === "rgb") {
135
+ if (Array.isArray(r)) {
136
+ let [o, y, c, u] = r;
137
+ return new e(o, y, c, u);
138
+ }
139
+ let { r: t, g: n, b: a, a: b } = r;
140
+ return new e(t, n, a, b);
141
+ }
142
+ if (s === "hsl") {
143
+ let t, n, a, b;
144
+ if (Array.isArray(r))
145
+ [t, n, a, b] = r;
146
+ else
147
+ ({ h: t, s: n, l: a, a: b } = r);
148
+ let [o, y, c] = R(t, n, a);
149
+ return new e(o, y, c, b);
150
+ }
151
+ if (s === "hsv") {
152
+ let t, n, a, b;
153
+ if (Array.isArray(r))
154
+ [t, n, a, b] = r;
155
+ else
156
+ ({ h: t, s: n, v: a, a: b } = r);
157
+ let [o, y, c] = H(t, n, a);
158
+ return new e(o, y, c, b);
159
+ }
160
+ if (s === "cmyk") {
161
+ let t, n, a, b, o;
162
+ if (Array.isArray(r))
163
+ [t, n, a, b, o] = r;
164
+ else
165
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
166
+ let [y, c, u] = v(t, n, a, b);
167
+ return new e(y, c, u, o);
168
+ }
169
+ if (s === "oklch") {
170
+ let t, n, a, b;
171
+ if (Array.isArray(r))
172
+ [t, n, a, b] = r;
173
+ else
174
+ ({ l: t, c: n, h: a, a: b } = r);
175
+ let [o, y, c] = C(t, n, a);
176
+ return new e(o, y, c, b);
177
+ }
178
+ if (s === "oklab") {
179
+ let t, n, a, b;
180
+ if (Array.isArray(r))
181
+ [t, n, a, b] = r;
182
+ else
183
+ ({ l: t, a: n, b: a, alpha: b } = r);
184
+ let [o, y, c] = M(t, n, a);
185
+ return new e(o, y, c, b);
186
+ }
187
+ throw Error("Invalid input");
188
+ }
189
+ to(s) {
190
+ switch (s) {
191
+ case "rgb":
192
+ return [this.r, this.g, this.b];
193
+ case "rgba":
194
+ return [this.r, this.g, this.b, this.a];
195
+ case "hex":
196
+ return A([this.r, this.g, this.b]);
197
+ case "hexa":
198
+ return A([this.r, this.g, this.b, this.a]);
199
+ case "hsl":
200
+ return k([this.r, this.g, this.b]);
201
+ case "hsla":
202
+ return [...k([this.r, this.g, this.b]), this.a];
203
+ case "hsv":
204
+ return f([this.r, this.g, this.b]);
205
+ case "hsva":
206
+ return [...f([this.r, this.g, this.b]), this.a];
207
+ case "cmyk":
208
+ return O([this.r, this.g, this.b]);
209
+ case "cmyka":
210
+ return [...O([this.r, this.g, this.b]), this.a];
211
+ case "oklch":
212
+ return d([this.r, this.g, this.b]);
213
+ case "oklcha":
214
+ return [...d([this.r, this.g, this.b]), this.a];
215
+ case "oklab":
216
+ return T([this.r, this.g, this.b]);
217
+ case "oklaba":
218
+ return [...T([this.r, this.g, this.b]), this.a];
219
+ default:
220
+ return [this.r, this.g, this.b];
221
+ }
222
+ }
223
+ getLuminance() {
224
+ let s = l(this.r), r = l(this.g), t = l(this.b);
225
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
226
+ }
227
+ contrastRatio(s) {
228
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
229
+ return (n + 0.05) / (a + 0.05);
230
+ }
231
+ bestContrastForeground() {
232
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
233
+ return t >= n ? s : r;
234
+ }
235
+ }
236
+
237
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
238
+ var r = 39;
239
+ var o = 49;
240
+ var f2 = "\x1B[";
241
+ 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") => {
242
+ let [a, l, s] = e.from("hex", i).to("rgb");
243
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
244
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
245
+ var b = new Set(["", "1", "2", "3", "true"]);
246
+ function h(i, n = globalThis.process?.env ?? {}) {
247
+ if (n.FORCE_COLOR !== undefined)
248
+ return b.has(n.FORCE_COLOR);
249
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
250
+ return false;
251
+ return i?.isTTY === true;
252
+ }
253
+ function d2(i, n, a) {
254
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
255
+ return n;
256
+ let l = "", s = "";
257
+ for (let g = 0, y = i.length;g < y; g++) {
258
+ let [c, p] = i[g];
259
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
260
+ }
261
+ return l + n + s;
262
+ }
263
+ function u(i, n = []) {
264
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
265
+ let g = C2[s];
266
+ if (Array.isArray(g))
267
+ return u(i, [...n, g]);
268
+ if (typeof g === "function")
269
+ return (...y) => u(i, [...n, g(...y)]);
270
+ throw Error(`Unknown style: ${String(s)}`);
271
+ } });
272
+ }
273
+ function le(i = {}) {
274
+ return u(i);
275
+ }
276
+ var t = le();
277
+
278
+ // ../kit/src/style.ts
279
+ function takesControlCodes(stream, env = process2.env) {
280
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
281
+ }
282
+ function paint(stream, env = process2.env) {
283
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
284
+ }
285
+ var STATUSES = {
286
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
287
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
288
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
289
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
290
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
291
+ };
292
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
293
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-hrsswv1w.js
294
+ function $e(t, e = false, i = 1) {
295
+ let n = typeof e === "object" ? e : { units: e ? "si" : "iec", dp: i }, { units: s = "iec", dp: u = 1 } = n, r = s === "si" ? 1000 : 1024;
296
+ if (Math.abs(t) < r)
297
+ return `${t} B`;
298
+ 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;
299
+ do
300
+ t /= r, ++o;
301
+ while (Math.round(Math.abs(t) * l) / l >= r && o < c.length - 1);
302
+ return `${t.toFixed(u)} ${c[o]}`;
303
+ }
304
+
305
+ // ../kit/src/format.ts
306
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
307
+ function formatSeconds(total) {
308
+ let rest = Math.max(0, Math.round(total));
309
+ const amounts = UNITS.map(([unit, size]) => {
310
+ const amount = Math.floor(rest / size);
311
+ rest -= amount * size;
312
+ return `${amount}${unit}`;
313
+ });
314
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
315
+ if (first === -1)
316
+ return "0s";
317
+ const next = amounts[first + 1];
318
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
319
+ }
320
+ function upTo(text, separator) {
321
+ const end = text.indexOf(separator);
322
+ return end === -1 ? text : text.slice(0, end);
323
+ }
324
+ function truncate(text, width) {
325
+ return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
326
+ }
327
+ var LINE_BREAKS = /\s*\n\s*/g;
328
+ var ESCAPE = String.fromCharCode(27);
329
+ function textWidth(text) {
330
+ return Bun.stringWidth(text);
331
+ }
332
+ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
333
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
334
+ const widths = [];
335
+ for (const row of cells) {
336
+ for (const [index, cell] of row.entries())
337
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
338
+ }
339
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
340
+ const colors = paint(process3.stdout);
341
+ const lines = shown.map((row) => row.map((cell, index) => {
342
+ const width = widths[index] ?? 0;
343
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
344
+ if (align[index] === "right")
345
+ return `${gap}${cell}`;
346
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
347
+ }).join(" ").trimEnd());
348
+ return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
349
+ `);
350
+ }
351
+ function narrow(rows, widths, limit) {
352
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
353
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
354
+ const floor = 8;
355
+ while (used() > limit) {
356
+ let widest = -1;
357
+ for (const [index, width] of widths.entries()) {
358
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
359
+ widest = index;
360
+ }
361
+ if (widest === -1)
362
+ break;
363
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
364
+ }
365
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
366
+ }
367
+ function printJson(value) {
368
+ console.log(JSON.stringify(value, undefined, 2));
369
+ }
370
+
371
+ // ../kit/src/help.ts
372
+ import process4 from "process";
373
+ var OPTIONAL = /\[[^\]]+\]/g;
374
+ var USAGE_PREFIX = /^usage:\s*/i;
375
+ var FULL_STOP = /\.$/;
376
+ function usageLine(usage, colors = paint(process4.stdout)) {
377
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
378
+ }
379
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces } = {}) {
380
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
381
+ `);
382
+ }
383
+ function replacesRows(replaces, colors = paint(process4.stdout)) {
384
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
385
+ }
386
+ function wantsHelpJson(env = process4.env) {
387
+ return env.KIT_HELP === "json";
388
+ }
389
+ function description(usage, { examples = [], replaces } = {}) {
390
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
391
+ `);
392
+ const first = lines[0];
393
+ const colon = first.indexOf(": ");
394
+ const prose = lines[lines.indexOf("") + 1] ?? "";
395
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
396
+ return {
397
+ synopsis: colon === -1 ? first : first.slice(0, colon),
398
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
399
+ ...replaces === undefined ? {} : { replaces },
400
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
401
+ };
402
+ }
403
+ function exampleRows(examples, colors = paint(process4.stdout)) {
404
+ if (examples.length === 0)
405
+ return [];
406
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
407
+ }
408
+ function optionRows(options, colors = paint(process4.stdout)) {
409
+ const rows = Object.entries(options).map(([name, option]) => {
410
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
411
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
412
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
413
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
414
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
415
+ });
416
+ const width = Math.max(0, ...rows.map((row) => row.width));
417
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
418
+ }
419
+
420
+ // ../kit/src/text.ts
421
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
422
+ function distance(a, b) {
423
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
424
+ for (const [i, left] of [...a].entries()) {
425
+ const current = [i + 1];
426
+ for (const [j, right] of [...b].entries())
427
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
428
+ previous = current;
429
+ }
430
+ return previous[b.length] ?? 0;
431
+ }
432
+ function closest(name, names) {
433
+ const started = names.find((known) => known.startsWith(name));
434
+ if (started !== undefined)
435
+ return started;
436
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
437
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
438
+ }
439
+ // ../kit/src/input.ts
440
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
441
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
442
+ function duration(value, name, fallback, unit = "s") {
443
+ if (value === undefined)
444
+ return fallback;
445
+ const match = DURATION.exec(value.trim());
446
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
447
+ if (ms < 1)
448
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
449
+ return ms;
450
+ }
451
+
452
+ // ../kit/src/args.ts
453
+ var DASHES = /^-+/;
454
+ function jsonOption(holds) {
455
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
456
+ }
457
+
458
+ class Exit extends Error {
459
+ code;
460
+ hint;
461
+ constructor(message, code, hint) {
462
+ super(message);
463
+ this.code = code;
464
+ this.hint = hint;
465
+ }
466
+ }
467
+ function fail(message, code = 2, hint) {
468
+ throw new Exit(message, code, hint);
469
+ }
470
+
471
+ class UsageError extends Exit {
472
+ constructor(message, hint) {
473
+ super(message, 2, hint);
474
+ }
475
+ }
476
+ function badUsage(message) {
477
+ throw new UsageError(message);
478
+ }
479
+
480
+ class HelpShown extends Exit {
481
+ constructor() {
482
+ super("help shown", 0);
483
+ }
484
+ }
485
+
486
+ class Completing {
487
+ options;
488
+ positionals;
489
+ candidates;
490
+ constructor(options, positionals = [], candidates = {}) {
491
+ this.options = options;
492
+ this.positionals = positionals;
493
+ this.candidates = candidates;
494
+ }
495
+ }
496
+ var completion = { active: false };
497
+ var OUTPUT_OPTIONS = {
498
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
499
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
500
+ };
501
+ function applyOutput(color, plain, env = process5.env) {
502
+ const when = plain === true ? "never" : color ?? "auto";
503
+ if (when === "auto")
504
+ return;
505
+ if (when !== "always" && when !== "never")
506
+ badUsage(`--color takes auto, always or never, not ${when}`);
507
+ if (when === "always") {
508
+ env.FORCE_COLOR = "1";
509
+ delete env.NO_COLOR;
510
+ } else {
511
+ env.NO_COLOR = "1";
512
+ delete env.FORCE_COLOR;
513
+ }
514
+ }
515
+ function parse(args, usage, options, settings = {}) {
516
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
517
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
518
+ const listing = listed(all, settings.allowNegative === true);
519
+ if (completion.active)
520
+ throw new Completing(listing, settings.positionals, settings.candidates);
521
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
522
+ let parsed;
523
+ try {
524
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
525
+ } catch (error) {
526
+ const message = parseError(error);
527
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
528
+ }
529
+ const values = parsed.values;
530
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
531
+ if (values.help === true) {
532
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
533
+ throw new HelpShown;
534
+ }
535
+ checkChoices(parsed.values, all);
536
+ checkConflicts(parsed.values, all);
537
+ if (settings.positionals !== undefined)
538
+ checkPositionals(parsed.positionals, settings.positionals);
539
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
540
+ }
541
+ function splitRest(args, passes) {
542
+ const separator = passes ? args.indexOf("--") : -1;
543
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
544
+ }
545
+ function splitTrailing(args, options, count) {
546
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
547
+ let seen = 0;
548
+ if (count === 0)
549
+ return { own: args, rest: undefined };
550
+ for (let at = 0;at < args.length; at++) {
551
+ const word = args[at];
552
+ if (word === "--")
553
+ break;
554
+ if (word.startsWith("-")) {
555
+ if (takesValue(word))
556
+ at++;
557
+ continue;
558
+ }
559
+ seen++;
560
+ if (seen === count)
561
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
562
+ }
563
+ return { own: args, rest: undefined };
564
+ }
565
+ function listed(options, allowNegative) {
566
+ if (!allowNegative)
567
+ return options;
568
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
569
+ if (option.type !== "boolean" || option.negative === undefined)
570
+ return [[name, option]];
571
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
572
+ }));
573
+ }
574
+ function withBare(args, options) {
575
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
576
+ if (bare.size === 0)
577
+ return args;
578
+ const separator = args.indexOf("--");
579
+ const own = separator === -1 ? args : args.slice(0, separator);
580
+ return [...own.flatMap((arg, index) => {
581
+ const optional = bare.get(arg);
582
+ const next = own[index + 1];
583
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
584
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
585
+ }), ...separator === -1 ? [] : args.slice(separator)];
586
+ }
587
+ function checkConflicts(values, options) {
588
+ const given = (name) => values[name] !== undefined && values[name] !== false;
589
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
590
+ const other = given(name) ? conflicts.find(given) : undefined;
591
+ if (other !== undefined)
592
+ badUsage(`--${name} cannot be used with --${other}`);
593
+ }
594
+ }
595
+ function checkChoices(values, options) {
596
+ for (const [name, option] of Object.entries(options)) {
597
+ if (option.choices === undefined)
598
+ continue;
599
+ const given = values[name];
600
+ for (const value of Array.isArray(given) ? given : [given]) {
601
+ if (typeof value === "string")
602
+ oneOf(value, name, option.choices);
603
+ }
604
+ }
605
+ }
606
+ function oneOf(value, name, choices) {
607
+ if (!choices.includes(value))
608
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
609
+ return value;
610
+ }
611
+ function checkPositionals(given, names) {
612
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
613
+ const required = names.filter((name) => !name.startsWith("[")).length;
614
+ if (given.length < required)
615
+ badUsage(`missing ${names[given.length]}`);
616
+ if (!variadic && given.length > names.length)
617
+ badUsage(`unexpected argument ${given[names.length]}`);
618
+ }
619
+ function joinDashValues(args, options) {
620
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
621
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
622
+ const joined = [];
623
+ for (let i = 0;i < args.length; i++) {
624
+ const arg = args[i] ?? "";
625
+ if (arg === "--")
626
+ return [...joined, ...args.slice(i)];
627
+ const name = longOf.get(arg);
628
+ const next = args[i + 1];
629
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
630
+ joined.push(`--${name}=${next}`);
631
+ i++;
632
+ } else {
633
+ joined.push(arg);
634
+ }
635
+ }
636
+ return joined;
637
+ }
638
+ function parseError(error) {
639
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
640
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
641
+ }
642
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
643
+ function nearestOption(message, options, allowNegative) {
644
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
645
+ if (typed === undefined)
646
+ return;
647
+ const word = typed.replace(DASHES, "");
648
+ if (word.length < 2 && !typed.startsWith("--"))
649
+ return;
650
+ const known = Object.entries(options).flatMap(([name, option]) => [
651
+ ...option.short === undefined ? [] : [`-${option.short}`],
652
+ `--${name}`,
653
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
654
+ ]);
655
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
656
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
657
+ }
658
+ // ../kit/src/process.ts
659
+ import { constants } from "os";
660
+ import process6 from "process";
661
+ var KILL_GRACE_MS = 2000;
662
+ function exitCodeOf(code, signal) {
663
+ if (code !== null)
664
+ return code;
665
+ if (typeof signal === "number")
666
+ return 128 + signal;
667
+ return signal === null ? 129 : 128 + constants.signals[signal];
668
+ }
669
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
670
+ const chunks = [];
671
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
672
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
673
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
674
+ const timers = [];
675
+ const killGroup = (killing) => {
676
+ if (state.done)
677
+ return;
678
+ try {
679
+ if (grouped)
680
+ process6.kill(-proc.pid, killing);
681
+ else
682
+ proc.kill(killing);
683
+ } catch {}
684
+ };
685
+ const stop = () => {
686
+ killGroup("SIGTERM");
687
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
688
+ };
689
+ const onAbort = () => stop();
690
+ if (timeoutMs !== undefined) {
691
+ timers.push(setTimeout(() => {
692
+ state.timedOut = true;
693
+ stop();
694
+ }, timeoutMs));
695
+ }
696
+ if (signal?.aborted === true)
697
+ onAbort();
698
+ else
699
+ signal?.addEventListener("abort", onAbort, { once: true });
700
+ onStart?.({ kill: (killing) => killGroup(killing) });
701
+ const drain = async (stream, name) => {
702
+ for await (const data of stream) {
703
+ if (state.failure !== undefined)
704
+ continue;
705
+ try {
706
+ onChunk?.({ stream: name, data });
707
+ } catch (error) {
708
+ state.failure = error;
709
+ stop();
710
+ continue;
711
+ }
712
+ if (state.kept + data.length > maxBytes) {
713
+ state.truncated = true;
714
+ continue;
715
+ }
716
+ state.kept += data.length;
717
+ chunks.push({ stream: name, data });
718
+ }
719
+ };
720
+ try {
721
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
722
+ await proc.exited;
723
+ } finally {
724
+ state.done = true;
725
+ for (const timer of timers)
726
+ clearTimeout(timer);
727
+ signal?.removeEventListener("abort", onAbort);
728
+ }
729
+ if (state.failure !== undefined)
730
+ throw state.failure;
731
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
732
+ let output;
733
+ let text;
734
+ return {
735
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
736
+ chunks,
737
+ timedOut: state.timedOut,
738
+ truncated: state.truncated,
739
+ get output() {
740
+ return output ??= joined();
741
+ },
742
+ get text() {
743
+ return text ??= (output ??= joined()).toString();
744
+ }
745
+ };
746
+ }
747
+
748
+ // ../kit/src/progress.ts
749
+ var ESC = String.fromCharCode(27);
750
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
751
+ var RESET_STYLE = `${ESC}[0m`;
752
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
753
+ // ../kit/src/cli.ts
754
+ import process8 from "process";
755
+
756
+ // ../kit/src/usage.ts
757
+ import { appendFileSync, mkdirSync } from "fs";
758
+ import { homedir } from "os";
759
+ import { dirname, isAbsolute, join } from "path";
760
+ import process7 from "process";
761
+
762
+ // ../kit/src/logs.ts
763
+ var DAY_MS = 24 * 60 * 60 * 1000;
764
+ var CLI_FOLDER = "kaynooo-cli";
765
+
766
+ // ../kit/src/usage.ts
767
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
768
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
769
+ var LONGEST_NAME = 40;
770
+ var usageError;
771
+ function noteUsageError(message) {
772
+ usageError = message;
773
+ }
774
+ function stateHome(env = process7.env) {
775
+ const dir = env.XDG_STATE_HOME;
776
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
777
+ }
778
+ function usagePath(env = process7.env) {
779
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
780
+ }
781
+ function usageRecorded(env = process7.env) {
782
+ const off = env.KAYNOOO_CLI_NO_USAGE;
783
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
784
+ }
785
+ function flagNames(argv) {
786
+ const end = argv.indexOf("--");
787
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
788
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
789
+ }
790
+ function usageEntry(bin, command, argv, code, now = new Date) {
791
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
792
+ usageError = undefined;
793
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
794
+ }
795
+ function recordUsage(entry, env = process7.env) {
796
+ if (!usageRecorded(env))
797
+ return;
798
+ try {
799
+ const path = usagePath(env);
800
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
801
+ appendFileSync(path, `${JSON.stringify(entry)}
802
+ `, { mode: 384 });
803
+ } catch {}
804
+ }
805
+
806
+ // ../kit/src/cli.ts
807
+ var LEVEL_OPTIONS = {
808
+ ...OUTPUT_OPTIONS,
809
+ help: { type: "boolean", short: "h", description: "show this help" }
810
+ };
811
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
812
+ function printError(prefix, message, hint, cause) {
813
+ const colors = paint(process8.stderr);
814
+ const styled = takesControlCodes(process8.stderr);
815
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
816
+ const under = (label, text, tint) => text === undefined ? "" : `
817
+ ${styled ? tint(label) : `${label}:`} ${text}`;
818
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
819
+ }
820
+ function printJsonError(message, hint, cause) {
821
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
822
+ }
823
+ function wantsJson(argv) {
824
+ const end = argv.indexOf("--");
825
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
826
+ }
827
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
828
+ if (error instanceof HelpShown)
829
+ return 0;
830
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
831
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
832
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
833
+ if (error instanceof UsageError)
834
+ noteUsageError(error.message);
835
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
836
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
837
+ return error instanceof Exit ? error.code : 1;
838
+ }
839
+ var COMPLETE = "__complete";
840
+ var FILES = "__files__";
841
+ async function completingOf(run) {
842
+ completion.active = true;
843
+ try {
844
+ await run([]);
845
+ } catch (error) {
846
+ if (error instanceof Completing)
847
+ return error;
848
+ } finally {
849
+ completion.active = false;
850
+ }
851
+ return new Completing({});
852
+ }
853
+ function candidateLine(candidate) {
854
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
855
+ }
856
+ function positionalBeingTyped(before, { options, positionals }) {
857
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
858
+ let index = 0;
859
+ let at = 0;
860
+ while (at < before.length) {
861
+ const word = before[at];
862
+ if (word === "--") {
863
+ index += before.length - at - 1;
864
+ break;
865
+ }
866
+ if (!word.startsWith("-"))
867
+ index++;
868
+ else if (takesValue(word))
869
+ at++;
870
+ at++;
871
+ }
872
+ const last = positionals.at(-1);
873
+ if (index < positionals.length)
874
+ return positionals[index];
875
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
876
+ }
877
+ async function leafCandidates(run, words) {
878
+ const completing = await completingOf(run);
879
+ if ((words.at(-1) ?? "").startsWith("-"))
880
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
881
+ const flag = words.at(-2);
882
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
883
+ if (option?.type === "string") {
884
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
885
+ return values === undefined ? [FILES] : values.map(candidateLine);
886
+ }
887
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
888
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
889
+ return values === undefined ? [FILES] : values.map(candidateLine);
890
+ }
891
+ async function printCandidates(found) {
892
+ for (const line of await found)
893
+ console.log(line);
894
+ return 0;
895
+ }
896
+ async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
897
+ if (argv[0] === COMPLETE)
898
+ return printCandidates(leafCandidates(run, argv.slice(1)));
899
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
900
+ console.log(version);
901
+ return 0;
902
+ }
903
+ let code;
904
+ try {
905
+ code = await run(argv);
906
+ } catch (error) {
907
+ code = reportThrown(name, error, redact, wantsJson(argv));
908
+ }
909
+ if (usage !== false)
910
+ recordUsage(usageEntry(name, undefined, argv, code));
911
+ return code;
912
+ }
913
+ // ../kit/src/secrets.ts
914
+ var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
915
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
916
+ var WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
917
+ function isSecretName(name) {
918
+ return SECRET_PART.test(name) || name.split(WORD_BREAKS).some((word) => SECRET_WORDS.has(word.toLowerCase()));
919
+ }
920
+ // ../kit/src/sessions.ts
921
+ var {Glob } = globalThis.Bun;
922
+ var SESSION_FILES = new Glob("*.json");
923
+ var ACCOUNT_DIRS = new Glob("*/sessions");
924
+ // package.json
925
+ var version = "0.1.0";
926
+
927
+ // src/procs.ts
928
+ import { existsSync } from "fs";
929
+ import { homedir as homedir2 } from "os";
930
+ import process10 from "process";
931
+
932
+ // src/read.ts
933
+ import { readdir, readFile, readlink } from "fs/promises";
934
+
935
+ // src/parse.ts
936
+ var LISTENING = { tcp: "0A", udp: "07" };
937
+ var WHITESPACE = /\s+/;
938
+ var HEX_PAIR = /../g;
939
+ var SOCKET_LINK = /^socket:\[(\d+)\]$/;
940
+ var UNIT_SCOPE = /\.(?:service|scope)$/;
941
+ var CONTAINER_ID = /(?:docker-|libpod-|\/docker\/)([0-9a-f]{64})/;
942
+ var DOCKER_PORT = /:(\d+)(?:-(\d+))?->[\d-]+\/(tcp|udp)/;
943
+ function word(hex) {
944
+ const bytes = (hex.match(HEX_PAIR) ?? []).reverse().map((byte) => Number.parseInt(byte, 16));
945
+ return [bytes[0] << 8 | bytes[1], bytes[2] << 8 | bytes[3]];
946
+ }
947
+ function parseAddress(hex) {
948
+ if (hex.length === 8) {
949
+ const [high, low] = word(hex);
950
+ return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
951
+ }
952
+ const hextets = (hex.match(/.{8}/g) ?? []).flatMap(word);
953
+ if (hextets.length !== 8)
954
+ return hex;
955
+ if (hextets.slice(0, 5).every((part) => part === 0) && hextets[5] === 65535)
956
+ return `::ffff:${hextets[6] >> 8}.${hextets[6] & 255}.${hextets[7] >> 8}.${hextets[7] & 255}`;
957
+ return compress(hextets);
958
+ }
959
+ function compress(hextets) {
960
+ let best = { start: -1, length: 0 };
961
+ let run = { start: 0, length: 0 };
962
+ for (const [at, part] of hextets.entries()) {
963
+ run = part === 0 ? { start: run.length === 0 ? at : run.start, length: run.length + 1 } : { start: 0, length: 0 };
964
+ if (run.length > best.length)
965
+ best = run;
966
+ }
967
+ const text = (parts) => parts.map((part) => part.toString(16)).join(":");
968
+ if (best.length < 2)
969
+ return text(hextets);
970
+ return `${text(hextets.slice(0, best.start))}::${text(hextets.slice(best.start + best.length))}`;
971
+ }
972
+ function parseNetTable(text, protocol, family) {
973
+ const sockets = [];
974
+ for (const line of text.split(`
975
+ `).slice(1)) {
976
+ const columns = line.trim().split(WHITESPACE);
977
+ const [address = "", port = ""] = (columns[1] ?? "").split(":");
978
+ if (columns.length < 10 || columns[3] !== LISTENING[protocol])
979
+ continue;
980
+ const number = Number.parseInt(port, 16);
981
+ if (number === 0 || Number.isNaN(number))
982
+ continue;
983
+ sockets.push({ protocol, family, address: parseAddress(address), port: number, uid: Number(columns[7]), inode: Number(columns[9]) });
984
+ }
985
+ return sockets;
986
+ }
987
+ function socketInode(link) {
988
+ const match = SOCKET_LINK.exec(link);
989
+ return match === null ? undefined : Number(match[1]);
990
+ }
991
+ function parseStat(text) {
992
+ const open = text.indexOf("(");
993
+ const close = text.lastIndexOf(")");
994
+ if (open === -1 || close < open)
995
+ return;
996
+ const rest = text.slice(close + 2).trim().split(WHITESPACE);
997
+ const field = (number) => Number(rest[number - 3]);
998
+ if (rest.length < 20)
999
+ return;
1000
+ return { comm: text.slice(open + 1, close), state: rest[0], ppid: field(4), pgrp: field(5), session: field(6), tty: field(7), threads: field(20), startTicks: field(22) };
1001
+ }
1002
+ function parseStatus(text) {
1003
+ const fields = new Map;
1004
+ for (const line of text.split(`
1005
+ `)) {
1006
+ const colon = line.indexOf(":");
1007
+ if (colon > 0)
1008
+ fields.set(line.slice(0, colon), line.slice(colon + 1).trim());
1009
+ }
1010
+ return fields;
1011
+ }
1012
+ function statusBytes(fields, key) {
1013
+ const value = Number.parseInt(fields.get(key) ?? "", 10);
1014
+ return Number.isNaN(value) ? undefined : value * 1024;
1015
+ }
1016
+ function statusUid(fields) {
1017
+ const value = Number.parseInt(fields.get("Uid") ?? "", 10);
1018
+ return Number.isNaN(value) ? undefined : value;
1019
+ }
1020
+ var LIMIT_LINE = /^(\S+(?: \S+)*)\s{2,}(\S+)\s+(\S+)(?:\s+(\S+))?\s*$/;
1021
+ function parseLimits(text) {
1022
+ const limits = [];
1023
+ for (const line of text.split(`
1024
+ `).slice(1)) {
1025
+ const match = LIMIT_LINE.exec(line);
1026
+ if (match !== null)
1027
+ limits.push({ name: match[1], soft: match[2], hard: match[3], units: match[4] ?? "" });
1028
+ }
1029
+ return limits;
1030
+ }
1031
+ function parseCmdline(text) {
1032
+ return text.split("\x00").filter((_, at, parts) => at < parts.length - 1 || parts[at] !== "");
1033
+ }
1034
+ function parseEnviron(text) {
1035
+ return parseCmdline(text).map((entry) => {
1036
+ const equals = entry.indexOf("=");
1037
+ return equals === -1 ? [entry, ""] : [entry.slice(0, equals), entry.slice(equals + 1)];
1038
+ });
1039
+ }
1040
+ function parseCgroup(text) {
1041
+ return text.split(`
1042
+ `).filter((line) => line !== "").map((line) => {
1043
+ const [hierarchy = "", controllers = "", ...path] = line.split(":");
1044
+ return { hierarchy, controllers, path: path.join(":") };
1045
+ });
1046
+ }
1047
+ function cgroupUnit(entries) {
1048
+ const path = (entries.find((entry) => entry.hierarchy === "0") ?? entries[0])?.path ?? "";
1049
+ return path.split("/").reverse().find((part) => UNIT_SCOPE.test(part));
1050
+ }
1051
+ function cgroupContainer(entries) {
1052
+ for (const { path } of entries) {
1053
+ const match = CONTAINER_ID.exec(path);
1054
+ if (match !== null)
1055
+ return match[1];
1056
+ }
1057
+ return;
1058
+ }
1059
+ var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
1060
+ var SIZE_UNITS = { "": 1024 ** 2, k: 1024, m: 1024 ** 2, g: 1024 ** 3, t: 1024 ** 4 };
1061
+ function parseSize(text) {
1062
+ const match = SIZE.exec(text.trim());
1063
+ return match === null ? undefined : Math.round(Number(match[1]) * SIZE_UNITS[match[2].toLowerCase()]);
1064
+ }
1065
+ function userNameOf(passwd, uid) {
1066
+ for (const line of passwd.split(`
1067
+ `)) {
1068
+ const [name, , id] = line.split(":");
1069
+ if (id === String(uid) && name !== undefined && name !== "")
1070
+ return name;
1071
+ }
1072
+ return;
1073
+ }
1074
+ function parseDockerPs(text) {
1075
+ const containers = [];
1076
+ for (const line of text.split(`
1077
+ `)) {
1078
+ const [name = "", ports = "", project = "", service = ""] = line.split("\t");
1079
+ if (name === "")
1080
+ continue;
1081
+ const published = [];
1082
+ for (const entry of ports.split(",")) {
1083
+ const match = DOCKER_PORT.exec(entry);
1084
+ if (match === null)
1085
+ continue;
1086
+ const first = Number(match[1]);
1087
+ for (let host = first;host <= Number(match[2] ?? first); host++)
1088
+ published.push({ host, protocol: match[3] });
1089
+ }
1090
+ containers.push({ name, project: project === "" ? undefined : project, service: service === "" ? undefined : service, published });
1091
+ }
1092
+ return containers;
1093
+ }
1094
+
1095
+ // src/read.ts
1096
+ var CLOCK_TICKS = 100;
1097
+ async function text2(path) {
1098
+ try {
1099
+ return await readFile(path, "utf8");
1100
+ } catch {
1101
+ return;
1102
+ }
1103
+ }
1104
+ async function link(path) {
1105
+ try {
1106
+ return await readlink(path);
1107
+ } catch {
1108
+ return;
1109
+ }
1110
+ }
1111
+ var DIGITS = /^\d+$/;
1112
+ var BOOT_TIME = /^btime\s+(\d+)/m;
1113
+ async function listPids(root = "/proc") {
1114
+ return (await readdir(root)).filter((name) => DIGITS.test(name)).map(Number);
1115
+ }
1116
+ async function bootMs(root = "/proc") {
1117
+ const match = BOOT_TIME.exec(await text2(`${root}/stat`) ?? "");
1118
+ return match === null ? Date.now() : Number(match[1]) * 1000;
1119
+ }
1120
+ async function readProc(pid, boot, { root = "/proc", detail = true } = {}) {
1121
+ const dir = `${root}/${pid}`;
1122
+ const [statText, statusText, cmdline] = await Promise.all([text2(`${dir}/stat`), text2(`${dir}/status`), text2(`${dir}/cmdline`)]);
1123
+ const stat = statText === undefined ? undefined : parseStat(statText);
1124
+ if (stat === undefined || statusText === undefined)
1125
+ return;
1126
+ const status = parseStatus(statusText);
1127
+ const info = {
1128
+ pid,
1129
+ ppid: stat.ppid,
1130
+ comm: stat.comm,
1131
+ args: parseCmdline(cmdline ?? ""),
1132
+ uid: statusUid(status) ?? -1,
1133
+ state: stat.state,
1134
+ session: stat.session,
1135
+ rss: statusBytes(status, "VmRSS") ?? 0,
1136
+ startMs: boot + stat.startTicks / CLOCK_TICKS * 1000
1137
+ };
1138
+ if (!detail)
1139
+ return info;
1140
+ const [cwd, exe, cgroup] = await Promise.all([link(`${dir}/cwd`), link(`${dir}/exe`), text2(`${dir}/cgroup`)]);
1141
+ const groups = parseCgroup(cgroup ?? "");
1142
+ return { ...info, cwd, exe, unit: cgroupUnit(groups), container: cgroupContainer(groups) };
1143
+ }
1144
+ async function snapshot(root = "/proc", detailed = () => true) {
1145
+ const boot = await bootMs(root);
1146
+ const found = [];
1147
+ for (const pid of await listPids(root)) {
1148
+ const light = await readProc(pid, boot, { root, detail: false });
1149
+ if (light === undefined)
1150
+ continue;
1151
+ found.push(detailed(light.uid) ? await readProc(pid, boot, { root }) ?? light : light);
1152
+ }
1153
+ return found;
1154
+ }
1155
+ function ancestry(pid, byPid) {
1156
+ const chain = [];
1157
+ let at = pid;
1158
+ while (at !== undefined && at > 0 && !chain.includes(at)) {
1159
+ chain.push(at);
1160
+ at = byPid.get(at)?.ppid;
1161
+ }
1162
+ return chain;
1163
+ }
1164
+ async function readSockets(root = "/proc") {
1165
+ const tables = [["tcp", "tcp", 4], ["tcp6", "tcp", 6], ["udp", "udp", 4], ["udp6", "udp", 6]];
1166
+ const sockets = [];
1167
+ for (const [file, protocol, family] of tables)
1168
+ sockets.push(...parseNetTable(await text2(`${root}/net/${file}`) ?? "", protocol, family));
1169
+ return sockets;
1170
+ }
1171
+ async function socketsOf(pid, root = "/proc") {
1172
+ const inodes = new Set;
1173
+ try {
1174
+ for (const fd of await readdir(`${root}/${pid}/fd`)) {
1175
+ const inode = socketInode(await link(`${root}/${pid}/fd/${fd}`) ?? "");
1176
+ if (inode !== undefined)
1177
+ inodes.add(inode);
1178
+ }
1179
+ } catch {}
1180
+ return inodes;
1181
+ }
1182
+ async function socketOwners(root = "/proc") {
1183
+ const owners = new Map;
1184
+ for (const pid of await listPids(root)) {
1185
+ for (const inode of await socketsOf(pid, root))
1186
+ owners.set(inode, pid);
1187
+ }
1188
+ return owners;
1189
+ }
1190
+ async function fdCount(pid, root = "/proc") {
1191
+ try {
1192
+ return (await readdir(`${root}/${pid}/fd`)).length;
1193
+ } catch {
1194
+ return;
1195
+ }
1196
+ }
1197
+ var passwd;
1198
+ async function userName(uid) {
1199
+ passwd ??= await text2("/etc/passwd") ?? "";
1200
+ return userNameOf(passwd, uid);
1201
+ }
1202
+
1203
+ // src/kill.ts
1204
+ var SHELLS = new Set(["sh", "bash", "zsh", "fish", "dash", "ash", "nu", "tcsh", "ksh", "elvish", "xonsh"]);
1205
+ var TERMINALS = new Set(["kitty", "alacritty", "konsole", "wezterm-gui", "foot", "footclient", "xterm", "gnome-terminal-", "ghostty", "tmux: server", "tmux", "screen", "terminator", "tilix", "urxvt", "st", "yakuake", "ptyxis"]);
1206
+ function protectionOf(proc, { uid, mine }) {
1207
+ if (proc.pid === 1)
1208
+ return "pid 1";
1209
+ if (proc.uid !== uid)
1210
+ return "another user's process";
1211
+ if (mine.has(proc.pid))
1212
+ return "this command or one of its ancestors";
1213
+ if (SHELLS.has(proc.comm))
1214
+ return "a shell";
1215
+ return TERMINALS.has(proc.comm) ? "a terminal" : undefined;
1216
+ }
1217
+ var realSignaller = {
1218
+ send(pid, signal) {
1219
+ try {
1220
+ process.kill(pid, signal);
1221
+ return true;
1222
+ } catch {
1223
+ return false;
1224
+ }
1225
+ },
1226
+ async alive(pid) {
1227
+ const stat = await text2(`/proc/${pid}/stat`);
1228
+ return stat !== undefined && !stat.slice(stat.lastIndexOf(")") + 2).startsWith("Z");
1229
+ },
1230
+ sleep: async (ms) => Bun.sleep(ms)
1231
+ };
1232
+ var POLL_MS = 100;
1233
+ async function waitGone(pids, graceMs, signaller) {
1234
+ let alive = pids;
1235
+ let waited = 0;
1236
+ while (alive.length > 0 && waited < graceMs) {
1237
+ await signaller.sleep(POLL_MS);
1238
+ waited += POLL_MS;
1239
+ alive = await filterAlive(alive, signaller);
1240
+ }
1241
+ return alive;
1242
+ }
1243
+ async function filterAlive(pids, signaller) {
1244
+ const alive = [];
1245
+ for (const pid of pids) {
1246
+ if (await signaller.alive(pid))
1247
+ alive.push(pid);
1248
+ }
1249
+ return alive;
1250
+ }
1251
+ async function terminate(pids, { escalate, graceMs, signaller = realSignaller }) {
1252
+ const refused = pids.filter((pid) => !signaller.send(pid, "SIGTERM"));
1253
+ const sent = pids.filter((pid) => !refused.includes(pid));
1254
+ const remaining = await waitGone(sent, graceMs, signaller);
1255
+ const terminated = sent.filter((pid) => !remaining.includes(pid));
1256
+ if (!escalate || remaining.length === 0)
1257
+ return { terminated, killed: [], survived: [...refused, ...remaining] };
1258
+ for (const pid of remaining)
1259
+ signaller.send(pid, "SIGKILL");
1260
+ const stuck = await waitGone(remaining, 2000, signaller);
1261
+ return { terminated, killed: remaining.filter((pid) => !stuck.includes(pid)), survived: [...refused, ...stuck] };
1262
+ }
1263
+
1264
+ // src/mask.ts
1265
+ var MASK = "***";
1266
+ var URL_PASSWORD = /(?<![a-z0-9+.-])([a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:)[^\s'"@]{1,1024}@/gi;
1267
+ var TOKEN = /\b(?:gh[pousr]_|github_pat_|glpat-|sk-|xox[abprs]-|npm_|[sr]k_(?:live|test)_)[\w-]{10,}|\beyJ[\w-]+\.[\w-]+\.[\w-]+|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bBearer\s+[\w.~+/=-]{16,}/g;
1268
+ var OPAQUE = /(?<![\w-])(?=[\w-]{32,}(?![\w-]))(?=[\w-]*[A-Z])(?=[\w-]*\d)[\w-]+/gi;
1269
+ var PEM = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*/;
1270
+ function maskText(value) {
1271
+ return value.replace(PEM, MASK).replace(URL_PASSWORD, `$1${MASK}@`).replace(TOKEN, MASK).replace(OPAQUE, MASK);
1272
+ }
1273
+ function maskValue(name, value) {
1274
+ if (value === "")
1275
+ return value;
1276
+ return isSecretName(name) ? MASK : maskText(value);
1277
+ }
1278
+ function maskEnviron(entries) {
1279
+ return entries.map(([name, value]) => [name, maskValue(name, value)]);
1280
+ }
1281
+ var FLAG = /^-{1,2}([\w.-]+)(=|$)/;
1282
+ var ASSIGNMENT_NAME = /^[\w.-]+$/;
1283
+ function maskArgs(args) {
1284
+ let hidden = false;
1285
+ return args.map((arg) => {
1286
+ if (hidden) {
1287
+ hidden = false;
1288
+ return arg.startsWith("-") ? maskText(arg) : MASK;
1289
+ }
1290
+ const flag = FLAG.exec(arg);
1291
+ if (flag !== null) {
1292
+ if (flag[2] === "=")
1293
+ return isSecretName(flag[1]) ? `${arg.slice(0, flag[0].length)}${MASK}` : maskText(arg);
1294
+ hidden = isSecretName(flag[1]);
1295
+ return arg;
1296
+ }
1297
+ const equals = arg.indexOf("=");
1298
+ return equals > 0 && ASSIGNMENT_NAME.test(arg.slice(0, equals)) ? `${arg.slice(0, equals + 1)}${maskValue(arg.slice(0, equals), arg.slice(equals + 1))}` : maskText(arg);
1299
+ });
1300
+ }
1301
+
1302
+ // src/select.ts
1303
+ import { basename, join as join2, relative } from "path";
1304
+ var BROWSERS = /^(?:chrom(?:e|ium)(?:-browser)?|google-chrome(?:-stable|-beta|-unstable)?|chrome_crashpad_handler|chrome-headless-shell|headless_shell|chromium-headless-shell|brave|brave-browser|msedge|microsoft-edge|webkitwebprocess|webkitnetworkprocess|webkitgpuprocess|minibrowser|webkitwebdriver|wpewebprocess|wpenetworkprocess|bun-webview.*)$/i;
1305
+ var NATIVE = new Set(["rust-analyzer", "gopls", "clangd", "lua-language-server", "pyright-langserver", "pylsp", "intelephense", "phpactor", "tsgo", "esbuild", "biome", "ruff", "phpunit", "pytest", "vitest", "jest"]);
1306
+ var RUNTIMES = new Set(["node", "bun", "bunx", "deno", "nodejs"]);
1307
+ var SCRIPTS = new Set(["vite", "vitest", "nuxt", "nuxi", "next", "jest", "playwright", "playwright-core", "tsserver", "typescript-language-server", "vue-language-server", "vtsls", "eslint_d", "esbuild", "webpack", "turbo", "astro", "tsgo", "svelte-kit", "remix", "storybook", "biome", "prettierd", "tailwindcss", "bun-webview"]);
1308
+ var EXTENSION = /\.[cm]?[jt]s$/;
1309
+ var MARKERS = ["package.json", "composer.json", "Cargo.toml", "go.mod", "pyproject.toml"];
1310
+ var AUTOMATION = /^--(?:headless|remote-debugging-(?:pipe|port)|enable-automation)/;
1311
+ var HEAVY_DEFAULT = 500 * 1024 ** 2;
1312
+ function toolOf(proc) {
1313
+ const names = [proc.exe, proc.args[0], proc.comm].filter((name) => name !== undefined && name !== "").map((name) => basename(name));
1314
+ for (const name of names) {
1315
+ if (BROWSERS.test(name))
1316
+ return name.toLowerCase().startsWith("webkit") || name.toLowerCase().startsWith("wpe") || name.toLowerCase() === "minibrowser" ? "webkit" : "chromium";
1317
+ if (NATIVE.has(name))
1318
+ return name;
1319
+ }
1320
+ const runtime = names.find((name) => RUNTIMES.has(name));
1321
+ if (runtime === undefined)
1322
+ return;
1323
+ for (const arg of proc.args.slice(1)) {
1324
+ if (arg.startsWith("-"))
1325
+ continue;
1326
+ const script = basename(arg).replace(EXTENSION, "");
1327
+ if (SCRIPTS.has(script))
1328
+ return script;
1329
+ }
1330
+ return runtime === "nodejs" ? "node" : runtime;
1331
+ }
1332
+ function userDataDir(args) {
1333
+ const arg = args.find((word) => word.startsWith("--user-data-dir="));
1334
+ return arg?.slice("--user-data-dir=".length);
1335
+ }
1336
+ function projectOf(cwd, exists, home) {
1337
+ if (cwd === undefined || !cwd.startsWith(`${home}/`))
1338
+ return;
1339
+ const folders = [];
1340
+ for (let dir = cwd;dir.startsWith(`${home}/`); dir = join2(dir, ".."))
1341
+ folders.push(dir);
1342
+ return folders.find((dir) => exists(join2(dir, ".git"))) ?? folders.find((dir) => MARKERS.some((marker) => exists(join2(dir, marker))));
1343
+ }
1344
+ function isOrphan(proc, byPid) {
1345
+ if (proc.unit?.endsWith(".service") === true)
1346
+ return false;
1347
+ const parent = byPid.get(proc.ppid);
1348
+ const userManager = parent !== undefined && parent.comm === "systemd" && parent.uid === proc.uid && parent.uid !== 0;
1349
+ const reparented = proc.ppid === 1 || userManager;
1350
+ const tool = toolOf(proc);
1351
+ if (!reparented || tool !== "chromium" && tool !== "webkit")
1352
+ return reparented;
1353
+ if (basename(proc.exe ?? proc.args[0] ?? proc.comm).includes("crashpad"))
1354
+ return false;
1355
+ return proc.args.some((arg) => arg.startsWith("--type=")) || proc.args.some((arg) => AUTOMATION.test(arg));
1356
+ }
1357
+ function originOf(proc, tool, { exists, home }) {
1358
+ const profile = userDataDir(proc.args);
1359
+ if (profile !== undefined)
1360
+ return { key: `profile:${profile}`, origin: `${tool} profile ${profile}`, kind: "profile" };
1361
+ const project = projectOf(proc.cwd, exists, home);
1362
+ if (project !== undefined)
1363
+ return { key: `project:${project}`, origin: `~/${relative(home, project)}`, kind: "project" };
1364
+ return { key: `command:${tool}`, origin: tool, kind: "command" };
1365
+ }
1366
+ function selectGroups(procs, options) {
1367
+ const byPid = new Map(procs.map((proc) => [proc.pid, proc]));
1368
+ const heavyFrom = options.minMem ?? HEAVY_DEFAULT;
1369
+ const candidates = procs.filter((proc) => proc.uid === options.guard.uid && proc.pid !== 1 && toolOf(proc) !== undefined);
1370
+ const chosen = new Map;
1371
+ let protectedCount = 0;
1372
+ for (const proc of candidates) {
1373
+ const ageMs = options.now - proc.startMs;
1374
+ const orphan = isOrphan(proc, byPid);
1375
+ const heavy = proc.rss >= heavyFrom;
1376
+ if (!(heavy || orphan && proc.rss >= (options.minMem ?? 0)) || ageMs < (options.olderMs ?? 0))
1377
+ continue;
1378
+ if (protectionOf(proc, options.guard) !== undefined) {
1379
+ protectedCount++;
1380
+ continue;
1381
+ }
1382
+ chosen.set(proc.pid, { orphan, heavy });
1383
+ }
1384
+ const profiles = new Set([...chosen.keys()].map((pid) => userDataDir(byPid.get(pid).args)).filter((dir) => dir !== undefined));
1385
+ let grew = true;
1386
+ while (grew) {
1387
+ grew = false;
1388
+ for (const proc of candidates) {
1389
+ const dir = userDataDir(proc.args);
1390
+ const joins = chosen.has(proc.ppid) || dir !== undefined && profiles.has(dir);
1391
+ if (chosen.has(proc.pid) || !joins || protectionOf(proc, options.guard) !== undefined)
1392
+ continue;
1393
+ chosen.set(proc.pid, { orphan: isOrphan(proc, byPid), heavy: proc.rss >= heavyFrom });
1394
+ grew = true;
1395
+ }
1396
+ }
1397
+ const groups = new Map;
1398
+ for (const [pid, flags] of chosen) {
1399
+ const proc = byPid.get(pid);
1400
+ const tool = toolOf(proc);
1401
+ const { key, origin, kind } = originOf(proc, tool, options);
1402
+ const group = groups.get(key) ?? { key, origin, kind, members: [], rss: 0, oldestMs: 0, orphans: 0 };
1403
+ const ageMs = options.now - proc.startMs;
1404
+ group.members.push({ proc, tool, ageMs, ...flags });
1405
+ group.rss += proc.rss;
1406
+ group.oldestMs = Math.max(group.oldestMs, ageMs);
1407
+ group.orphans += flags.orphan ? 1 : 0;
1408
+ groups.set(key, group);
1409
+ }
1410
+ for (const group of groups.values())
1411
+ group.members.sort((a, b) => a.proc.pid - b.proc.pid);
1412
+ return { groups: [...groups.values()].sort((a, b) => b.rss - a.rss), protectedCount };
1413
+ }
1414
+
1415
+ // src/procs.ts
1416
+ var usage2 = `procs
1417
+
1418
+ Lists the leftover or heavy processes of the calling user that are worth cleaning, grouped by origin: the project folder their working directory is in, a browser profile for a chromium and its helpers, else their command. Each group shows its process count, total resident memory and oldest age.
1419
+ A process is listed when it is a dev tool (bun, node, vite, nuxt, next, chromium and chrome, playwright and webview browsers and their helpers, language servers, test runners) and either an orphan, reparented to init or to the user's systemd, or heavy (500M resident by default). The processes below a listed one, and those sharing a browser profile with it, are listed too, so a chromium whose main process was killed groups with its leftover helpers.
1420
+ \`--kill\` is a dry run that names what it would stop unless --yes is given; it sends SIGTERM, then SIGKILL after --grace to what is still there. It never signals pid 1, shells, terminals, this command and its ancestors, or processes of other users.
1421
+
1422
+ Exits 0 when it listed or stopped everything, 1 when a process survived SIGKILL, 2 on a usage error.`;
1423
+ var options = {
1424
+ json: jsonOption("{ groups: [{ origin, kind, count, rss, oldestSeconds, tools, orphans, pids, processes }], skipped }"),
1425
+ kill: { type: "boolean", description: "stop the listed processes: a dry run without --yes" },
1426
+ yes: { type: "boolean", short: "y", description: "with --kill, really stop them, without asking" },
1427
+ "min-mem": { type: "string", description: "heavy from this resident size (500M), and the least a left over process must use to be listed; a bare number counts megabytes" },
1428
+ older: { type: "string", description: "only processes at least this old: 30m, 2h, 1d" },
1429
+ grace: { type: "string", description: "how long SIGTERM gets before SIGKILL (5s)" }
1430
+ };
1431
+ function summary(group) {
1432
+ const tools = {};
1433
+ for (const { tool } of group.members)
1434
+ tools[tool] = (tools[tool] ?? 0) + 1;
1435
+ return {
1436
+ origin: group.origin,
1437
+ kind: group.kind,
1438
+ count: group.members.length,
1439
+ rss: group.rss,
1440
+ oldestSeconds: Math.round(group.oldestMs / 1000),
1441
+ tools,
1442
+ orphans: group.orphans,
1443
+ pids: group.members.map(({ proc }) => proc.pid),
1444
+ processes: group.members.map(({ proc, tool, orphan, heavy, ageMs }) => ({ pid: proc.pid, ppid: proc.ppid, tool, command: maskArgs(proc.args).join(" ") || proc.comm, cwd: proc.cwd, rss: proc.rss, ageSeconds: Math.round(ageMs / 1000), orphan, heavy }))
1445
+ };
1446
+ }
1447
+ function render(groups) {
1448
+ const colors = paint(process10.stdout);
1449
+ const rows = groups.map((group) => [
1450
+ group.origin,
1451
+ String(group.members.length),
1452
+ $e(group.rss),
1453
+ formatSeconds(group.oldestMs / 1000),
1454
+ colors.dim(truncate(Object.entries(Object.groupBy(group.members, ({ tool }) => tool)).map(([tool, list]) => `${tool}${list.length > 1 ? ` x${list.length}` : ""}`).join(", "), 50)),
1455
+ group.orphans === 0 ? "" : colors.yellow(`${group.orphans} orphaned`)
1456
+ ]);
1457
+ return table([["ORIGIN", "PROCS", "RSS", "OLDEST", "WHAT", ""], ...rows], { header: true, align: ["left", "right", "right", "right"] });
1458
+ }
1459
+ async function procs(args) {
1460
+ const { values } = parse(args, usage2, options, {
1461
+ replaces: "pkill -f and pgrep -f one-liners (which match their own shell), ps aux | grep for leftover chromium, bun or vite processes",
1462
+ examples: [
1463
+ ["procs", "leftover and heavy dev processes, by origin"],
1464
+ ["procs --min-mem 1G --older 1h", "only the big ones that have run a while"],
1465
+ ["procs --kill", "dry run: what would be stopped"],
1466
+ "procs --kill --yes"
1467
+ ]
1468
+ });
1469
+ const minMem = values["min-mem"] === undefined ? undefined : parseSize(values["min-mem"]);
1470
+ if (values["min-mem"] !== undefined && minMem === undefined)
1471
+ fail(`--min-mem takes a size such as 500M or 1.5G, not ${values["min-mem"]}`, 2);
1472
+ const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0, "m");
1473
+ const uid = process10.getuid?.() ?? -1;
1474
+ const all = await snapshot("/proc", (owner) => owner === uid);
1475
+ const mine = new Set(ancestry(process10.pid, new Map(all.map((proc) => [proc.pid, proc]))));
1476
+ const { groups, protectedCount } = selectGroups(all, { guard: { uid, mine }, now: Date.now(), home: homedir2(), exists: existsSync, minMem, olderMs });
1477
+ const pids = groups.flatMap((group) => group.members.map(({ proc }) => proc.pid));
1478
+ const show = (extra = {}) => {
1479
+ if (values.json === true)
1480
+ printJson({ groups: groups.map(summary), skipped: protectedCount, ...extra });
1481
+ else
1482
+ console.log(groups.length === 0 ? "nothing to clean" : render(groups));
1483
+ };
1484
+ if (values.kill !== true || pids.length === 0 || values.yes !== true) {
1485
+ show();
1486
+ if (values.json !== true && protectedCount > 0)
1487
+ console.error(paint(process10.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`));
1488
+ if (values.kill === true && pids.length > 0)
1489
+ console.error(`dry run: would stop ${pids.length} ${pids.length === 1 ? "process" : "processes"} (${pids.join(" ")}), pass --yes to do it`);
1490
+ return 0;
1491
+ }
1492
+ const outcome = await terminate(pids, { escalate: true, graceMs: duration(values.grace, "grace", 5000) });
1493
+ show({ stopped: [...outcome.terminated, ...outcome.killed], killed: outcome.killed, survived: outcome.survived });
1494
+ if (values.json !== true)
1495
+ console.log(`stopped ${outcome.terminated.length + outcome.killed.length} of ${pids.length}${outcome.killed.length === 0 ? "" : `, ${outcome.killed.length} needed SIGKILL`}`);
1496
+ if (outcome.survived.length > 0)
1497
+ console.error(`still running: ${outcome.survived.join(" ")}`);
1498
+ return outcome.survived.length === 0 ? 0 : 1;
1499
+ }
1500
+
1501
+ // src/procs-cli.ts
1502
+ process11.exitCode = await runMain({ name: "procs", version, run: procs });