@kaynooo/cli-proc 0.2.1 → 0.4.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/README.md +1 -1
- package/dist/pid-cli.js +310 -45
- package/dist/ports-cli.js +396 -65
- package/dist/proc-cli.js +2262 -0
- package/dist/procs-cli.js +317 -49
- package/package.json +5 -3
- package/src/ports.ts +7 -2
- package/src/proc-cli.ts +19 -0
- package/src/procs.ts +6 -2
package/dist/proc-cli.js
ADDED
|
@@ -0,0 +1,2262 @@
|
|
|
1
|
+
#!/usr/bin/env -S bun --no-env-file
|
|
2
|
+
// @bun
|
|
3
|
+
|
|
4
|
+
// src/proc-cli.ts
|
|
5
|
+
import process16 from "process";
|
|
6
|
+
// ../kit/src/args.ts
|
|
7
|
+
import process6 from "process";
|
|
8
|
+
import { parseArgs } from "util";
|
|
9
|
+
|
|
10
|
+
// ../kit/src/format.ts
|
|
11
|
+
import process4 from "process";
|
|
12
|
+
|
|
13
|
+
// ../kit/src/mode.ts
|
|
14
|
+
import process2 from "process";
|
|
15
|
+
var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
16
|
+
var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
17
|
+
function isSet(value) {
|
|
18
|
+
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
19
|
+
}
|
|
20
|
+
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
21
|
+
const chosen = env.KIT_MODE;
|
|
22
|
+
if (chosen !== undefined && MODES.has(chosen))
|
|
23
|
+
return chosen;
|
|
24
|
+
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
25
|
+
return "agent";
|
|
26
|
+
if (stream.isTTY === true)
|
|
27
|
+
return "terminal";
|
|
28
|
+
return isSet(env.CI) ? "ci" : "pipe";
|
|
29
|
+
}
|
|
30
|
+
function isInteractive(streams = process2) {
|
|
31
|
+
return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// ../kit/src/style.ts
|
|
35
|
+
import process3 from "process";
|
|
36
|
+
|
|
37
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
38
|
+
function x(s) {
|
|
39
|
+
let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
|
|
40
|
+
if (!/^[a-f0-9]+$/.test(r))
|
|
41
|
+
return [0, 0, 0];
|
|
42
|
+
let t = r.length, n = (c) => Number.parseInt(c, 16);
|
|
43
|
+
if (t === 3 || t === 4) {
|
|
44
|
+
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;
|
|
45
|
+
return g !== undefined ? [c, u, h, g] : [c, u, h];
|
|
46
|
+
}
|
|
47
|
+
if (t !== 6 && t !== 8)
|
|
48
|
+
throw Error(`Invalid hex color length: ${t}`);
|
|
49
|
+
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;
|
|
50
|
+
if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
|
|
51
|
+
throw Error(`Invalid hex color value: ${s}`);
|
|
52
|
+
return y !== undefined ? [a, b, o, y] : [a, b, o];
|
|
53
|
+
}
|
|
54
|
+
function A(s) {
|
|
55
|
+
let [r, t, n, a] = s;
|
|
56
|
+
if (a)
|
|
57
|
+
return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
|
|
58
|
+
return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
|
|
59
|
+
}
|
|
60
|
+
function R(s, r, t) {
|
|
61
|
+
s = (s % 360 + 360) % 360, t /= 100;
|
|
62
|
+
let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
|
|
63
|
+
let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
|
|
64
|
+
return Math.round(255 * y);
|
|
65
|
+
};
|
|
66
|
+
return [a(0), a(8), a(4)];
|
|
67
|
+
}
|
|
68
|
+
function k(s) {
|
|
69
|
+
let [r, t, n] = s;
|
|
70
|
+
r /= 255, t /= 255, n /= 255;
|
|
71
|
+
let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
|
|
72
|
+
if (a !== b) {
|
|
73
|
+
let u = a - b;
|
|
74
|
+
if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
|
|
75
|
+
o = (t - n) / u + (t < n ? 6 : 0);
|
|
76
|
+
else if (a === t)
|
|
77
|
+
o = (n - r) / u + 2;
|
|
78
|
+
else
|
|
79
|
+
o = (r - t) / u + 4;
|
|
80
|
+
o /= 6;
|
|
81
|
+
}
|
|
82
|
+
return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
|
|
83
|
+
}
|
|
84
|
+
function H(s, r, t) {
|
|
85
|
+
s = (s % 360 + 360) % 360, r /= 100, t /= 100;
|
|
86
|
+
let n = (a) => {
|
|
87
|
+
let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
|
|
88
|
+
return Math.round(255 * o);
|
|
89
|
+
};
|
|
90
|
+
return [n(5), n(3), n(1)];
|
|
91
|
+
}
|
|
92
|
+
function f(s) {
|
|
93
|
+
let [r, t, n] = s;
|
|
94
|
+
r /= 255, t /= 255, n /= 255;
|
|
95
|
+
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;
|
|
96
|
+
if (o !== 0) {
|
|
97
|
+
if (a === r)
|
|
98
|
+
y = (t - n) / o + (t < n ? 6 : 0);
|
|
99
|
+
else if (a === t)
|
|
100
|
+
y = (n - r) / o + 2;
|
|
101
|
+
else
|
|
102
|
+
y = (r - t) / o + 4;
|
|
103
|
+
y /= 6;
|
|
104
|
+
}
|
|
105
|
+
return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
|
|
106
|
+
}
|
|
107
|
+
function O(s) {
|
|
108
|
+
let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
|
|
109
|
+
if (a === 1)
|
|
110
|
+
return [0, 0, 0, 100];
|
|
111
|
+
let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
|
|
112
|
+
return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
|
|
113
|
+
}
|
|
114
|
+
function v(s, r, t, n) {
|
|
115
|
+
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))];
|
|
116
|
+
}
|
|
117
|
+
var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
|
118
|
+
var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
|
|
119
|
+
var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
|
|
120
|
+
function T(s) {
|
|
121
|
+
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);
|
|
122
|
+
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)];
|
|
123
|
+
}
|
|
124
|
+
function M(s, r, t) {
|
|
125
|
+
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)));
|
|
126
|
+
return [u(o), u(y), u(c)];
|
|
127
|
+
}
|
|
128
|
+
function d(s) {
|
|
129
|
+
let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
|
|
130
|
+
return [i(r, 4), i(a, 4), i(b, 2)];
|
|
131
|
+
}
|
|
132
|
+
function C(s, r, t) {
|
|
133
|
+
let n = t * Math.PI / 180;
|
|
134
|
+
return M(s, r * Math.cos(n), r * Math.sin(n));
|
|
135
|
+
}
|
|
136
|
+
function l(s) {
|
|
137
|
+
let r = s / 255;
|
|
138
|
+
return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
class e {
|
|
142
|
+
r;
|
|
143
|
+
g;
|
|
144
|
+
b;
|
|
145
|
+
a;
|
|
146
|
+
constructor(s, r, t, n = 1) {
|
|
147
|
+
this.r = s, this.g = r, this.b = t, this.a = n;
|
|
148
|
+
}
|
|
149
|
+
static from(s, r) {
|
|
150
|
+
if (s === "hex") {
|
|
151
|
+
let [t, n, a, b] = x(r);
|
|
152
|
+
return new e(t, n, a, b);
|
|
153
|
+
}
|
|
154
|
+
if (s === "rgb") {
|
|
155
|
+
if (Array.isArray(r)) {
|
|
156
|
+
let [o, y, c, u] = r;
|
|
157
|
+
return new e(o, y, c, u);
|
|
158
|
+
}
|
|
159
|
+
let { r: t, g: n, b: a, a: b } = r;
|
|
160
|
+
return new e(t, n, a, b);
|
|
161
|
+
}
|
|
162
|
+
if (s === "hsl") {
|
|
163
|
+
let t, n, a, b;
|
|
164
|
+
if (Array.isArray(r))
|
|
165
|
+
[t, n, a, b] = r;
|
|
166
|
+
else
|
|
167
|
+
({ h: t, s: n, l: a, a: b } = r);
|
|
168
|
+
let [o, y, c] = R(t, n, a);
|
|
169
|
+
return new e(o, y, c, b);
|
|
170
|
+
}
|
|
171
|
+
if (s === "hsv") {
|
|
172
|
+
let t, n, a, b;
|
|
173
|
+
if (Array.isArray(r))
|
|
174
|
+
[t, n, a, b] = r;
|
|
175
|
+
else
|
|
176
|
+
({ h: t, s: n, v: a, a: b } = r);
|
|
177
|
+
let [o, y, c] = H(t, n, a);
|
|
178
|
+
return new e(o, y, c, b);
|
|
179
|
+
}
|
|
180
|
+
if (s === "cmyk") {
|
|
181
|
+
let t, n, a, b, o;
|
|
182
|
+
if (Array.isArray(r))
|
|
183
|
+
[t, n, a, b, o] = r;
|
|
184
|
+
else
|
|
185
|
+
({ c: t, m: n, y: a, k: b, a: o } = r);
|
|
186
|
+
let [y, c, u] = v(t, n, a, b);
|
|
187
|
+
return new e(y, c, u, o);
|
|
188
|
+
}
|
|
189
|
+
if (s === "oklch") {
|
|
190
|
+
let t, n, a, b;
|
|
191
|
+
if (Array.isArray(r))
|
|
192
|
+
[t, n, a, b] = r;
|
|
193
|
+
else
|
|
194
|
+
({ l: t, c: n, h: a, a: b } = r);
|
|
195
|
+
let [o, y, c] = C(t, n, a);
|
|
196
|
+
return new e(o, y, c, b);
|
|
197
|
+
}
|
|
198
|
+
if (s === "oklab") {
|
|
199
|
+
let t, n, a, b;
|
|
200
|
+
if (Array.isArray(r))
|
|
201
|
+
[t, n, a, b] = r;
|
|
202
|
+
else
|
|
203
|
+
({ l: t, a: n, b: a, alpha: b } = r);
|
|
204
|
+
let [o, y, c] = M(t, n, a);
|
|
205
|
+
return new e(o, y, c, b);
|
|
206
|
+
}
|
|
207
|
+
throw Error("Invalid input");
|
|
208
|
+
}
|
|
209
|
+
to(s) {
|
|
210
|
+
switch (s) {
|
|
211
|
+
case "rgb":
|
|
212
|
+
return [this.r, this.g, this.b];
|
|
213
|
+
case "rgba":
|
|
214
|
+
return [this.r, this.g, this.b, this.a];
|
|
215
|
+
case "hex":
|
|
216
|
+
return A([this.r, this.g, this.b]);
|
|
217
|
+
case "hexa":
|
|
218
|
+
return A([this.r, this.g, this.b, this.a]);
|
|
219
|
+
case "hsl":
|
|
220
|
+
return k([this.r, this.g, this.b]);
|
|
221
|
+
case "hsla":
|
|
222
|
+
return [...k([this.r, this.g, this.b]), this.a];
|
|
223
|
+
case "hsv":
|
|
224
|
+
return f([this.r, this.g, this.b]);
|
|
225
|
+
case "hsva":
|
|
226
|
+
return [...f([this.r, this.g, this.b]), this.a];
|
|
227
|
+
case "cmyk":
|
|
228
|
+
return O([this.r, this.g, this.b]);
|
|
229
|
+
case "cmyka":
|
|
230
|
+
return [...O([this.r, this.g, this.b]), this.a];
|
|
231
|
+
case "oklch":
|
|
232
|
+
return d([this.r, this.g, this.b]);
|
|
233
|
+
case "oklcha":
|
|
234
|
+
return [...d([this.r, this.g, this.b]), this.a];
|
|
235
|
+
case "oklab":
|
|
236
|
+
return T([this.r, this.g, this.b]);
|
|
237
|
+
case "oklaba":
|
|
238
|
+
return [...T([this.r, this.g, this.b]), this.a];
|
|
239
|
+
default:
|
|
240
|
+
return [this.r, this.g, this.b];
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
getLuminance() {
|
|
244
|
+
let s = l(this.r), r = l(this.g), t = l(this.b);
|
|
245
|
+
return 0.2126 * s + 0.7152 * r + 0.0722 * t;
|
|
246
|
+
}
|
|
247
|
+
contrastRatio(s) {
|
|
248
|
+
let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
|
|
249
|
+
return (n + 0.05) / (a + 0.05);
|
|
250
|
+
}
|
|
251
|
+
bestContrastForeground() {
|
|
252
|
+
let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
|
|
253
|
+
return t >= n ? s : r;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
|
|
258
|
+
var r = 39;
|
|
259
|
+
var o = 49;
|
|
260
|
+
var f2 = "\x1B[";
|
|
261
|
+
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") => {
|
|
262
|
+
let [a, l, s] = e.from("hex", i).to("rgb");
|
|
263
|
+
return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
|
|
264
|
+
}, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
|
|
265
|
+
var b = new Set(["", "1", "2", "3", "true"]);
|
|
266
|
+
function h(i, n = globalThis.process?.env ?? {}) {
|
|
267
|
+
if (n.FORCE_COLOR !== undefined)
|
|
268
|
+
return b.has(n.FORCE_COLOR);
|
|
269
|
+
if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
|
|
270
|
+
return false;
|
|
271
|
+
return i?.isTTY === true;
|
|
272
|
+
}
|
|
273
|
+
function d2(i, n, a) {
|
|
274
|
+
if (!h(a.stream ?? globalThis.process?.stdout, a.env))
|
|
275
|
+
return n;
|
|
276
|
+
let l = "", s = "";
|
|
277
|
+
for (let g = 0, y = i.length;g < y; g++) {
|
|
278
|
+
let [c, p] = i[g];
|
|
279
|
+
l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
|
|
280
|
+
}
|
|
281
|
+
return l + n + s;
|
|
282
|
+
}
|
|
283
|
+
function u(i, n = []) {
|
|
284
|
+
return new Proxy((l) => d2(n, l, i), { get(l, s) {
|
|
285
|
+
let g = C2[s];
|
|
286
|
+
if (Array.isArray(g))
|
|
287
|
+
return u(i, [...n, g]);
|
|
288
|
+
if (typeof g === "function")
|
|
289
|
+
return (...y) => u(i, [...n, g(...y)]);
|
|
290
|
+
throw Error(`Unknown style: ${String(s)}`);
|
|
291
|
+
} });
|
|
292
|
+
}
|
|
293
|
+
function le(i = {}) {
|
|
294
|
+
return u(i);
|
|
295
|
+
}
|
|
296
|
+
var t = le();
|
|
297
|
+
|
|
298
|
+
// ../kit/src/theme.ts
|
|
299
|
+
var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
|
|
300
|
+
var MAX_FILE_BYTES = 64 * 1024;
|
|
301
|
+
var warned = new Set;
|
|
302
|
+
|
|
303
|
+
// ../kit/src/style.ts
|
|
304
|
+
function takesControlCodes(stream, env = process3.env) {
|
|
305
|
+
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
306
|
+
}
|
|
307
|
+
function paint(stream, env = process3.env) {
|
|
308
|
+
return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
309
|
+
}
|
|
310
|
+
var STATUS_WORDS = {
|
|
311
|
+
passed: ["passed", "success", "succeeded", "ok"],
|
|
312
|
+
failed: ["failed", "failure", "error", "errored"],
|
|
313
|
+
running: ["running", "in_progress", "started", "holding"],
|
|
314
|
+
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
315
|
+
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
316
|
+
};
|
|
317
|
+
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
318
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-hrsswv1w.js
|
|
319
|
+
function $e(t, e = false, i = 1) {
|
|
320
|
+
let n = typeof e === "object" ? e : { units: e ? "si" : "iec", dp: i }, { units: s = "iec", dp: u = 1 } = n, r = s === "si" ? 1000 : 1024;
|
|
321
|
+
if (Math.abs(t) < r)
|
|
322
|
+
return `${t} B`;
|
|
323
|
+
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;
|
|
324
|
+
do
|
|
325
|
+
t /= r, ++o;
|
|
326
|
+
while (Math.round(Math.abs(t) * l) / l >= r && o < c.length - 1);
|
|
327
|
+
return `${t.toFixed(u)} ${c[o]}`;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// ../kit/src/format.ts
|
|
331
|
+
var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
332
|
+
function formatSeconds(total) {
|
|
333
|
+
let rest = Math.max(0, Math.round(total));
|
|
334
|
+
const amounts = UNITS.map(([unit, size]) => {
|
|
335
|
+
const amount = Math.floor(rest / size);
|
|
336
|
+
rest -= amount * size;
|
|
337
|
+
return `${amount}${unit}`;
|
|
338
|
+
});
|
|
339
|
+
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
340
|
+
if (first === -1)
|
|
341
|
+
return "0s";
|
|
342
|
+
const next = amounts[first + 1];
|
|
343
|
+
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
344
|
+
}
|
|
345
|
+
function upTo(text, separator) {
|
|
346
|
+
const end = text.indexOf(separator);
|
|
347
|
+
return end === -1 ? text : text.slice(0, end);
|
|
348
|
+
}
|
|
349
|
+
function truncate(text, width) {
|
|
350
|
+
return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
|
|
351
|
+
}
|
|
352
|
+
var LINE_BREAKS = /\s*\n\s*/g;
|
|
353
|
+
var ESCAPE = String.fromCharCode(27);
|
|
354
|
+
function textWidth(text) {
|
|
355
|
+
return Bun.stringWidth(text);
|
|
356
|
+
}
|
|
357
|
+
function table(rows, { cellWidth, header = false, align = [], fit, stream = process4.stdout, env = process4.env } = {}) {
|
|
358
|
+
const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
|
|
359
|
+
if (outputMode(stream, env) === "agent")
|
|
360
|
+
return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
|
|
361
|
+
`);
|
|
362
|
+
const widths = [];
|
|
363
|
+
for (const row of cells) {
|
|
364
|
+
for (const [index, cell] of row.entries())
|
|
365
|
+
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
366
|
+
}
|
|
367
|
+
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
368
|
+
const colors = paint(stream);
|
|
369
|
+
const lines = shown.map((row) => row.map((cell, index) => {
|
|
370
|
+
const width = widths[index] ?? 0;
|
|
371
|
+
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
372
|
+
if (align[index] === "right")
|
|
373
|
+
return `${gap}${cell}`;
|
|
374
|
+
return index === row.length - 1 ? cell : `${cell}${gap}`;
|
|
375
|
+
}).join(" ").trimEnd());
|
|
376
|
+
const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
|
|
377
|
+
return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
|
|
378
|
+
`);
|
|
379
|
+
}
|
|
380
|
+
function narrow(rows, widths, limit) {
|
|
381
|
+
const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
|
|
382
|
+
const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
|
|
383
|
+
const floor = 8;
|
|
384
|
+
while (used() > limit) {
|
|
385
|
+
let widest = -1;
|
|
386
|
+
for (const [index, width] of widths.entries()) {
|
|
387
|
+
if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
|
|
388
|
+
widest = index;
|
|
389
|
+
}
|
|
390
|
+
if (widest === -1)
|
|
391
|
+
break;
|
|
392
|
+
widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
|
|
393
|
+
}
|
|
394
|
+
return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
|
|
395
|
+
}
|
|
396
|
+
function jsonText(value, replacer, { stream = process4.stdout, env = process4.env } = {}) {
|
|
397
|
+
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
398
|
+
}
|
|
399
|
+
function printJson(value) {
|
|
400
|
+
console.log(jsonText(value));
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// ../kit/src/help.ts
|
|
404
|
+
import process5 from "process";
|
|
405
|
+
var OPTIONAL = /\[[^\]]+\]/g;
|
|
406
|
+
var USAGE_PREFIX = /^usage:\s*/i;
|
|
407
|
+
var FULL_STOP = /\.$/;
|
|
408
|
+
function usageLine(usage, colors = paint(process5.stdout)) {
|
|
409
|
+
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
410
|
+
}
|
|
411
|
+
function helpText(usage, options, colors = paint(process5.stdout), { examples = [], replaces, exits = [] } = {}) {
|
|
412
|
+
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
413
|
+
`);
|
|
414
|
+
}
|
|
415
|
+
function exitRows(exits, colors = paint(process5.stdout)) {
|
|
416
|
+
if (exits.length === 0)
|
|
417
|
+
return [];
|
|
418
|
+
const width = Math.max(...exits.map(([code]) => String(code).length));
|
|
419
|
+
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
420
|
+
}
|
|
421
|
+
function replacesRows(replaces, colors = paint(process5.stdout)) {
|
|
422
|
+
return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
423
|
+
}
|
|
424
|
+
function wantsHelpJson(env = process5.env) {
|
|
425
|
+
return env.KIT_HELP === "json";
|
|
426
|
+
}
|
|
427
|
+
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
428
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
429
|
+
`);
|
|
430
|
+
const first = lines[0];
|
|
431
|
+
const colon = first.indexOf(": ");
|
|
432
|
+
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
433
|
+
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
434
|
+
return {
|
|
435
|
+
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
436
|
+
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
437
|
+
...replaces === undefined ? {} : { replaces },
|
|
438
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
439
|
+
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
440
|
+
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
function exampleRows(examples, colors = paint(process5.stdout)) {
|
|
444
|
+
if (examples.length === 0 || outputMode() === "agent")
|
|
445
|
+
return [];
|
|
446
|
+
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
447
|
+
}
|
|
448
|
+
function optionRows(options, colors = paint(process5.stdout)) {
|
|
449
|
+
const rows = Object.entries(options).map(([name, option]) => {
|
|
450
|
+
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
451
|
+
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
452
|
+
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
453
|
+
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
454
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
|
|
455
|
+
});
|
|
456
|
+
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
457
|
+
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// ../kit/src/text.ts
|
|
461
|
+
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
462
|
+
function distance(a, b) {
|
|
463
|
+
let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
|
|
464
|
+
for (const [i, left] of [...a].entries()) {
|
|
465
|
+
const current = [i + 1];
|
|
466
|
+
for (const [j, right] of [...b].entries())
|
|
467
|
+
current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
|
|
468
|
+
previous = current;
|
|
469
|
+
}
|
|
470
|
+
return previous[b.length] ?? 0;
|
|
471
|
+
}
|
|
472
|
+
function closest(name, names) {
|
|
473
|
+
const started = names.find((known) => known.startsWith(name));
|
|
474
|
+
if (started !== undefined)
|
|
475
|
+
return started;
|
|
476
|
+
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
477
|
+
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
478
|
+
}
|
|
479
|
+
// ../kit/src/input.ts
|
|
480
|
+
var WHOLE = /^\d+$/;
|
|
481
|
+
function wholeNumber(value, name, fallback, min = 1) {
|
|
482
|
+
if (value === undefined)
|
|
483
|
+
return fallback;
|
|
484
|
+
const number = Number(value);
|
|
485
|
+
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
486
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
487
|
+
return number;
|
|
488
|
+
}
|
|
489
|
+
var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
|
|
490
|
+
var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
|
|
491
|
+
function duration(value, name, fallback, unit = "s") {
|
|
492
|
+
if (value === undefined)
|
|
493
|
+
return fallback;
|
|
494
|
+
const match = DURATION.exec(value.trim());
|
|
495
|
+
const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
|
|
496
|
+
if (ms < 1)
|
|
497
|
+
badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
|
|
498
|
+
return ms;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// ../kit/src/args.ts
|
|
502
|
+
var DASHES = /^-+/;
|
|
503
|
+
function jsonOption(holds) {
|
|
504
|
+
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
505
|
+
}
|
|
506
|
+
class Exit extends Error {
|
|
507
|
+
code;
|
|
508
|
+
hint;
|
|
509
|
+
constructor(message, code, hint) {
|
|
510
|
+
super(message);
|
|
511
|
+
this.code = code;
|
|
512
|
+
this.hint = hint;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
function fail(message, code = 2, hint) {
|
|
516
|
+
throw new Exit(message, code, hint);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
class UsageError extends Exit {
|
|
520
|
+
constructor(message, hint) {
|
|
521
|
+
super(message, 2, hint);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
function badUsage(message) {
|
|
525
|
+
throw new UsageError(message);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
class HelpShown extends Exit {
|
|
529
|
+
constructor() {
|
|
530
|
+
super("help shown", 0);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
class Completing {
|
|
535
|
+
options;
|
|
536
|
+
positionals;
|
|
537
|
+
candidates;
|
|
538
|
+
constructor(options, positionals = [], candidates = {}) {
|
|
539
|
+
this.options = options;
|
|
540
|
+
this.positionals = positionals;
|
|
541
|
+
this.candidates = candidates;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
var completion = { active: false };
|
|
545
|
+
var OUTPUT_OPTIONS = {
|
|
546
|
+
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
547
|
+
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
548
|
+
};
|
|
549
|
+
function applyOutput(color, plain, env = process6.env) {
|
|
550
|
+
const when = plain === true ? "never" : color ?? "auto";
|
|
551
|
+
if (when === "auto")
|
|
552
|
+
return;
|
|
553
|
+
if (when !== "always" && when !== "never")
|
|
554
|
+
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
555
|
+
if (when === "always") {
|
|
556
|
+
env.FORCE_COLOR = "1";
|
|
557
|
+
delete env.NO_COLOR;
|
|
558
|
+
} else {
|
|
559
|
+
env.NO_COLOR = "1";
|
|
560
|
+
delete env.FORCE_COLOR;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
function parse(args, usage, options, settings = {}) {
|
|
564
|
+
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
565
|
+
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
566
|
+
const listing = listed(all, settings.allowNegative === true);
|
|
567
|
+
if (completion.active)
|
|
568
|
+
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
569
|
+
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
570
|
+
let parsed;
|
|
571
|
+
try {
|
|
572
|
+
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
573
|
+
} catch (error) {
|
|
574
|
+
const message = parseError(error);
|
|
575
|
+
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
576
|
+
}
|
|
577
|
+
const values = parsed.values;
|
|
578
|
+
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
579
|
+
if (values.help === true) {
|
|
580
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
581
|
+
throw new HelpShown;
|
|
582
|
+
}
|
|
583
|
+
checkChoices(parsed.values, all);
|
|
584
|
+
checkConflicts(parsed.values, all);
|
|
585
|
+
if (settings.positionals !== undefined)
|
|
586
|
+
checkPositionals(parsed.positionals, settings.positionals);
|
|
587
|
+
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
588
|
+
}
|
|
589
|
+
function splitRest(args, passes) {
|
|
590
|
+
const separator = passes ? args.indexOf("--") : -1;
|
|
591
|
+
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
592
|
+
}
|
|
593
|
+
function splitTrailing(args, options, count) {
|
|
594
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
595
|
+
let seen = 0;
|
|
596
|
+
if (count === 0)
|
|
597
|
+
return { own: args, rest: undefined };
|
|
598
|
+
for (let at = 0;at < args.length; at++) {
|
|
599
|
+
const word = args[at];
|
|
600
|
+
if (word === "--")
|
|
601
|
+
break;
|
|
602
|
+
if (word.startsWith("-")) {
|
|
603
|
+
if (takesValue(word))
|
|
604
|
+
at++;
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
seen++;
|
|
608
|
+
if (seen === count)
|
|
609
|
+
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
610
|
+
}
|
|
611
|
+
return { own: args, rest: undefined };
|
|
612
|
+
}
|
|
613
|
+
function listed(options, allowNegative) {
|
|
614
|
+
if (!allowNegative)
|
|
615
|
+
return options;
|
|
616
|
+
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
617
|
+
if (option.type !== "boolean" || option.negative === undefined)
|
|
618
|
+
return [[name, option]];
|
|
619
|
+
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
620
|
+
}));
|
|
621
|
+
}
|
|
622
|
+
function withAliases(args, options) {
|
|
623
|
+
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
624
|
+
if (named.size === 0)
|
|
625
|
+
return args;
|
|
626
|
+
const separator = args.indexOf("--");
|
|
627
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
628
|
+
return [...own.map((arg) => {
|
|
629
|
+
const at = arg.indexOf("=");
|
|
630
|
+
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
631
|
+
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
632
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
633
|
+
}
|
|
634
|
+
function withBare(args, options) {
|
|
635
|
+
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
636
|
+
if (bare.size === 0)
|
|
637
|
+
return args;
|
|
638
|
+
const separator = args.indexOf("--");
|
|
639
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
640
|
+
return [...own.flatMap((arg, index) => {
|
|
641
|
+
const optional = bare.get(arg);
|
|
642
|
+
const next = own[index + 1];
|
|
643
|
+
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
644
|
+
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
645
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
646
|
+
}
|
|
647
|
+
function checkConflicts(values, options) {
|
|
648
|
+
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
649
|
+
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
650
|
+
const other = given(name) ? conflicts.find(given) : undefined;
|
|
651
|
+
if (other !== undefined)
|
|
652
|
+
badUsage(`--${name} cannot be used with --${other}`);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
function checkChoices(values, options) {
|
|
656
|
+
for (const [name, option] of Object.entries(options)) {
|
|
657
|
+
if (option.choices === undefined)
|
|
658
|
+
continue;
|
|
659
|
+
const given = values[name];
|
|
660
|
+
for (const value of Array.isArray(given) ? given : [given]) {
|
|
661
|
+
if (typeof value === "string")
|
|
662
|
+
oneOf(value, name, option.choices);
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
function oneOf(value, name, choices) {
|
|
667
|
+
if (!choices.includes(value))
|
|
668
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
669
|
+
return value;
|
|
670
|
+
}
|
|
671
|
+
function checkPositionals(given, names) {
|
|
672
|
+
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
673
|
+
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
674
|
+
if (given.length < required)
|
|
675
|
+
badUsage(`missing ${names[given.length]}`);
|
|
676
|
+
if (!variadic && given.length > names.length)
|
|
677
|
+
badUsage(`unexpected argument ${given[names.length]}`);
|
|
678
|
+
}
|
|
679
|
+
function joinDashValues(args, options) {
|
|
680
|
+
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
681
|
+
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
682
|
+
const joined = [];
|
|
683
|
+
for (let i = 0;i < args.length; i++) {
|
|
684
|
+
const arg = args[i] ?? "";
|
|
685
|
+
if (arg === "--")
|
|
686
|
+
return [...joined, ...args.slice(i)];
|
|
687
|
+
const name = longOf.get(arg);
|
|
688
|
+
const next = args[i + 1];
|
|
689
|
+
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
690
|
+
joined.push(`--${name}=${next}`);
|
|
691
|
+
i++;
|
|
692
|
+
} else {
|
|
693
|
+
joined.push(arg);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
return joined;
|
|
697
|
+
}
|
|
698
|
+
function parseError(error) {
|
|
699
|
+
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
700
|
+
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
701
|
+
}
|
|
702
|
+
var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
703
|
+
function nearestOption(message, options, allowNegative) {
|
|
704
|
+
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
705
|
+
if (typed === undefined)
|
|
706
|
+
return;
|
|
707
|
+
const word = typed.replace(DASHES, "");
|
|
708
|
+
if (word.length < 2 && !typed.startsWith("--"))
|
|
709
|
+
return;
|
|
710
|
+
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
711
|
+
...option.short === undefined ? [] : [`-${option.short}`],
|
|
712
|
+
`--${name}`,
|
|
713
|
+
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
714
|
+
]);
|
|
715
|
+
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
716
|
+
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
717
|
+
}
|
|
718
|
+
// ../kit/src/process.ts
|
|
719
|
+
import { constants } from "os";
|
|
720
|
+
import process7 from "process";
|
|
721
|
+
var KILL_GRACE_MS = 2000;
|
|
722
|
+
function exitCodeOf(code, signal) {
|
|
723
|
+
if (code !== null)
|
|
724
|
+
return code;
|
|
725
|
+
if (typeof signal === "number")
|
|
726
|
+
return 128 + signal;
|
|
727
|
+
return signal === null ? 129 : 128 + constants.signals[signal];
|
|
728
|
+
}
|
|
729
|
+
async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
730
|
+
const chunks = [];
|
|
731
|
+
const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
|
|
732
|
+
const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
|
|
733
|
+
const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
|
|
734
|
+
const timers = [];
|
|
735
|
+
const killGroup = (killing) => {
|
|
736
|
+
if (state.done)
|
|
737
|
+
return;
|
|
738
|
+
try {
|
|
739
|
+
if (grouped)
|
|
740
|
+
process7.kill(-proc.pid, killing);
|
|
741
|
+
else
|
|
742
|
+
proc.kill(killing);
|
|
743
|
+
} catch {}
|
|
744
|
+
};
|
|
745
|
+
const stop = () => {
|
|
746
|
+
killGroup("SIGTERM");
|
|
747
|
+
timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
|
|
748
|
+
};
|
|
749
|
+
const onAbort = () => stop();
|
|
750
|
+
if (timeoutMs !== undefined) {
|
|
751
|
+
timers.push(setTimeout(() => {
|
|
752
|
+
state.timedOut = true;
|
|
753
|
+
stop();
|
|
754
|
+
}, timeoutMs));
|
|
755
|
+
}
|
|
756
|
+
if (signal?.aborted === true)
|
|
757
|
+
onAbort();
|
|
758
|
+
else
|
|
759
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
760
|
+
onStart?.({ kill: (killing) => killGroup(killing) });
|
|
761
|
+
const drain = async (stream, name) => {
|
|
762
|
+
for await (const data of stream) {
|
|
763
|
+
if (state.failure !== undefined)
|
|
764
|
+
continue;
|
|
765
|
+
try {
|
|
766
|
+
onChunk?.({ stream: name, data });
|
|
767
|
+
} catch (error) {
|
|
768
|
+
state.failure = error;
|
|
769
|
+
stop();
|
|
770
|
+
continue;
|
|
771
|
+
}
|
|
772
|
+
if (state.kept + data.length > maxBytes) {
|
|
773
|
+
state.truncated = true;
|
|
774
|
+
continue;
|
|
775
|
+
}
|
|
776
|
+
state.kept += data.length;
|
|
777
|
+
chunks.push({ stream: name, data });
|
|
778
|
+
}
|
|
779
|
+
};
|
|
780
|
+
try {
|
|
781
|
+
await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
|
|
782
|
+
await proc.exited;
|
|
783
|
+
} finally {
|
|
784
|
+
state.done = true;
|
|
785
|
+
for (const timer of timers)
|
|
786
|
+
clearTimeout(timer);
|
|
787
|
+
signal?.removeEventListener("abort", onAbort);
|
|
788
|
+
}
|
|
789
|
+
if (state.failure !== undefined)
|
|
790
|
+
throw state.failure;
|
|
791
|
+
const joined = () => Buffer.concat(chunks.map(({ data }) => data));
|
|
792
|
+
let output;
|
|
793
|
+
let text;
|
|
794
|
+
return {
|
|
795
|
+
code: exitCodeOf(proc.exitCode, proc.signalCode),
|
|
796
|
+
chunks,
|
|
797
|
+
timedOut: state.timedOut,
|
|
798
|
+
truncated: state.truncated,
|
|
799
|
+
get output() {
|
|
800
|
+
return output ??= joined();
|
|
801
|
+
},
|
|
802
|
+
get text() {
|
|
803
|
+
return text ??= (output ??= joined()).toString();
|
|
804
|
+
}
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
// ../kit/src/progress.ts
|
|
809
|
+
var ESC = String.fromCharCode(27);
|
|
810
|
+
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
811
|
+
var RESET_STYLE = `${ESC}[0m`;
|
|
812
|
+
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
813
|
+
// ../kit/src/cli.ts
|
|
814
|
+
import { readFileSync, realpathSync } from "fs";
|
|
815
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
816
|
+
import process9 from "process";
|
|
817
|
+
|
|
818
|
+
// ../kit/src/usage.ts
|
|
819
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
820
|
+
import { homedir } from "os";
|
|
821
|
+
import { dirname, isAbsolute, join } from "path";
|
|
822
|
+
import process8 from "process";
|
|
823
|
+
|
|
824
|
+
// ../kit/src/logs.ts
|
|
825
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
826
|
+
var CLI_FOLDER = "kaynooo-cli";
|
|
827
|
+
|
|
828
|
+
// ../kit/src/usage.ts
|
|
829
|
+
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
830
|
+
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
831
|
+
var LONGEST_NAME = 40;
|
|
832
|
+
var usageError;
|
|
833
|
+
function noteUsageError(message) {
|
|
834
|
+
usageError = message;
|
|
835
|
+
}
|
|
836
|
+
function stateHome(env = process8.env) {
|
|
837
|
+
const dir = env.XDG_STATE_HOME;
|
|
838
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
|
|
839
|
+
}
|
|
840
|
+
function usagePath(env = process8.env) {
|
|
841
|
+
return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
842
|
+
}
|
|
843
|
+
function usageRecorded(env = process8.env) {
|
|
844
|
+
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
845
|
+
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
846
|
+
}
|
|
847
|
+
function flagNames(argv) {
|
|
848
|
+
const end = argv.indexOf("--");
|
|
849
|
+
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
850
|
+
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
851
|
+
}
|
|
852
|
+
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
853
|
+
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
854
|
+
usageError = undefined;
|
|
855
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
856
|
+
}
|
|
857
|
+
function recordUsage(entry, env = process8.env) {
|
|
858
|
+
if (!usageRecorded(env))
|
|
859
|
+
return;
|
|
860
|
+
try {
|
|
861
|
+
const path = usagePath(env);
|
|
862
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
863
|
+
appendFileSync(path, `${JSON.stringify(entry)}
|
|
864
|
+
`, { mode: 384 });
|
|
865
|
+
} catch {}
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// ../kit/src/cli.ts
|
|
869
|
+
var LEVEL_OPTIONS = {
|
|
870
|
+
...OUTPUT_OPTIONS,
|
|
871
|
+
help: { type: "boolean", short: "h", description: "show this help" }
|
|
872
|
+
};
|
|
873
|
+
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
874
|
+
async function commandRows(all, colors) {
|
|
875
|
+
const commands = shown(all);
|
|
876
|
+
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
877
|
+
const groups = new Map([["Commands:", []]]);
|
|
878
|
+
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
879
|
+
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
880
|
+
const heading = group === undefined ? "Commands:" : `${group}:`;
|
|
881
|
+
const rows = groups.get(heading) ?? [];
|
|
882
|
+
rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
|
|
883
|
+
groups.set(heading, rows);
|
|
884
|
+
}
|
|
885
|
+
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
886
|
+
}
|
|
887
|
+
function shown(commands) {
|
|
888
|
+
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
889
|
+
}
|
|
890
|
+
function takeOutputFlags(argv) {
|
|
891
|
+
let index = 0;
|
|
892
|
+
for (;index < argv.length; index++) {
|
|
893
|
+
const word = argv[index];
|
|
894
|
+
if (word === "--plain")
|
|
895
|
+
applyOutput(undefined, true);
|
|
896
|
+
else if (word.startsWith("--color="))
|
|
897
|
+
applyOutput(word.slice("--color=".length), undefined);
|
|
898
|
+
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
899
|
+
applyOutput(argv[++index], undefined);
|
|
900
|
+
else
|
|
901
|
+
break;
|
|
902
|
+
}
|
|
903
|
+
return argv.slice(index);
|
|
904
|
+
}
|
|
905
|
+
async function resolveSummary(summary) {
|
|
906
|
+
return typeof summary === "string" ? summary : summary();
|
|
907
|
+
}
|
|
908
|
+
function scopeOf(commands, extra, aliases) {
|
|
909
|
+
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
910
|
+
}
|
|
911
|
+
async function expand(scope, words) {
|
|
912
|
+
if (scope.lazy.length === 0)
|
|
913
|
+
return scope;
|
|
914
|
+
const commands = { ...scope.commands };
|
|
915
|
+
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
916
|
+
for (const [name, command] of Object.entries(added))
|
|
917
|
+
commands[name] ??= command;
|
|
918
|
+
}
|
|
919
|
+
return { ...scope, commands, lazy: [] };
|
|
920
|
+
}
|
|
921
|
+
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
922
|
+
const colors = paint(stream);
|
|
923
|
+
const prefix = path.join(" ");
|
|
924
|
+
const summary = await resolveSummary(lazySummary);
|
|
925
|
+
if (wantsHelpJson())
|
|
926
|
+
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
927
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
928
|
+
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
929
|
+
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
930
|
+
return [
|
|
931
|
+
header(colors, summary),
|
|
932
|
+
"",
|
|
933
|
+
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
934
|
+
...replacesRows(replaces, colors),
|
|
935
|
+
"",
|
|
936
|
+
...await commandRows(commands, colors),
|
|
937
|
+
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
938
|
+
"",
|
|
939
|
+
colors.bold("Options:"),
|
|
940
|
+
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
941
|
+
...exampleRows(examples ?? [], colors),
|
|
942
|
+
"",
|
|
943
|
+
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
944
|
+
].join(`
|
|
945
|
+
`);
|
|
946
|
+
}
|
|
947
|
+
function printError(prefix, message, hint, cause) {
|
|
948
|
+
const colors = paint(process9.stderr);
|
|
949
|
+
const styled = takesControlCodes(process9.stderr);
|
|
950
|
+
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
951
|
+
const under = (label, text, tint) => text === undefined ? "" : `
|
|
952
|
+
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
953
|
+
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
954
|
+
}
|
|
955
|
+
function printJsonError(message, hint, cause) {
|
|
956
|
+
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
957
|
+
}
|
|
958
|
+
function wantsJson(argv) {
|
|
959
|
+
const end = argv.indexOf("--");
|
|
960
|
+
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
961
|
+
}
|
|
962
|
+
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
963
|
+
if (error instanceof HelpShown)
|
|
964
|
+
return 0;
|
|
965
|
+
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
966
|
+
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
967
|
+
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
968
|
+
if (error instanceof Exit && error.code === 2)
|
|
969
|
+
noteUsageError(error.message);
|
|
970
|
+
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
971
|
+
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
972
|
+
return error instanceof Exit ? error.code : 1;
|
|
973
|
+
}
|
|
974
|
+
async function dispatch(level, typed, { version, redact }) {
|
|
975
|
+
const prefix = level.path.join(" ");
|
|
976
|
+
let argv;
|
|
977
|
+
try {
|
|
978
|
+
argv = takeOutputFlags(typed);
|
|
979
|
+
} catch (error) {
|
|
980
|
+
return reportThrown(prefix, error);
|
|
981
|
+
}
|
|
982
|
+
const [name, ...args] = argv;
|
|
983
|
+
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
984
|
+
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
985
|
+
try {
|
|
986
|
+
return await fallback.run([]);
|
|
987
|
+
} catch (error) {
|
|
988
|
+
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
if (name === undefined && level.path.length > 1) {
|
|
992
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
|
|
993
|
+
return 2;
|
|
994
|
+
}
|
|
995
|
+
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
996
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
|
|
997
|
+
return 0;
|
|
998
|
+
}
|
|
999
|
+
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
1000
|
+
console.log(version);
|
|
1001
|
+
return 0;
|
|
1002
|
+
}
|
|
1003
|
+
let command = level.commands[level.aliases?.[name] ?? name];
|
|
1004
|
+
let rest = args;
|
|
1005
|
+
let ran = name;
|
|
1006
|
+
if (command === undefined && level.lazy.length > 0) {
|
|
1007
|
+
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
1008
|
+
command = level.commands[level.aliases?.[name] ?? name];
|
|
1009
|
+
}
|
|
1010
|
+
if (command === undefined && level.defaultCommand !== undefined) {
|
|
1011
|
+
command = level.commands[level.defaultCommand];
|
|
1012
|
+
rest = argv;
|
|
1013
|
+
ran = level.defaultCommand;
|
|
1014
|
+
}
|
|
1015
|
+
if (command === undefined) {
|
|
1016
|
+
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
1017
|
+
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
1018
|
+
return 2;
|
|
1019
|
+
}
|
|
1020
|
+
if ("commands" in command) {
|
|
1021
|
+
const { summary } = command;
|
|
1022
|
+
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 });
|
|
1023
|
+
}
|
|
1024
|
+
try {
|
|
1025
|
+
return await command.run(rest);
|
|
1026
|
+
} catch (error) {
|
|
1027
|
+
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
var COMPLETE = "__complete";
|
|
1031
|
+
var FILES = "__files__";
|
|
1032
|
+
async function completingOf(run) {
|
|
1033
|
+
completion.active = true;
|
|
1034
|
+
try {
|
|
1035
|
+
await run([]);
|
|
1036
|
+
} catch (error) {
|
|
1037
|
+
if (error instanceof Completing)
|
|
1038
|
+
return error;
|
|
1039
|
+
} finally {
|
|
1040
|
+
completion.active = false;
|
|
1041
|
+
}
|
|
1042
|
+
return new Completing({});
|
|
1043
|
+
}
|
|
1044
|
+
async function optionsOf(run) {
|
|
1045
|
+
return (await completingOf(run)).options;
|
|
1046
|
+
}
|
|
1047
|
+
function candidateLine(candidate) {
|
|
1048
|
+
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
1049
|
+
}
|
|
1050
|
+
function positionalBeingTyped(before, { options, positionals }) {
|
|
1051
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1052
|
+
let index = 0;
|
|
1053
|
+
let at = 0;
|
|
1054
|
+
while (at < before.length) {
|
|
1055
|
+
const word = before[at];
|
|
1056
|
+
if (word === "--") {
|
|
1057
|
+
index += before.length - at - 1;
|
|
1058
|
+
break;
|
|
1059
|
+
}
|
|
1060
|
+
if (!word.startsWith("-"))
|
|
1061
|
+
index++;
|
|
1062
|
+
else if (takesValue(word))
|
|
1063
|
+
at++;
|
|
1064
|
+
at++;
|
|
1065
|
+
}
|
|
1066
|
+
const last = positionals.at(-1);
|
|
1067
|
+
if (index < positionals.length)
|
|
1068
|
+
return positionals[index];
|
|
1069
|
+
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
1070
|
+
}
|
|
1071
|
+
async function leafCandidates(run, words) {
|
|
1072
|
+
const completing = await completingOf(run);
|
|
1073
|
+
if ((words.at(-1) ?? "").startsWith("-"))
|
|
1074
|
+
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1075
|
+
const flag = words.at(-2);
|
|
1076
|
+
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1077
|
+
if (option?.type === "string") {
|
|
1078
|
+
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
1079
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1080
|
+
}
|
|
1081
|
+
const name = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1082
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
1083
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1084
|
+
}
|
|
1085
|
+
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1086
|
+
const [word = "", ...rest] = words;
|
|
1087
|
+
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1088
|
+
let { commands, aliases } = scope;
|
|
1089
|
+
let command = commands[aliases?.[word] ?? word];
|
|
1090
|
+
if (listing || command === undefined) {
|
|
1091
|
+
({ commands, aliases } = await expand(scope, [...before, ...words]));
|
|
1092
|
+
command = commands[aliases?.[word] ?? word];
|
|
1093
|
+
}
|
|
1094
|
+
if (listing) {
|
|
1095
|
+
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1096
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1097
|
+
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1098
|
+
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1099
|
+
return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
|
|
1100
|
+
}
|
|
1101
|
+
if (command === undefined) {
|
|
1102
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1103
|
+
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
1104
|
+
}
|
|
1105
|
+
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1106
|
+
}
|
|
1107
|
+
async function printCandidates(found) {
|
|
1108
|
+
for (const line of await found)
|
|
1109
|
+
console.log(line);
|
|
1110
|
+
return 0;
|
|
1111
|
+
}
|
|
1112
|
+
function packageVersion(entry = Bun.main) {
|
|
1113
|
+
for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
|
|
1114
|
+
try {
|
|
1115
|
+
const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
|
|
1116
|
+
if (typeof version === "string")
|
|
1117
|
+
return version;
|
|
1118
|
+
} catch {}
|
|
1119
|
+
if (dirname2(dir) === dir)
|
|
1120
|
+
return "0.0.0";
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
async function runCli(cli, argv = process9.argv.slice(2)) {
|
|
1124
|
+
const version = cli.version ?? packageVersion();
|
|
1125
|
+
if (argv[0] === COMPLETE)
|
|
1126
|
+
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1127
|
+
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 });
|
|
1128
|
+
if (cli.usage !== false) {
|
|
1129
|
+
try {
|
|
1130
|
+
recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
|
|
1131
|
+
} catch {}
|
|
1132
|
+
}
|
|
1133
|
+
return code;
|
|
1134
|
+
}
|
|
1135
|
+
function commandPath(scope, argv) {
|
|
1136
|
+
const path = [];
|
|
1137
|
+
let level = scope;
|
|
1138
|
+
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1139
|
+
const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
|
|
1140
|
+
const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
|
|
1141
|
+
if (command === undefined)
|
|
1142
|
+
break;
|
|
1143
|
+
path.push(word);
|
|
1144
|
+
if (!("commands" in command))
|
|
1145
|
+
break;
|
|
1146
|
+
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
1147
|
+
}
|
|
1148
|
+
return path.length === 0 ? undefined : path.join(" ");
|
|
1149
|
+
}
|
|
1150
|
+
async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
|
|
1151
|
+
if (argv[0] === COMPLETE)
|
|
1152
|
+
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1153
|
+
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
1154
|
+
console.log(version ?? packageVersion());
|
|
1155
|
+
return 0;
|
|
1156
|
+
}
|
|
1157
|
+
let code;
|
|
1158
|
+
try {
|
|
1159
|
+
code = await run(argv);
|
|
1160
|
+
} catch (error) {
|
|
1161
|
+
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1162
|
+
}
|
|
1163
|
+
if (usage !== false) {
|
|
1164
|
+
try {
|
|
1165
|
+
recordUsage(usageEntry(name, undefined, argv, code));
|
|
1166
|
+
} catch {}
|
|
1167
|
+
}
|
|
1168
|
+
return code;
|
|
1169
|
+
}
|
|
1170
|
+
// ../kit/src/secrets.ts
|
|
1171
|
+
var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
|
|
1172
|
+
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1173
|
+
var WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
|
|
1174
|
+
function isSecretName(name) {
|
|
1175
|
+
return SECRET_PART.test(name) || name.split(WORD_BREAKS).some((word) => SECRET_WORDS.has(word.toLowerCase()));
|
|
1176
|
+
}
|
|
1177
|
+
// ../kit/src/sessions.ts
|
|
1178
|
+
var {Glob } = globalThis.Bun;
|
|
1179
|
+
var SESSION_FILES = new Glob("*.json");
|
|
1180
|
+
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1181
|
+
// ../kit/src/size.ts
|
|
1182
|
+
var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
|
|
1183
|
+
var POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
|
|
1184
|
+
function parseSize(text, bareUnit = 1) {
|
|
1185
|
+
const match = SIZE.exec(text.trim());
|
|
1186
|
+
if (match === null)
|
|
1187
|
+
return;
|
|
1188
|
+
const suffix = match[2].toLowerCase();
|
|
1189
|
+
return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
|
|
1190
|
+
}
|
|
1191
|
+
// ../kit/src/watch.ts
|
|
1192
|
+
import process10 from "process";
|
|
1193
|
+
import { format } from "util";
|
|
1194
|
+
var CLEAR_SCREEN = "\x1B[H\x1B[2J";
|
|
1195
|
+
var DEFAULT_SECONDS = 2;
|
|
1196
|
+
var ATTACHED_SHORT = /^-w./;
|
|
1197
|
+
var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
|
|
1198
|
+
function watchOption(what) {
|
|
1199
|
+
return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
|
|
1200
|
+
}
|
|
1201
|
+
function withoutWatch(args) {
|
|
1202
|
+
const rest = [];
|
|
1203
|
+
for (let at = 0;at < args.length; at++) {
|
|
1204
|
+
const arg = args[at];
|
|
1205
|
+
if (arg === "--watch" || arg === "-w") {
|
|
1206
|
+
if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
|
|
1207
|
+
at++;
|
|
1208
|
+
} else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
|
|
1209
|
+
rest.push(arg);
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
return rest;
|
|
1213
|
+
}
|
|
1214
|
+
async function watching(value, step, stream = process10.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
|
|
1215
|
+
const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
|
|
1216
|
+
if (!takesControlCodes(stream))
|
|
1217
|
+
badUsage("--watch redraws the screen, so it needs a terminal");
|
|
1218
|
+
let code = 0;
|
|
1219
|
+
for (let round = 0;round < rounds; round++) {
|
|
1220
|
+
const held = [];
|
|
1221
|
+
const { log, info } = console;
|
|
1222
|
+
const write = process10.stdout.write.bind(process10.stdout);
|
|
1223
|
+
const hold = (...parts) => void held.push(`${format(...parts)}
|
|
1224
|
+
`);
|
|
1225
|
+
console.log = hold;
|
|
1226
|
+
console.info = hold;
|
|
1227
|
+
process10.stdout.write = (text) => {
|
|
1228
|
+
held.push(typeof text === "string" ? text : Buffer.from(text).toString());
|
|
1229
|
+
return true;
|
|
1230
|
+
};
|
|
1231
|
+
try {
|
|
1232
|
+
code = await step();
|
|
1233
|
+
} finally {
|
|
1234
|
+
console.log = log;
|
|
1235
|
+
console.info = info;
|
|
1236
|
+
process10.stdout.write = write;
|
|
1237
|
+
}
|
|
1238
|
+
stream.write(`${CLEAR_SCREEN}${held.join("")}`);
|
|
1239
|
+
await sleep(interval);
|
|
1240
|
+
}
|
|
1241
|
+
return code;
|
|
1242
|
+
}
|
|
1243
|
+
// src/pid.ts
|
|
1244
|
+
import process12 from "process";
|
|
1245
|
+
|
|
1246
|
+
// src/mask.ts
|
|
1247
|
+
import { basename } from "path";
|
|
1248
|
+
var MASK = "***";
|
|
1249
|
+
var URL_PASSWORD = /(?<![a-z0-9+.-])([a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:)[^\s'"@]{1,1024}@/gi;
|
|
1250
|
+
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;
|
|
1251
|
+
var OPAQUE = /(?<![\w-])(?=[\w-]{32,}(?![\w-]))(?=[\w-]*[A-Z])(?=[\w-]*\d)[\w-]+/gi;
|
|
1252
|
+
var PEM = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*/;
|
|
1253
|
+
function maskText(value) {
|
|
1254
|
+
return value.replace(PEM, MASK).replace(URL_PASSWORD, `$1${MASK}@`).replace(TOKEN, MASK).replace(OPAQUE, MASK);
|
|
1255
|
+
}
|
|
1256
|
+
function maskValue(name, value) {
|
|
1257
|
+
if (value === "")
|
|
1258
|
+
return value;
|
|
1259
|
+
return isSecretName(name) ? MASK : maskText(value);
|
|
1260
|
+
}
|
|
1261
|
+
function maskEnviron(entries) {
|
|
1262
|
+
return entries.map(([name, value]) => [name, maskValue(name, value)]);
|
|
1263
|
+
}
|
|
1264
|
+
var FLAG = /^-{1,2}([\w.-]+)(=|$)/;
|
|
1265
|
+
var ASSIGNMENT_NAME = /^[\w.-]+$/;
|
|
1266
|
+
var PASSWORD_SPLIT = new Set(["sshpass"]);
|
|
1267
|
+
var PASSWORD_JOINED = new Set(["mysql", "mysqldump", "mysqladmin", "mariadb", "mariadb-dump"]);
|
|
1268
|
+
function maskArgs(args) {
|
|
1269
|
+
const command = basename(args[0] ?? "");
|
|
1270
|
+
let hidden = false;
|
|
1271
|
+
return args.map((arg, index) => {
|
|
1272
|
+
if (hidden) {
|
|
1273
|
+
hidden = false;
|
|
1274
|
+
return arg.startsWith("-") ? maskText(arg) : MASK;
|
|
1275
|
+
}
|
|
1276
|
+
if (index > 0 && arg === "-p" && PASSWORD_SPLIT.has(command)) {
|
|
1277
|
+
hidden = true;
|
|
1278
|
+
return arg;
|
|
1279
|
+
}
|
|
1280
|
+
if (index > 0 && arg.length > 2 && arg.startsWith("-p") && PASSWORD_JOINED.has(command))
|
|
1281
|
+
return `-p${MASK}`;
|
|
1282
|
+
const flag = FLAG.exec(arg);
|
|
1283
|
+
if (flag !== null) {
|
|
1284
|
+
if (flag[2] === "=")
|
|
1285
|
+
return isSecretName(flag[1]) ? `${arg.slice(0, flag[0].length)}${MASK}` : maskText(arg);
|
|
1286
|
+
hidden = isSecretName(flag[1]);
|
|
1287
|
+
return arg;
|
|
1288
|
+
}
|
|
1289
|
+
const equals = arg.indexOf("=");
|
|
1290
|
+
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);
|
|
1291
|
+
});
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
// src/parse.ts
|
|
1295
|
+
var LISTENING = { tcp: "0A", udp: "07" };
|
|
1296
|
+
var WHITESPACE = /\s+/;
|
|
1297
|
+
var HEX_PAIR = /../g;
|
|
1298
|
+
var SOCKET_LINK = /^socket:\[(\d+)\]$/;
|
|
1299
|
+
var UNIT_SCOPE = /\.(?:service|scope)$/;
|
|
1300
|
+
var CONTAINER_ID = /(?:docker-|libpod-|\/docker\/)([0-9a-f]{64})/;
|
|
1301
|
+
var DOCKER_PORT = /:(\d+)(?:-(\d+))?->[\d-]+\/(tcp|udp)/;
|
|
1302
|
+
function word(hex) {
|
|
1303
|
+
const bytes = (hex.match(HEX_PAIR) ?? []).reverse().map((byte) => Number.parseInt(byte, 16));
|
|
1304
|
+
return [bytes[0] << 8 | bytes[1], bytes[2] << 8 | bytes[3]];
|
|
1305
|
+
}
|
|
1306
|
+
function parseAddress(hex) {
|
|
1307
|
+
if (hex.length === 8) {
|
|
1308
|
+
const [high, low] = word(hex);
|
|
1309
|
+
return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
|
|
1310
|
+
}
|
|
1311
|
+
const hextets = (hex.match(/.{8}/g) ?? []).flatMap(word);
|
|
1312
|
+
if (hextets.length !== 8)
|
|
1313
|
+
return hex;
|
|
1314
|
+
if (hextets.slice(0, 5).every((part) => part === 0) && hextets[5] === 65535)
|
|
1315
|
+
return `::ffff:${hextets[6] >> 8}.${hextets[6] & 255}.${hextets[7] >> 8}.${hextets[7] & 255}`;
|
|
1316
|
+
return compress(hextets);
|
|
1317
|
+
}
|
|
1318
|
+
function compress(hextets) {
|
|
1319
|
+
let best = { start: -1, length: 0 };
|
|
1320
|
+
let run = { start: 0, length: 0 };
|
|
1321
|
+
for (const [at, part] of hextets.entries()) {
|
|
1322
|
+
run = part === 0 ? { start: run.length === 0 ? at : run.start, length: run.length + 1 } : { start: 0, length: 0 };
|
|
1323
|
+
if (run.length > best.length)
|
|
1324
|
+
best = run;
|
|
1325
|
+
}
|
|
1326
|
+
const text = (parts) => parts.map((part) => part.toString(16)).join(":");
|
|
1327
|
+
if (best.length < 2)
|
|
1328
|
+
return text(hextets);
|
|
1329
|
+
return `${text(hextets.slice(0, best.start))}::${text(hextets.slice(best.start + best.length))}`;
|
|
1330
|
+
}
|
|
1331
|
+
function parseNetTable(text, protocol, family) {
|
|
1332
|
+
const sockets = [];
|
|
1333
|
+
for (const line of text.split(`
|
|
1334
|
+
`).slice(1)) {
|
|
1335
|
+
const columns = line.trim().split(WHITESPACE);
|
|
1336
|
+
const [address = "", port = ""] = (columns[1] ?? "").split(":");
|
|
1337
|
+
if (columns.length < 10 || columns[3] !== LISTENING[protocol])
|
|
1338
|
+
continue;
|
|
1339
|
+
const number = Number.parseInt(port, 16);
|
|
1340
|
+
if (number === 0 || Number.isNaN(number))
|
|
1341
|
+
continue;
|
|
1342
|
+
sockets.push({ protocol, family, address: parseAddress(address), port: number, uid: Number(columns[7]), inode: Number(columns[9]) });
|
|
1343
|
+
}
|
|
1344
|
+
return sockets;
|
|
1345
|
+
}
|
|
1346
|
+
function socketInode(link) {
|
|
1347
|
+
const match = SOCKET_LINK.exec(link);
|
|
1348
|
+
return match === null ? undefined : Number(match[1]);
|
|
1349
|
+
}
|
|
1350
|
+
function parseStat(text) {
|
|
1351
|
+
const open = text.indexOf("(");
|
|
1352
|
+
const close = text.lastIndexOf(")");
|
|
1353
|
+
if (open === -1 || close < open)
|
|
1354
|
+
return;
|
|
1355
|
+
const rest = text.slice(close + 2).trim().split(WHITESPACE);
|
|
1356
|
+
const field = (number) => Number(rest[number - 3]);
|
|
1357
|
+
if (rest.length < 20)
|
|
1358
|
+
return;
|
|
1359
|
+
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) };
|
|
1360
|
+
}
|
|
1361
|
+
function parseStatus(text) {
|
|
1362
|
+
const fields = new Map;
|
|
1363
|
+
for (const line of text.split(`
|
|
1364
|
+
`)) {
|
|
1365
|
+
const colon = line.indexOf(":");
|
|
1366
|
+
if (colon > 0)
|
|
1367
|
+
fields.set(line.slice(0, colon), line.slice(colon + 1).trim());
|
|
1368
|
+
}
|
|
1369
|
+
return fields;
|
|
1370
|
+
}
|
|
1371
|
+
function statusBytes(fields, key) {
|
|
1372
|
+
const value = Number.parseInt(fields.get(key) ?? "", 10);
|
|
1373
|
+
return Number.isNaN(value) ? undefined : value * 1024;
|
|
1374
|
+
}
|
|
1375
|
+
function statusUid(fields) {
|
|
1376
|
+
const value = Number.parseInt(fields.get("Uid") ?? "", 10);
|
|
1377
|
+
return Number.isNaN(value) ? undefined : value;
|
|
1378
|
+
}
|
|
1379
|
+
var LIMIT_LINE = /^(\S+(?: \S+)*)\s{2,}(\S+)\s+(\S+)(?:\s+(\S+))?\s*$/;
|
|
1380
|
+
function parseLimits(text) {
|
|
1381
|
+
const limits = [];
|
|
1382
|
+
for (const line of text.split(`
|
|
1383
|
+
`).slice(1)) {
|
|
1384
|
+
const match = LIMIT_LINE.exec(line);
|
|
1385
|
+
if (match !== null)
|
|
1386
|
+
limits.push({ name: match[1], soft: match[2], hard: match[3], units: match[4] ?? "" });
|
|
1387
|
+
}
|
|
1388
|
+
return limits;
|
|
1389
|
+
}
|
|
1390
|
+
function parseCmdline(text) {
|
|
1391
|
+
return text.split("\x00").filter((_, at, parts) => at < parts.length - 1 || parts[at] !== "");
|
|
1392
|
+
}
|
|
1393
|
+
function parseEnviron(text) {
|
|
1394
|
+
return parseCmdline(text).map((entry) => {
|
|
1395
|
+
const equals = entry.indexOf("=");
|
|
1396
|
+
return equals === -1 ? [entry, ""] : [entry.slice(0, equals), entry.slice(equals + 1)];
|
|
1397
|
+
});
|
|
1398
|
+
}
|
|
1399
|
+
function parseCgroup(text) {
|
|
1400
|
+
return text.split(`
|
|
1401
|
+
`).filter((line) => line !== "").map((line) => {
|
|
1402
|
+
const [hierarchy = "", controllers = "", ...path] = line.split(":");
|
|
1403
|
+
return { hierarchy, controllers, path: path.join(":") };
|
|
1404
|
+
});
|
|
1405
|
+
}
|
|
1406
|
+
function cgroupUnit(entries) {
|
|
1407
|
+
const path = (entries.find((entry) => entry.hierarchy === "0") ?? entries[0])?.path ?? "";
|
|
1408
|
+
return path.split("/").reverse().find((part) => UNIT_SCOPE.test(part));
|
|
1409
|
+
}
|
|
1410
|
+
function cgroupContainer(entries) {
|
|
1411
|
+
for (const { path } of entries) {
|
|
1412
|
+
const match = CONTAINER_ID.exec(path);
|
|
1413
|
+
if (match !== null)
|
|
1414
|
+
return match[1];
|
|
1415
|
+
}
|
|
1416
|
+
return;
|
|
1417
|
+
}
|
|
1418
|
+
function userNameOf(passwd, uid) {
|
|
1419
|
+
for (const line of passwd.split(`
|
|
1420
|
+
`)) {
|
|
1421
|
+
const [name, , id] = line.split(":");
|
|
1422
|
+
if (id === String(uid) && name !== undefined && name !== "")
|
|
1423
|
+
return name;
|
|
1424
|
+
}
|
|
1425
|
+
return;
|
|
1426
|
+
}
|
|
1427
|
+
function parseDockerPs(text) {
|
|
1428
|
+
const containers = [];
|
|
1429
|
+
for (const line of text.split(`
|
|
1430
|
+
`)) {
|
|
1431
|
+
const [name = "", ports = "", project = "", service = ""] = line.split("\t");
|
|
1432
|
+
if (name === "")
|
|
1433
|
+
continue;
|
|
1434
|
+
const published = [];
|
|
1435
|
+
for (const entry of ports.split(",")) {
|
|
1436
|
+
const match = DOCKER_PORT.exec(entry);
|
|
1437
|
+
if (match === null)
|
|
1438
|
+
continue;
|
|
1439
|
+
const first = Number(match[1]);
|
|
1440
|
+
for (let host = first;host <= Number(match[2] ?? first); host++)
|
|
1441
|
+
published.push({ host, protocol: match[3] });
|
|
1442
|
+
}
|
|
1443
|
+
containers.push({ name, project: project === "" ? undefined : project, service: service === "" ? undefined : service, published });
|
|
1444
|
+
}
|
|
1445
|
+
return containers;
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
// src/read.ts
|
|
1449
|
+
import { readdir, readFile, readlink } from "fs/promises";
|
|
1450
|
+
var CLOCK_TICKS = 100;
|
|
1451
|
+
async function text2(path) {
|
|
1452
|
+
try {
|
|
1453
|
+
return await readFile(path, "utf8");
|
|
1454
|
+
} catch {
|
|
1455
|
+
return;
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
async function link(path) {
|
|
1459
|
+
try {
|
|
1460
|
+
return await readlink(path);
|
|
1461
|
+
} catch {
|
|
1462
|
+
return;
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
var DIGITS = /^\d+$/;
|
|
1466
|
+
var BOOT_TIME = /^btime\s+(\d+)/m;
|
|
1467
|
+
async function listPids(root = "/proc") {
|
|
1468
|
+
return (await readdir(root)).filter((name) => DIGITS.test(name)).map(Number);
|
|
1469
|
+
}
|
|
1470
|
+
async function bootMs(root = "/proc") {
|
|
1471
|
+
const match = BOOT_TIME.exec(await text2(`${root}/stat`) ?? "");
|
|
1472
|
+
return match === null ? Date.now() : Number(match[1]) * 1000;
|
|
1473
|
+
}
|
|
1474
|
+
async function readProc(pid, boot, { root = "/proc", detail = true } = {}) {
|
|
1475
|
+
const dir = `${root}/${pid}`;
|
|
1476
|
+
const [statText, statusText, cmdline] = await Promise.all([text2(`${dir}/stat`), text2(`${dir}/status`), text2(`${dir}/cmdline`)]);
|
|
1477
|
+
const stat = statText === undefined ? undefined : parseStat(statText);
|
|
1478
|
+
if (stat === undefined || statusText === undefined)
|
|
1479
|
+
return;
|
|
1480
|
+
const status = parseStatus(statusText);
|
|
1481
|
+
const info = {
|
|
1482
|
+
pid,
|
|
1483
|
+
ppid: stat.ppid,
|
|
1484
|
+
comm: stat.comm,
|
|
1485
|
+
args: parseCmdline(cmdline ?? ""),
|
|
1486
|
+
uid: statusUid(status) ?? -1,
|
|
1487
|
+
state: stat.state,
|
|
1488
|
+
session: stat.session,
|
|
1489
|
+
rss: statusBytes(status, "VmRSS") ?? 0,
|
|
1490
|
+
startMs: boot + stat.startTicks / CLOCK_TICKS * 1000
|
|
1491
|
+
};
|
|
1492
|
+
if (!detail)
|
|
1493
|
+
return info;
|
|
1494
|
+
const [cwd, exe, cgroup] = await Promise.all([link(`${dir}/cwd`), link(`${dir}/exe`), text2(`${dir}/cgroup`)]);
|
|
1495
|
+
const groups = parseCgroup(cgroup ?? "");
|
|
1496
|
+
return { ...info, cwd, exe, unit: cgroupUnit(groups), container: cgroupContainer(groups) };
|
|
1497
|
+
}
|
|
1498
|
+
async function snapshot(root = "/proc", detailed = () => true) {
|
|
1499
|
+
const boot = await bootMs(root);
|
|
1500
|
+
const found = [];
|
|
1501
|
+
for (const pid of await listPids(root)) {
|
|
1502
|
+
const light = await readProc(pid, boot, { root, detail: false });
|
|
1503
|
+
if (light === undefined)
|
|
1504
|
+
continue;
|
|
1505
|
+
found.push(detailed(light.uid) ? await readProc(pid, boot, { root }) ?? light : light);
|
|
1506
|
+
}
|
|
1507
|
+
return found;
|
|
1508
|
+
}
|
|
1509
|
+
function ancestry(pid, byPid) {
|
|
1510
|
+
const chain = [];
|
|
1511
|
+
let at = pid;
|
|
1512
|
+
while (at !== undefined && at > 0 && !chain.includes(at)) {
|
|
1513
|
+
chain.push(at);
|
|
1514
|
+
at = byPid.get(at)?.ppid;
|
|
1515
|
+
}
|
|
1516
|
+
return chain;
|
|
1517
|
+
}
|
|
1518
|
+
async function readSockets(root = "/proc") {
|
|
1519
|
+
const tables = [["tcp", "tcp", 4], ["tcp6", "tcp", 6], ["udp", "udp", 4], ["udp6", "udp", 6]];
|
|
1520
|
+
const sockets = [];
|
|
1521
|
+
for (const [file, protocol, family] of tables)
|
|
1522
|
+
sockets.push(...parseNetTable(await text2(`${root}/net/${file}`) ?? "", protocol, family));
|
|
1523
|
+
return sockets;
|
|
1524
|
+
}
|
|
1525
|
+
async function socketsOf(pid, root = "/proc") {
|
|
1526
|
+
const inodes = new Set;
|
|
1527
|
+
try {
|
|
1528
|
+
for (const fd of await readdir(`${root}/${pid}/fd`)) {
|
|
1529
|
+
const inode = socketInode(await link(`${root}/${pid}/fd/${fd}`) ?? "");
|
|
1530
|
+
if (inode !== undefined)
|
|
1531
|
+
inodes.add(inode);
|
|
1532
|
+
}
|
|
1533
|
+
} catch {}
|
|
1534
|
+
return inodes;
|
|
1535
|
+
}
|
|
1536
|
+
async function socketOwners(root = "/proc") {
|
|
1537
|
+
const owners = new Map;
|
|
1538
|
+
for (const pid of await listPids(root)) {
|
|
1539
|
+
for (const inode of await socketsOf(pid, root))
|
|
1540
|
+
owners.set(inode, pid);
|
|
1541
|
+
}
|
|
1542
|
+
return owners;
|
|
1543
|
+
}
|
|
1544
|
+
async function fdCount(pid, root = "/proc") {
|
|
1545
|
+
try {
|
|
1546
|
+
return (await readdir(`${root}/${pid}/fd`)).length;
|
|
1547
|
+
} catch {
|
|
1548
|
+
return;
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
var passwd;
|
|
1552
|
+
async function userName(uid) {
|
|
1553
|
+
passwd ??= await text2("/etc/passwd") ?? "";
|
|
1554
|
+
return userNameOf(passwd, uid);
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
// src/pid.ts
|
|
1558
|
+
var usage2 = `pid <pid>
|
|
1559
|
+
|
|
1560
|
+
Shows what a process is: its executable, working directory, command line, parent chain up to init, user, start time and age, memory, open files and limits, the TCP and UDP ports it listens on and its cgroup. Everything is read from /proc; what the calling user cannot read of another user's process is left out and named at the end.
|
|
1561
|
+
The environment is not shown unless --env is given, with every value that looks like a secret masked.
|
|
1562
|
+
|
|
1563
|
+
Exits 0 when it showed the process, 1 when no process has this pid, 2 on a usage error.`;
|
|
1564
|
+
var DIGITS2 = /^\d+$/;
|
|
1565
|
+
var options = {
|
|
1566
|
+
env: { type: "boolean", description: "show the environment, secrets masked" },
|
|
1567
|
+
json: jsonOption("everything, with the environment under env when --env is given")
|
|
1568
|
+
};
|
|
1569
|
+
async function parentsOf(proc, boot) {
|
|
1570
|
+
const parents = [];
|
|
1571
|
+
const seen = new Set([proc.pid]);
|
|
1572
|
+
let at = proc.ppid;
|
|
1573
|
+
while (at > 0 && !seen.has(at)) {
|
|
1574
|
+
seen.add(at);
|
|
1575
|
+
const parent = await readProc(at, boot, { detail: false });
|
|
1576
|
+
if (parent === undefined)
|
|
1577
|
+
break;
|
|
1578
|
+
parents.push({ pid: parent.pid, comm: parent.comm, command: maskArgs(parent.args).join(" ") });
|
|
1579
|
+
at = parent.ppid;
|
|
1580
|
+
}
|
|
1581
|
+
return parents;
|
|
1582
|
+
}
|
|
1583
|
+
async function report(pid, showEnv) {
|
|
1584
|
+
const boot = await bootMs();
|
|
1585
|
+
const proc = await readProc(pid, boot);
|
|
1586
|
+
if (proc === undefined)
|
|
1587
|
+
return;
|
|
1588
|
+
const unreadable = [];
|
|
1589
|
+
const status = parseStatus(await text2(`/proc/${pid}/status`) ?? "");
|
|
1590
|
+
const limitsText = await text2(`/proc/${pid}/limits`);
|
|
1591
|
+
const sockets = await socketsOf(pid);
|
|
1592
|
+
const listening = sockets.size === 0 ? [] : (await readSockets()).filter((socket) => sockets.has(socket.inode));
|
|
1593
|
+
const environText = showEnv ? await text2(`/proc/${pid}/environ`) : undefined;
|
|
1594
|
+
const cgroup = parseCgroup(await text2(`/proc/${pid}/cgroup`) ?? "")[0]?.path;
|
|
1595
|
+
const files = await fdCount(pid);
|
|
1596
|
+
const stat = parseStat(await text2(`/proc/${pid}/stat`) ?? "");
|
|
1597
|
+
const uid = proc.uid;
|
|
1598
|
+
if (proc.exe === undefined)
|
|
1599
|
+
unreadable.push("executable");
|
|
1600
|
+
if (proc.cwd === undefined)
|
|
1601
|
+
unreadable.push("working directory");
|
|
1602
|
+
if (files === undefined)
|
|
1603
|
+
unreadable.push("open files");
|
|
1604
|
+
if (limitsText === undefined)
|
|
1605
|
+
unreadable.push("limits");
|
|
1606
|
+
if (showEnv && environText === undefined)
|
|
1607
|
+
unreadable.push("environment");
|
|
1608
|
+
return {
|
|
1609
|
+
pid,
|
|
1610
|
+
comm: proc.comm,
|
|
1611
|
+
state: proc.state,
|
|
1612
|
+
exe: proc.exe,
|
|
1613
|
+
cwd: proc.cwd,
|
|
1614
|
+
command: maskArgs(proc.args),
|
|
1615
|
+
parents: await parentsOf(proc, boot),
|
|
1616
|
+
user: { uid, name: await userName(uid) },
|
|
1617
|
+
startedAt: new Date(proc.startMs).toISOString(),
|
|
1618
|
+
ageSeconds: Math.max(0, (Date.now() - proc.startMs) / 1000),
|
|
1619
|
+
threads: stat?.threads,
|
|
1620
|
+
memory: { rss: statusBytes(status, "VmRSS"), peak: statusBytes(status, "VmHWM"), virtual: statusBytes(status, "VmSize"), swap: statusBytes(status, "VmSwap") },
|
|
1621
|
+
openFiles: files,
|
|
1622
|
+
limits: parseLimits(limitsText ?? ""),
|
|
1623
|
+
listening: listening.map(({ protocol, address, port }) => ({ protocol, address, port })),
|
|
1624
|
+
cgroup: cgroup === "" ? undefined : cgroup,
|
|
1625
|
+
container: proc.container,
|
|
1626
|
+
env: environText === undefined ? undefined : maskEnviron(parseEnviron(environText)).map(([name, value]) => ({ name, value })),
|
|
1627
|
+
unreadable
|
|
1628
|
+
};
|
|
1629
|
+
}
|
|
1630
|
+
function limitLine(limits, name) {
|
|
1631
|
+
const limit = limits.find((candidate) => candidate.name === name);
|
|
1632
|
+
return limit === undefined ? "-" : `soft ${limit.soft}, hard ${limit.hard}`;
|
|
1633
|
+
}
|
|
1634
|
+
function render(info, showEnv) {
|
|
1635
|
+
const colors = paint(process12.stdout);
|
|
1636
|
+
const memory = info.memory;
|
|
1637
|
+
const size = (bytes) => bytes === undefined ? "-" : $e(bytes);
|
|
1638
|
+
const rows = [
|
|
1639
|
+
["Executable", info.exe ?? "-"],
|
|
1640
|
+
["Directory", info.cwd ?? "-"],
|
|
1641
|
+
["Command", info.command.join(" ") || `[${info.comm}]`],
|
|
1642
|
+
["Parents", info.parents.length === 0 ? "none (init)" : info.parents.map((parent) => `${parent.pid} ${parent.comm}`).join(" < ")],
|
|
1643
|
+
["User", `${info.user.name ?? "?"} (${info.user.uid})`],
|
|
1644
|
+
["State", info.state],
|
|
1645
|
+
["Started", `${info.startedAt} (${formatSeconds(info.ageSeconds)} ago)`],
|
|
1646
|
+
["Memory", `rss ${size(memory.rss)}, peak ${size(memory.peak)}, virtual ${size(memory.virtual)}, swap ${size(memory.swap)}`],
|
|
1647
|
+
["Open files", `${info.openFiles ?? "-"} (limit ${limitLine(info.limits, "Max open files")})`],
|
|
1648
|
+
["Processes", `${info.threads ?? "-"} threads (limit ${limitLine(info.limits, "Max processes")})`],
|
|
1649
|
+
["Listening", info.listening.length === 0 ? "nothing" : info.listening.map(({ protocol, address, port }) => `${protocol} ${address.includes(":") ? `[${address}]` : address}:${port}`).join(", ")]
|
|
1650
|
+
];
|
|
1651
|
+
if (info.cgroup !== undefined)
|
|
1652
|
+
rows.push(["Cgroup", info.cgroup]);
|
|
1653
|
+
const lines = [colors.bold(`pid ${info.pid} ${info.comm}`), ...rows.map(([label, value]) => `${colors.dim(label.padEnd(11))} ${value}`)];
|
|
1654
|
+
if (showEnv && info.env !== undefined)
|
|
1655
|
+
lines.push("", colors.bold("Environment"), ...info.env.map(({ name, value }) => `${name}=${value}`));
|
|
1656
|
+
else if (!showEnv)
|
|
1657
|
+
lines.push("", colors.dim("Environment hidden, pass --env to show it with secrets masked"));
|
|
1658
|
+
if (info.unreadable.length > 0)
|
|
1659
|
+
lines.push("", colors.yellow(`Could not read: ${info.unreadable.join(", ")} (a process of another user: rerun as that user)`));
|
|
1660
|
+
return lines.join(`
|
|
1661
|
+
`);
|
|
1662
|
+
}
|
|
1663
|
+
async function pid(args) {
|
|
1664
|
+
const { values, positionals } = parse(args, usage2, options, {
|
|
1665
|
+
positionals: ["<pid>"],
|
|
1666
|
+
replaces: "cat /proc/<pid>/{cmdline,environ,limits}, readlink /proc/<pid>/{exe,cwd}, the fish pid function",
|
|
1667
|
+
examples: [
|
|
1668
|
+
["pid 4242", "executable, directory, command, parents, memory, limits and ports"],
|
|
1669
|
+
["pid 4242 --env", "with the environment, secrets masked"],
|
|
1670
|
+
"pid 4242 --json"
|
|
1671
|
+
]
|
|
1672
|
+
});
|
|
1673
|
+
const [given] = positionals;
|
|
1674
|
+
if (!DIGITS2.test(given))
|
|
1675
|
+
fail(`the pid takes a number, not ${given}`, 2);
|
|
1676
|
+
const info = await report(Number(given), values.env === true);
|
|
1677
|
+
if (info === undefined)
|
|
1678
|
+
return fail(`no process with pid ${given}`, 1);
|
|
1679
|
+
if (values.json === true)
|
|
1680
|
+
printJson(info);
|
|
1681
|
+
else
|
|
1682
|
+
console.log(render(info, values.env === true));
|
|
1683
|
+
return 0;
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
// src/ports.ts
|
|
1687
|
+
import { basename as basename2 } from "path";
|
|
1688
|
+
import process14 from "process";
|
|
1689
|
+
|
|
1690
|
+
// ../kit/src/prompt.ts
|
|
1691
|
+
import process13 from "process";
|
|
1692
|
+
|
|
1693
|
+
// ../kit/src/picker/score.ts
|
|
1694
|
+
var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
|
|
1695
|
+
var NONE = Number.NEGATIVE_INFINITY;
|
|
1696
|
+
|
|
1697
|
+
// ../kit/src/picker/state.ts
|
|
1698
|
+
var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
|
|
1699
|
+
var PASTE_START = "\x1B[200~";
|
|
1700
|
+
var PASTE_END = "\x1B[201~";
|
|
1701
|
+
var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
|
|
1702
|
+
var KEYS = {
|
|
1703
|
+
"\x1B[A": "up",
|
|
1704
|
+
"\x1BOA": "up",
|
|
1705
|
+
"\x10": "up",
|
|
1706
|
+
"\x1B[B": "down",
|
|
1707
|
+
"\x1BOB": "down",
|
|
1708
|
+
"\x0E": "down",
|
|
1709
|
+
"\x1B[5~": "pageup",
|
|
1710
|
+
"\x1B[6~": "pagedown",
|
|
1711
|
+
"\x1B[H": "home",
|
|
1712
|
+
"\x1B[1~": "home",
|
|
1713
|
+
"\x1BOH": "home",
|
|
1714
|
+
"\x1B[F": "end",
|
|
1715
|
+
"\x1B[4~": "end",
|
|
1716
|
+
"\x1BOF": "end",
|
|
1717
|
+
"\r": "enter",
|
|
1718
|
+
"\n": "enter",
|
|
1719
|
+
"\x03": "cancel",
|
|
1720
|
+
"\x1B": "cancel",
|
|
1721
|
+
"\x7F": "erase",
|
|
1722
|
+
"\b": "erase",
|
|
1723
|
+
"\x15": "clear",
|
|
1724
|
+
"\x17": "word",
|
|
1725
|
+
"\t": "tab",
|
|
1726
|
+
"\x1F": "help",
|
|
1727
|
+
"\x1BOP": "help",
|
|
1728
|
+
"\x1B[11~": "help"
|
|
1729
|
+
};
|
|
1730
|
+
function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
1731
|
+
const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
|
|
1732
|
+
return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
|
|
1733
|
+
const named = codes.get(sequence);
|
|
1734
|
+
const key = named === undefined ? KEYS[sequence] : { ctrl: named };
|
|
1735
|
+
if (sequence === PASTE_START || sequence === PASTE_END) {
|
|
1736
|
+
paste.active = sequence === PASTE_START;
|
|
1737
|
+
return [];
|
|
1738
|
+
}
|
|
1739
|
+
if (paste.active && (sequence === "\r" || sequence === `
|
|
1740
|
+
`))
|
|
1741
|
+
return [];
|
|
1742
|
+
if (key !== undefined)
|
|
1743
|
+
return [key];
|
|
1744
|
+
return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
|
|
1745
|
+
});
|
|
1746
|
+
}
|
|
1747
|
+
|
|
1748
|
+
// ../kit/src/prompt.ts
|
|
1749
|
+
var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "erase"]);
|
|
1750
|
+
function readKeys(input, paste = { active: false }) {
|
|
1751
|
+
return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key));
|
|
1752
|
+
}
|
|
1753
|
+
async function confirm(question, { default: fallback, ...settings } = {}) {
|
|
1754
|
+
let answered = fallback;
|
|
1755
|
+
const choices = { true: "Y/n", false: "y/N", undefined: "y/n" }[String(fallback)];
|
|
1756
|
+
const accepted = await ask(question, settings, (colors, state) => [state === "asking" ? asking(colors, question, "", choices) : answer(colors, question, state, answered ? "yes" : "no")], (key) => {
|
|
1757
|
+
if (key === "cancel")
|
|
1758
|
+
return "cancel";
|
|
1759
|
+
if (key === "enter")
|
|
1760
|
+
return answered === undefined ? undefined : "enter";
|
|
1761
|
+
const letter = typeof key === "object" ? key.text.toLowerCase() : "";
|
|
1762
|
+
if (letter !== "y" && letter !== "n")
|
|
1763
|
+
return;
|
|
1764
|
+
answered = letter === "y";
|
|
1765
|
+
return "enter";
|
|
1766
|
+
});
|
|
1767
|
+
return accepted ? answered : undefined;
|
|
1768
|
+
}
|
|
1769
|
+
function asking(colors, question, typed, keys) {
|
|
1770
|
+
return `${colors.cyan("?")} ${question} ${typed === "" ? colors.dim(`(${keys})`) : typed}`;
|
|
1771
|
+
}
|
|
1772
|
+
function answer(colors, question, state, picked) {
|
|
1773
|
+
return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
|
|
1774
|
+
}
|
|
1775
|
+
async function ask(question, { hint, terminal = process13 }, render, press) {
|
|
1776
|
+
const { stdin, stderr } = terminal;
|
|
1777
|
+
if (!isInteractive(terminal))
|
|
1778
|
+
fail(`cannot ask "${question}" off a terminal`, 2, hint);
|
|
1779
|
+
const colors = paint(stderr);
|
|
1780
|
+
let drawn = [];
|
|
1781
|
+
let current = "asking";
|
|
1782
|
+
let outcome;
|
|
1783
|
+
const columns = () => stderr.columns || 80;
|
|
1784
|
+
const draw = (state) => {
|
|
1785
|
+
const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
|
|
1786
|
+
const rows = drawn.reduce((sum, line) => sum + Math.max(1, Math.ceil(Bun.stringWidth(line) / columns())), 0);
|
|
1787
|
+
stderr.write(`${rows > 1 ? `\x1B[${rows - 1}A` : ""}\r\x1B[0J${frame.join(`
|
|
1788
|
+
`)}`);
|
|
1789
|
+
drawn = frame;
|
|
1790
|
+
current = state;
|
|
1791
|
+
};
|
|
1792
|
+
const redraw = () => draw(current);
|
|
1793
|
+
const paste = { active: false };
|
|
1794
|
+
try {
|
|
1795
|
+
stderr.on?.("resize", redraw);
|
|
1796
|
+
stdin.setRawMode(true);
|
|
1797
|
+
stdin.resume();
|
|
1798
|
+
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
1799
|
+
draw("asking");
|
|
1800
|
+
return await new Promise((resolve) => {
|
|
1801
|
+
function onData(data) {
|
|
1802
|
+
for (const key of readKeys(data.toString(), paste)) {
|
|
1803
|
+
const pressed = press(key);
|
|
1804
|
+
if (pressed !== undefined) {
|
|
1805
|
+
settle(pressed);
|
|
1806
|
+
return;
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
draw("asking");
|
|
1810
|
+
}
|
|
1811
|
+
function onEnd() {
|
|
1812
|
+
settle("cancel");
|
|
1813
|
+
}
|
|
1814
|
+
function settle(settled) {
|
|
1815
|
+
outcome = settled;
|
|
1816
|
+
stdin.off("data", onData);
|
|
1817
|
+
stdin.off("end", onEnd);
|
|
1818
|
+
resolve(settled === "enter");
|
|
1819
|
+
}
|
|
1820
|
+
stdin.on("data", onData);
|
|
1821
|
+
stdin.on("end", onEnd);
|
|
1822
|
+
});
|
|
1823
|
+
} finally {
|
|
1824
|
+
stderr.off?.("resize", redraw);
|
|
1825
|
+
draw(outcome ?? "cancel");
|
|
1826
|
+
stderr.write(`
|
|
1827
|
+
\x1B[?25h\x1B[?2004l`);
|
|
1828
|
+
stdin.setRawMode(false);
|
|
1829
|
+
stdin.pause();
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1833
|
+
// src/docker.ts
|
|
1834
|
+
var FORMAT = '{{.Names}}\t{{.Ports}}\t{{.Label "com.docker.compose.project"}}\t{{.Label "com.docker.compose.service"}}';
|
|
1835
|
+
async function dockerContainers() {
|
|
1836
|
+
if (Bun.which("docker") === null)
|
|
1837
|
+
return [];
|
|
1838
|
+
try {
|
|
1839
|
+
const ran = await runCommand(["docker", "ps", "--format", FORMAT], { timeoutMs: 4000 });
|
|
1840
|
+
return ran.code === 0 ? parseDockerPs(ran.text) : [];
|
|
1841
|
+
} catch {
|
|
1842
|
+
return [];
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1846
|
+
// src/kill.ts
|
|
1847
|
+
var SHELLS = new Set(["sh", "bash", "zsh", "fish", "dash", "ash", "nu", "tcsh", "ksh", "elvish", "xonsh"]);
|
|
1848
|
+
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"]);
|
|
1849
|
+
function protectionOf(proc, { uid, mine }) {
|
|
1850
|
+
if (proc.pid === 1)
|
|
1851
|
+
return "pid 1";
|
|
1852
|
+
if (proc.uid !== uid)
|
|
1853
|
+
return "another user's process";
|
|
1854
|
+
if (mine.has(proc.pid))
|
|
1855
|
+
return "this command or one of its ancestors";
|
|
1856
|
+
if (SHELLS.has(proc.comm))
|
|
1857
|
+
return "a shell";
|
|
1858
|
+
return TERMINALS.has(proc.comm) ? "a terminal" : undefined;
|
|
1859
|
+
}
|
|
1860
|
+
var realSignaller = {
|
|
1861
|
+
send(pid, signal) {
|
|
1862
|
+
try {
|
|
1863
|
+
process.kill(pid, signal);
|
|
1864
|
+
return true;
|
|
1865
|
+
} catch {
|
|
1866
|
+
return false;
|
|
1867
|
+
}
|
|
1868
|
+
},
|
|
1869
|
+
async alive(pid) {
|
|
1870
|
+
const stat = await text2(`/proc/${pid}/stat`);
|
|
1871
|
+
return stat !== undefined && !stat.slice(stat.lastIndexOf(")") + 2).startsWith("Z");
|
|
1872
|
+
},
|
|
1873
|
+
sleep: async (ms) => Bun.sleep(ms)
|
|
1874
|
+
};
|
|
1875
|
+
var POLL_MS = 100;
|
|
1876
|
+
async function waitGone(pids, graceMs, signaller) {
|
|
1877
|
+
let alive = pids;
|
|
1878
|
+
let waited = 0;
|
|
1879
|
+
while (alive.length > 0 && waited < graceMs) {
|
|
1880
|
+
await signaller.sleep(POLL_MS);
|
|
1881
|
+
waited += POLL_MS;
|
|
1882
|
+
alive = await filterAlive(alive, signaller);
|
|
1883
|
+
}
|
|
1884
|
+
return alive;
|
|
1885
|
+
}
|
|
1886
|
+
async function filterAlive(pids, signaller) {
|
|
1887
|
+
const alive = [];
|
|
1888
|
+
for (const pid of pids) {
|
|
1889
|
+
if (await signaller.alive(pid))
|
|
1890
|
+
alive.push(pid);
|
|
1891
|
+
}
|
|
1892
|
+
return alive;
|
|
1893
|
+
}
|
|
1894
|
+
async function terminate(pids, { escalate, graceMs, signaller = realSignaller }) {
|
|
1895
|
+
const failed = pids.filter((pid) => !signaller.send(pid, "SIGTERM"));
|
|
1896
|
+
const refused = await filterAlive(failed, signaller);
|
|
1897
|
+
const sent = pids.filter((pid) => !failed.includes(pid));
|
|
1898
|
+
const remaining = await waitGone(sent, graceMs, signaller);
|
|
1899
|
+
const terminated = pids.filter((pid) => failed.includes(pid) ? !refused.includes(pid) : !remaining.includes(pid));
|
|
1900
|
+
if (!escalate || remaining.length === 0)
|
|
1901
|
+
return { terminated, killed: [], survived: [...refused, ...remaining] };
|
|
1902
|
+
for (const pid of remaining)
|
|
1903
|
+
signaller.send(pid, "SIGKILL");
|
|
1904
|
+
const stuck = await waitGone(remaining, 2000, signaller);
|
|
1905
|
+
return { terminated, killed: remaining.filter((pid) => !stuck.includes(pid)), survived: [...refused, ...stuck] };
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
// src/ports.ts
|
|
1909
|
+
var usage3 = `ports [port]
|
|
1910
|
+
|
|
1911
|
+
Lists what listens on this machine, TCP and UDP over IPv4 and IPv6, one row per port with its bound address, the owning process, its command and its working directory. A port Docker publishes is held by docker-proxy, and shows as its compose project and service when docker is installed; the owner of a socket of another user cannot be read and shows as -.
|
|
1912
|
+
\`ports <port>\` keeps that port alone and exits 1 when nothing listens on it.
|
|
1913
|
+
\`ports <port> --kill\` stops its owner with SIGTERM, and with --force SIGKILL once --grace has passed, after asking on a terminal unless --yes is given. It refuses processes of other users, pid 1, this command and its ancestors, and docker-proxy, for which it names the container to stop instead.
|
|
1914
|
+
|
|
1915
|
+
Exits 0 when it listed or stopped, 1 when nothing listens on the given port or the owner could not be stopped, 2 on a usage error.`;
|
|
1916
|
+
var options2 = {
|
|
1917
|
+
json: jsonOption("[{ port, protocol, addresses, pid, command, cwd, container }]"),
|
|
1918
|
+
kill: { type: "boolean", conflicts: ["watch"], description: "stop the owner of the given port" },
|
|
1919
|
+
watch: watchOption("the ports"),
|
|
1920
|
+
force: { type: "boolean", description: "with --kill, SIGKILL what SIGTERM did not stop within --grace" },
|
|
1921
|
+
yes: { type: "boolean", short: "y", description: "with --kill, do not ask first" },
|
|
1922
|
+
grace: { type: "string", description: "with --force, how long SIGTERM gets before SIGKILL (5s)" }
|
|
1923
|
+
};
|
|
1924
|
+
function buildRows(sockets, owners, procs, containers) {
|
|
1925
|
+
const rows = new Map;
|
|
1926
|
+
for (const socket of sockets) {
|
|
1927
|
+
const pid = owners.get(socket.inode);
|
|
1928
|
+
const proc = pid === undefined ? undefined : procs.get(pid);
|
|
1929
|
+
const key = `${socket.protocol}/${socket.port}/${pid ?? "unknown"}`;
|
|
1930
|
+
const row = rows.get(key);
|
|
1931
|
+
if (row !== undefined) {
|
|
1932
|
+
if (!row.addresses.includes(socket.address))
|
|
1933
|
+
row.addresses.push(socket.address);
|
|
1934
|
+
continue;
|
|
1935
|
+
}
|
|
1936
|
+
const held = proc === undefined || proc.comm === "docker-proxy";
|
|
1937
|
+
const container = held ? containers.find((candidate) => candidate.published.some((port) => port.host === socket.port && port.protocol === socket.protocol)) : undefined;
|
|
1938
|
+
rows.set(key, {
|
|
1939
|
+
port: socket.port,
|
|
1940
|
+
protocol: socket.protocol,
|
|
1941
|
+
addresses: [socket.address],
|
|
1942
|
+
pid,
|
|
1943
|
+
command: proc === undefined ? undefined : maskArgs([basename2(proc.args[0] ?? proc.comm), ...proc.args.slice(1)]).join(" "),
|
|
1944
|
+
cwd: proc?.cwd,
|
|
1945
|
+
uid: proc?.uid ?? socket.uid,
|
|
1946
|
+
container: container === undefined ? undefined : { name: container.name, project: container.project, service: container.service }
|
|
1947
|
+
});
|
|
1948
|
+
}
|
|
1949
|
+
return [...rows.values()].sort((a, b) => a.port - b.port || a.protocol.localeCompare(b.protocol) || (a.pid ?? 0) - (b.pid ?? 0));
|
|
1950
|
+
}
|
|
1951
|
+
function containerLabel(container) {
|
|
1952
|
+
return container.project === undefined ? container.name : `${container.project}/${container.service ?? container.name}`;
|
|
1953
|
+
}
|
|
1954
|
+
function refusal(row, proc, guard) {
|
|
1955
|
+
if (row.container !== undefined && (proc === undefined || proc.comm === "docker-proxy"))
|
|
1956
|
+
return `published by the container ${row.container.name} (${containerLabel(row.container)}): stop it with \`docker stop ${row.container.name}\``;
|
|
1957
|
+
if (proc === undefined || row.pid === undefined)
|
|
1958
|
+
return "its owner is not readable (another user's process): rerun as that user";
|
|
1959
|
+
const reason = protectionOf(proc, guard);
|
|
1960
|
+
return reason === undefined ? undefined : `pid ${row.pid} is ${reason}`;
|
|
1961
|
+
}
|
|
1962
|
+
function render2(rows) {
|
|
1963
|
+
const colors = paint(process14.stdout);
|
|
1964
|
+
const cells = rows.map((row) => [
|
|
1965
|
+
colors.cyan(String(row.port)),
|
|
1966
|
+
row.protocol,
|
|
1967
|
+
row.addresses.join(", "),
|
|
1968
|
+
row.pid === undefined ? "-" : String(row.pid),
|
|
1969
|
+
row.container === undefined ? truncate(row.command ?? "-", 60) : colors.yellow(`docker ${containerLabel(row.container)}`),
|
|
1970
|
+
colors.dim(row.cwd ?? "-")
|
|
1971
|
+
]);
|
|
1972
|
+
return table([["PORT", "PROTO", "ADDRESS", "PID", "COMMAND", "CWD"], ...cells], { header: true });
|
|
1973
|
+
}
|
|
1974
|
+
async function stop(port, rows, procs, values) {
|
|
1975
|
+
const guard = { uid: process14.getuid?.() ?? -1, mine: new Set(ancestry(process14.pid, procs)) };
|
|
1976
|
+
const targets = new Map;
|
|
1977
|
+
for (const row of rows) {
|
|
1978
|
+
const reason = refusal(row, row.pid === undefined ? undefined : procs.get(row.pid), guard);
|
|
1979
|
+
if (reason !== undefined)
|
|
1980
|
+
console.error(`port ${port}: ${reason}`);
|
|
1981
|
+
else if (row.pid !== undefined)
|
|
1982
|
+
targets.set(row.pid, row);
|
|
1983
|
+
}
|
|
1984
|
+
if (targets.size === 0)
|
|
1985
|
+
return 1;
|
|
1986
|
+
const names = [...targets].map(([pid, row]) => `${pid} (${truncate(row.command ?? "", 40)})`).join(", ");
|
|
1987
|
+
if (values.yes !== true) {
|
|
1988
|
+
if (!process14.stdin.isTTY)
|
|
1989
|
+
fail(`stopping ${names} needs a terminal to ask on: pass --yes`, 2);
|
|
1990
|
+
if (await confirm(`Stop ${names}?`, { default: false }) !== true)
|
|
1991
|
+
return 1;
|
|
1992
|
+
}
|
|
1993
|
+
const outcome = await terminate([...targets.keys()], { escalate: values.force === true, graceMs: duration(values.grace, "grace", 5000) });
|
|
1994
|
+
for (const pid of [...outcome.terminated, ...outcome.killed])
|
|
1995
|
+
console.log(`stopped ${pid}${outcome.killed.includes(pid) ? " (SIGKILL)" : ""}`);
|
|
1996
|
+
for (const pid of outcome.survived)
|
|
1997
|
+
console.error(`${pid} is still running${values.force === true ? "" : ", pass --force to SIGKILL it"}`);
|
|
1998
|
+
return outcome.survived.length === 0 ? 0 : 1;
|
|
1999
|
+
}
|
|
2000
|
+
async function ports(args) {
|
|
2001
|
+
const { values, positionals } = parse(args, usage3, options2, {
|
|
2002
|
+
positionals: ["[port]"],
|
|
2003
|
+
replaces: "ss -ltnp | grep, lsof -i, fuser -k and lookups of docker-proxy by hand",
|
|
2004
|
+
examples: [
|
|
2005
|
+
["ports", "every listening port with its owner"],
|
|
2006
|
+
["ports 3000", "who holds 3000, exit 1 when nobody does"],
|
|
2007
|
+
["ports 3000 --kill --yes", "stop it"],
|
|
2008
|
+
"ports --json"
|
|
2009
|
+
]
|
|
2010
|
+
});
|
|
2011
|
+
if (values.watch !== undefined)
|
|
2012
|
+
return watching(values.watch, async () => ports(withoutWatch(args)));
|
|
2013
|
+
const [given] = positionals;
|
|
2014
|
+
const port = given === undefined ? undefined : wholeNumber(given, "<port>", 0);
|
|
2015
|
+
if (port !== undefined && port > 65535)
|
|
2016
|
+
badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`);
|
|
2017
|
+
if (values.kill === true && port === undefined)
|
|
2018
|
+
badUsage("--kill takes the port to free: ports <port> --kill");
|
|
2019
|
+
const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process14.getuid?.())]);
|
|
2020
|
+
const byPid = new Map(procs.map((proc) => [proc.pid, proc]));
|
|
2021
|
+
const wanted = sockets.filter((socket) => port === undefined || socket.port === port);
|
|
2022
|
+
const needsDocker = wanted.some((socket) => {
|
|
2023
|
+
const pid = owners.get(socket.inode);
|
|
2024
|
+
return pid === undefined || byPid.get(pid)?.comm === "docker-proxy";
|
|
2025
|
+
});
|
|
2026
|
+
const rows = buildRows(wanted, owners, byPid, needsDocker ? await dockerContainers() : []);
|
|
2027
|
+
if (port !== undefined && rows.length === 0) {
|
|
2028
|
+
console.error(`nothing listens on port ${port}`);
|
|
2029
|
+
return 1;
|
|
2030
|
+
}
|
|
2031
|
+
if (values.kill === true && port !== undefined)
|
|
2032
|
+
return stop(port, rows, byPid, values);
|
|
2033
|
+
if (values.json === true) {
|
|
2034
|
+
printJson(rows);
|
|
2035
|
+
return 0;
|
|
2036
|
+
}
|
|
2037
|
+
console.log(render2(rows));
|
|
2038
|
+
const unknown = rows.filter((row) => row.pid === undefined && row.container === undefined).length;
|
|
2039
|
+
if (unknown > 0)
|
|
2040
|
+
console.error(paint(process14.stderr).dim(`${unknown} ${unknown === 1 ? "port has" : "ports have"} an owner this user cannot read, shown as -`));
|
|
2041
|
+
return 0;
|
|
2042
|
+
}
|
|
2043
|
+
|
|
2044
|
+
// src/procs.ts
|
|
2045
|
+
import { existsSync } from "fs";
|
|
2046
|
+
import { homedir as homedir2 } from "os";
|
|
2047
|
+
import process15 from "process";
|
|
2048
|
+
|
|
2049
|
+
// src/select.ts
|
|
2050
|
+
import { basename as basename3, join as join3, relative } from "path";
|
|
2051
|
+
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;
|
|
2052
|
+
var NATIVE = new Set(["rust-analyzer", "gopls", "clangd", "lua-language-server", "pyright-langserver", "pylsp", "intelephense", "phpactor", "tsgo", "esbuild", "biome", "ruff", "phpunit", "pytest", "vitest", "jest"]);
|
|
2053
|
+
var RUNTIMES = new Set(["node", "bun", "bunx", "deno", "nodejs"]);
|
|
2054
|
+
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"]);
|
|
2055
|
+
var EXTENSION = /\.[cm]?[jt]s$/;
|
|
2056
|
+
var MARKERS = ["package.json", "composer.json", "Cargo.toml", "go.mod", "pyproject.toml"];
|
|
2057
|
+
var AUTOMATION = /^--(?:headless|remote-debugging-(?:pipe|port)|enable-automation)/;
|
|
2058
|
+
var HEAVY_DEFAULT = 500 * 1024 ** 2;
|
|
2059
|
+
function toolOf(proc) {
|
|
2060
|
+
const names = [proc.exe, proc.args[0], proc.comm].filter((name) => name !== undefined && name !== "").map((name) => basename3(name));
|
|
2061
|
+
for (const name of names) {
|
|
2062
|
+
if (BROWSERS.test(name))
|
|
2063
|
+
return name.toLowerCase().startsWith("webkit") || name.toLowerCase().startsWith("wpe") || name.toLowerCase() === "minibrowser" ? "webkit" : "chromium";
|
|
2064
|
+
if (NATIVE.has(name))
|
|
2065
|
+
return name;
|
|
2066
|
+
}
|
|
2067
|
+
const runtime = names.find((name) => RUNTIMES.has(name));
|
|
2068
|
+
if (runtime === undefined)
|
|
2069
|
+
return;
|
|
2070
|
+
for (const arg of proc.args.slice(1)) {
|
|
2071
|
+
if (arg.startsWith("-"))
|
|
2072
|
+
continue;
|
|
2073
|
+
const script = basename3(arg).replace(EXTENSION, "");
|
|
2074
|
+
if (SCRIPTS.has(script))
|
|
2075
|
+
return script;
|
|
2076
|
+
}
|
|
2077
|
+
return runtime === "nodejs" ? "node" : runtime;
|
|
2078
|
+
}
|
|
2079
|
+
function userDataDir(args) {
|
|
2080
|
+
const arg = args.find((word) => word.startsWith("--user-data-dir="));
|
|
2081
|
+
return arg?.slice("--user-data-dir=".length);
|
|
2082
|
+
}
|
|
2083
|
+
function projectOf(cwd, exists, home) {
|
|
2084
|
+
if (cwd === undefined || !cwd.startsWith(`${home}/`))
|
|
2085
|
+
return;
|
|
2086
|
+
const folders = [];
|
|
2087
|
+
for (let dir = cwd;dir.startsWith(`${home}/`); dir = join3(dir, ".."))
|
|
2088
|
+
folders.push(dir);
|
|
2089
|
+
return folders.find((dir) => exists(join3(dir, ".git"))) ?? folders.find((dir) => MARKERS.some((marker) => exists(join3(dir, marker))));
|
|
2090
|
+
}
|
|
2091
|
+
function isOrphan(proc, byPid) {
|
|
2092
|
+
if (proc.unit?.endsWith(".service") === true)
|
|
2093
|
+
return false;
|
|
2094
|
+
const parent = byPid.get(proc.ppid);
|
|
2095
|
+
const userManager = parent !== undefined && parent.comm === "systemd" && parent.uid === proc.uid && parent.uid !== 0;
|
|
2096
|
+
const reparented = proc.ppid === 1 || userManager;
|
|
2097
|
+
const tool = toolOf(proc);
|
|
2098
|
+
if (!reparented || tool !== "chromium" && tool !== "webkit")
|
|
2099
|
+
return reparented;
|
|
2100
|
+
if (basename3(proc.exe ?? proc.args[0] ?? proc.comm).includes("crashpad"))
|
|
2101
|
+
return false;
|
|
2102
|
+
return proc.args.some((arg) => arg.startsWith("--type=")) || proc.args.some((arg) => AUTOMATION.test(arg));
|
|
2103
|
+
}
|
|
2104
|
+
function originOf(proc, tool, { exists, home }) {
|
|
2105
|
+
const profile = userDataDir(proc.args);
|
|
2106
|
+
if (profile !== undefined)
|
|
2107
|
+
return { key: `profile:${profile}`, origin: `${tool} profile ${profile}`, kind: "profile" };
|
|
2108
|
+
const project = projectOf(proc.cwd, exists, home);
|
|
2109
|
+
if (project !== undefined)
|
|
2110
|
+
return { key: `project:${project}`, origin: `~/${relative(home, project)}`, kind: "project" };
|
|
2111
|
+
return { key: `command:${tool}`, origin: tool, kind: "command" };
|
|
2112
|
+
}
|
|
2113
|
+
function selectGroups(procs, options) {
|
|
2114
|
+
const byPid = new Map(procs.map((proc) => [proc.pid, proc]));
|
|
2115
|
+
const heavyFrom = options.minMem ?? HEAVY_DEFAULT;
|
|
2116
|
+
const candidates = procs.filter((proc) => proc.uid === options.guard.uid && proc.pid !== 1 && toolOf(proc) !== undefined);
|
|
2117
|
+
const chosen = new Map;
|
|
2118
|
+
let protectedCount = 0;
|
|
2119
|
+
for (const proc of candidates) {
|
|
2120
|
+
const ageMs = options.now - proc.startMs;
|
|
2121
|
+
const orphan = isOrphan(proc, byPid);
|
|
2122
|
+
const heavy = proc.rss >= heavyFrom;
|
|
2123
|
+
if (!(heavy || orphan && proc.rss >= (options.minMem ?? 0)) || ageMs < (options.olderMs ?? 0))
|
|
2124
|
+
continue;
|
|
2125
|
+
if (protectionOf(proc, options.guard) !== undefined) {
|
|
2126
|
+
protectedCount++;
|
|
2127
|
+
continue;
|
|
2128
|
+
}
|
|
2129
|
+
chosen.set(proc.pid, { orphan, heavy });
|
|
2130
|
+
}
|
|
2131
|
+
const profiles = new Set([...chosen.keys()].map((pid) => userDataDir(byPid.get(pid).args)).filter((dir) => dir !== undefined));
|
|
2132
|
+
let grew = true;
|
|
2133
|
+
while (grew) {
|
|
2134
|
+
grew = false;
|
|
2135
|
+
for (const proc of candidates) {
|
|
2136
|
+
const dir = userDataDir(proc.args);
|
|
2137
|
+
const joins = chosen.has(proc.ppid) || dir !== undefined && profiles.has(dir);
|
|
2138
|
+
if (chosen.has(proc.pid) || !joins || protectionOf(proc, options.guard) !== undefined)
|
|
2139
|
+
continue;
|
|
2140
|
+
chosen.set(proc.pid, { orphan: isOrphan(proc, byPid), heavy: proc.rss >= heavyFrom });
|
|
2141
|
+
grew = true;
|
|
2142
|
+
}
|
|
2143
|
+
}
|
|
2144
|
+
const groups = new Map;
|
|
2145
|
+
for (const [pid, flags] of chosen) {
|
|
2146
|
+
const proc = byPid.get(pid);
|
|
2147
|
+
const tool = toolOf(proc);
|
|
2148
|
+
const { key, origin, kind } = originOf(proc, tool, options);
|
|
2149
|
+
const group = groups.get(key) ?? { key, origin, kind, members: [], rss: 0, oldestMs: 0, orphans: 0 };
|
|
2150
|
+
const ageMs = options.now - proc.startMs;
|
|
2151
|
+
group.members.push({ proc, tool, ageMs, ...flags });
|
|
2152
|
+
group.rss += proc.rss;
|
|
2153
|
+
group.oldestMs = Math.max(group.oldestMs, ageMs);
|
|
2154
|
+
group.orphans += flags.orphan ? 1 : 0;
|
|
2155
|
+
groups.set(key, group);
|
|
2156
|
+
}
|
|
2157
|
+
for (const group of groups.values())
|
|
2158
|
+
group.members.sort((a, b) => a.proc.pid - b.proc.pid);
|
|
2159
|
+
return { groups: [...groups.values()].sort((a, b) => b.rss - a.rss), protectedCount };
|
|
2160
|
+
}
|
|
2161
|
+
|
|
2162
|
+
// src/procs.ts
|
|
2163
|
+
var usage4 = `procs
|
|
2164
|
+
|
|
2165
|
+
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.
|
|
2166
|
+
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.
|
|
2167
|
+
\`--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.
|
|
2168
|
+
|
|
2169
|
+
Exits 0 when it listed or stopped everything, 1 when a process survived SIGKILL, 2 on a usage error.`;
|
|
2170
|
+
var options3 = {
|
|
2171
|
+
json: jsonOption("{ groups: [{ origin, kind, count, rss, oldestSeconds, tools, orphans, pids, processes }], skipped }"),
|
|
2172
|
+
kill: { type: "boolean", conflicts: ["watch"], description: "stop the listed processes: a dry run without --yes" },
|
|
2173
|
+
watch: watchOption("the processes"),
|
|
2174
|
+
yes: { type: "boolean", short: "y", description: "with --kill, really stop them, without asking" },
|
|
2175
|
+
"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" },
|
|
2176
|
+
older: { type: "string", description: "only processes at least this old: 30m, 2h, 1d" },
|
|
2177
|
+
grace: { type: "string", description: "how long SIGTERM gets before SIGKILL (5s)" }
|
|
2178
|
+
};
|
|
2179
|
+
function summary(group) {
|
|
2180
|
+
const tools = {};
|
|
2181
|
+
for (const { tool } of group.members)
|
|
2182
|
+
tools[tool] = (tools[tool] ?? 0) + 1;
|
|
2183
|
+
return {
|
|
2184
|
+
origin: group.origin,
|
|
2185
|
+
kind: group.kind,
|
|
2186
|
+
count: group.members.length,
|
|
2187
|
+
rss: group.rss,
|
|
2188
|
+
oldestSeconds: Math.round(group.oldestMs / 1000),
|
|
2189
|
+
tools,
|
|
2190
|
+
orphans: group.orphans,
|
|
2191
|
+
pids: group.members.map(({ proc }) => proc.pid),
|
|
2192
|
+
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 }))
|
|
2193
|
+
};
|
|
2194
|
+
}
|
|
2195
|
+
function render3(groups) {
|
|
2196
|
+
const colors = paint(process15.stdout);
|
|
2197
|
+
const rows = groups.map((group) => [
|
|
2198
|
+
group.origin,
|
|
2199
|
+
String(group.members.length),
|
|
2200
|
+
$e(group.rss),
|
|
2201
|
+
formatSeconds(group.oldestMs / 1000),
|
|
2202
|
+
colors.dim(truncate(Object.entries(Object.groupBy(group.members, ({ tool }) => tool)).map(([tool, list]) => `${tool}${list.length > 1 ? ` x${list.length}` : ""}`).join(", "), 50)),
|
|
2203
|
+
group.orphans === 0 ? "" : colors.yellow(`${group.orphans} orphaned`)
|
|
2204
|
+
]);
|
|
2205
|
+
return table([["ORIGIN", "PROCS", "RSS", "OLDEST", "WHAT", ""], ...rows], { header: true, align: ["left", "right", "right", "right"] });
|
|
2206
|
+
}
|
|
2207
|
+
async function procs(args) {
|
|
2208
|
+
const { values } = parse(args, usage4, options3, {
|
|
2209
|
+
replaces: "pkill -f and pgrep -f one-liners (which match their own shell), ps aux | grep for leftover chromium, bun or vite processes",
|
|
2210
|
+
examples: [
|
|
2211
|
+
["procs", "leftover and heavy dev processes, by origin"],
|
|
2212
|
+
["procs --min-mem 1G --older 1h", "only the big ones that have run a while"],
|
|
2213
|
+
["procs --kill", "dry run: what would be stopped"],
|
|
2214
|
+
"procs --kill --yes"
|
|
2215
|
+
]
|
|
2216
|
+
});
|
|
2217
|
+
const minMem = values["min-mem"] === undefined ? undefined : parseSize(values["min-mem"], 1024 ** 2);
|
|
2218
|
+
if (values["min-mem"] !== undefined && minMem === undefined)
|
|
2219
|
+
fail(`--min-mem takes a size such as 500M or 1.5G, not ${values["min-mem"]}`, 2);
|
|
2220
|
+
if (values.watch !== undefined)
|
|
2221
|
+
return watching(values.watch, async () => procs(withoutWatch(args)));
|
|
2222
|
+
const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0, "m");
|
|
2223
|
+
const uid = process15.getuid?.() ?? -1;
|
|
2224
|
+
const all = await snapshot("/proc", (owner) => owner === uid);
|
|
2225
|
+
const mine = new Set(ancestry(process15.pid, new Map(all.map((proc) => [proc.pid, proc]))));
|
|
2226
|
+
const { groups, protectedCount } = selectGroups(all, { guard: { uid, mine }, now: Date.now(), home: homedir2(), exists: existsSync, minMem, olderMs });
|
|
2227
|
+
const pids = groups.flatMap((group) => group.members.map(({ proc }) => proc.pid));
|
|
2228
|
+
const show = (extra = {}) => {
|
|
2229
|
+
if (values.json === true)
|
|
2230
|
+
printJson({ groups: groups.map(summary), skipped: protectedCount, ...extra });
|
|
2231
|
+
else
|
|
2232
|
+
console.log(groups.length === 0 ? "nothing to clean" : render3(groups));
|
|
2233
|
+
};
|
|
2234
|
+
if (values.kill !== true || pids.length === 0 || values.yes !== true) {
|
|
2235
|
+
show();
|
|
2236
|
+
if (values.json !== true && protectedCount > 0)
|
|
2237
|
+
console.error(paint(process15.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`));
|
|
2238
|
+
if (values.kill === true && pids.length > 0)
|
|
2239
|
+
console.error(`dry run: would stop ${pids.length} ${pids.length === 1 ? "process" : "processes"} (${pids.join(" ")}), pass --yes to do it`);
|
|
2240
|
+
return 0;
|
|
2241
|
+
}
|
|
2242
|
+
const outcome = await terminate(pids, { escalate: true, graceMs: duration(values.grace, "grace", 5000) });
|
|
2243
|
+
show({ stopped: [...outcome.terminated, ...outcome.killed], killed: outcome.killed, survived: outcome.survived });
|
|
2244
|
+
if (values.json !== true)
|
|
2245
|
+
console.log(`stopped ${outcome.terminated.length + outcome.killed.length} of ${pids.length}${outcome.killed.length === 0 ? "" : `, ${outcome.killed.length} needed SIGKILL`}`);
|
|
2246
|
+
if (outcome.survived.length > 0)
|
|
2247
|
+
console.error(`still running: ${outcome.survived.join(" ")}`);
|
|
2248
|
+
return outcome.survived.length === 0 ? 0 : 1;
|
|
2249
|
+
}
|
|
2250
|
+
|
|
2251
|
+
// src/proc-cli.ts
|
|
2252
|
+
process16.exitCode = await runCli({
|
|
2253
|
+
name: "proc",
|
|
2254
|
+
about: "what a process is, who listens on a port and which dev processes are worth cleaning, read from /proc",
|
|
2255
|
+
replaces: "cat /proc/<pid>/..., ss -ltnp, lsof -i and pgrep -f one-liners",
|
|
2256
|
+
examples: ["proc pid 1234", "proc ports", ["proc procs", "the leftover or heavy processes, dry-run first"]],
|
|
2257
|
+
commands: {
|
|
2258
|
+
pid: { summary: "what a process is: executable, parents, memory, limits and listening ports", run: pid },
|
|
2259
|
+
ports: { summary: "what listens on this machine, with its owner, and a safe --kill", run: ports },
|
|
2260
|
+
procs: { summary: "the leftover or heavy processes of the calling user, grouped by origin", run: procs }
|
|
2261
|
+
}
|
|
2262
|
+
});
|