@kaynooo/cli-proc 0.7.5 → 0.8.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 +10 -10
- package/dist/proc-cli.js +17 -41
- package/package.json +9 -15
- package/src/pid.ts +4 -4
- package/src/ports.ts +8 -8
- package/src/procs.ts +5 -5
- package/dist/pid-cli.js +0 -1890
- package/dist/ports-cli.js +0 -2155
- package/dist/procs-cli.js +0 -2032
- package/src/pid-cli.ts +0 -7
- package/src/ports-cli.ts +0 -7
- package/src/procs-cli.ts +0 -7
package/dist/pid-cli.js
DELETED
|
@@ -1,1890 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
2
|
-
// @bun
|
|
3
|
-
|
|
4
|
-
// src/pid-cli.ts
|
|
5
|
-
import process18 from "process";
|
|
6
|
-
// ../kit/src/args.ts
|
|
7
|
-
import process9 from "process";
|
|
8
|
-
import { parseArgs } from "util";
|
|
9
|
-
|
|
10
|
-
// ../kit/src/format.ts
|
|
11
|
-
import process7 from "process";
|
|
12
|
-
|
|
13
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-n6z2kk96.js
|
|
14
|
-
var r = new Map;
|
|
15
|
-
var i = new Map;
|
|
16
|
-
var l = new Map;
|
|
17
|
-
function a(e, t, o) {
|
|
18
|
-
return JSON.stringify([e ?? null, t ?? null, o]);
|
|
19
|
-
}
|
|
20
|
-
function y(e, t) {
|
|
21
|
-
let o = a(e, t), n = i.get(o);
|
|
22
|
-
if (!n)
|
|
23
|
-
n = new Intl.NumberFormat(e, t), i.set(o, n);
|
|
24
|
-
return n;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
|
|
28
|
-
var N = new Map;
|
|
29
|
-
var Nt = /\s+\S*$/;
|
|
30
|
-
var Y = /\s/;
|
|
31
|
-
function ko(t, e, r = "...") {
|
|
32
|
-
let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
|
|
33
|
-
if (t.length <= e)
|
|
34
|
-
return t;
|
|
35
|
-
let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
|
|
36
|
-
if (o && !Y.test(t[c.length] ?? " "))
|
|
37
|
-
c = c.replace(Nt, "") || c;
|
|
38
|
-
if (o)
|
|
39
|
-
c = c.trimEnd();
|
|
40
|
-
return s ? (c + n).slice(0, l) : c + n;
|
|
41
|
-
}
|
|
42
|
-
var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
|
|
43
|
-
var z = new Map;
|
|
44
|
-
|
|
45
|
-
// ../kit/src/mode.ts
|
|
46
|
-
import process2 from "process";
|
|
47
|
-
var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
48
|
-
var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
49
|
-
function isSet(value) {
|
|
50
|
-
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
51
|
-
}
|
|
52
|
-
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
53
|
-
const chosen = env.KIT_MODE;
|
|
54
|
-
if (chosen !== undefined && MODES.has(chosen))
|
|
55
|
-
return chosen;
|
|
56
|
-
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
57
|
-
return "agent";
|
|
58
|
-
if (stream.isTTY === true)
|
|
59
|
-
return "terminal";
|
|
60
|
-
return isSet(env.CI) ? "ci" : "pipe";
|
|
61
|
-
}
|
|
62
|
-
function isInteractive(streams = process2) {
|
|
63
|
-
return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// ../kit/src/style.ts
|
|
67
|
-
import process6 from "process";
|
|
68
|
-
|
|
69
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
70
|
-
var G2 = /^[a-f0-9]+$/i;
|
|
71
|
-
function b(r) {
|
|
72
|
-
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
73
|
-
if (!G2.test(e))
|
|
74
|
-
return [0, 0, 0];
|
|
75
|
-
if (e.length === 3 || e.length === 4)
|
|
76
|
-
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
77
|
-
if (e.length !== 6 && e.length !== 8)
|
|
78
|
-
throw Error(`Invalid hex color length: ${e.length}`);
|
|
79
|
-
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
80
|
-
}
|
|
81
|
-
var B2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
|
|
82
|
-
let [l, n, c] = b(r);
|
|
83
|
-
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
84
|
-
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
85
|
-
var h = new Set(["", "1", "2", "3", "true"]);
|
|
86
|
-
function C(r, e = globalThis.process?.env ?? {}) {
|
|
87
|
-
if (e.FORCE_COLOR !== undefined)
|
|
88
|
-
return h.has(e.FORCE_COLOR);
|
|
89
|
-
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
90
|
-
return false;
|
|
91
|
-
return r?.isTTY === true;
|
|
92
|
-
}
|
|
93
|
-
function f(r, e = []) {
|
|
94
|
-
let l = "", n = "";
|
|
95
|
-
for (let t = 0, i = e.length;t < i; t++)
|
|
96
|
-
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
97
|
-
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
98
|
-
return new Proxy(c, { get(t, i) {
|
|
99
|
-
let a = B2[i];
|
|
100
|
-
if (Array.isArray(a)) {
|
|
101
|
-
let s = g.get(i);
|
|
102
|
-
if (s === undefined)
|
|
103
|
-
s = f(r, [...e, a]), g.set(i, s);
|
|
104
|
-
return s;
|
|
105
|
-
}
|
|
106
|
-
if (typeof a === "function")
|
|
107
|
-
return (...s) => {
|
|
108
|
-
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
109
|
-
if (u === undefined) {
|
|
110
|
-
if (g.size >= 64)
|
|
111
|
-
g.clear();
|
|
112
|
-
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
113
|
-
}
|
|
114
|
-
return u;
|
|
115
|
-
};
|
|
116
|
-
throw Error(`Unknown style: ${String(i)}`);
|
|
117
|
-
} });
|
|
118
|
-
}
|
|
119
|
-
function Fe(r = {}) {
|
|
120
|
-
return f(r);
|
|
121
|
-
}
|
|
122
|
-
var o = Fe();
|
|
123
|
-
|
|
124
|
-
// ../kit/src/theme.ts
|
|
125
|
-
import { existsSync as existsSync2, readFileSync, statSync } from "fs";
|
|
126
|
-
import { homedir as homedir2 } from "os";
|
|
127
|
-
import { join as join3, resolve as resolve2 } from "path";
|
|
128
|
-
import process5 from "process";
|
|
129
|
-
|
|
130
|
-
// ../kit/src/config.ts
|
|
131
|
-
import { existsSync } from "fs";
|
|
132
|
-
import { dirname, join, resolve } from "path";
|
|
133
|
-
import process3 from "process";
|
|
134
|
-
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
135
|
-
const wanted = typeof names === "string" ? [names] : names;
|
|
136
|
-
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
137
|
-
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
138
|
-
if (found !== undefined)
|
|
139
|
-
return found;
|
|
140
|
-
if (stop(dir) || dirname(dir) === dir)
|
|
141
|
-
return;
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// ../kit/src/user-config.ts
|
|
146
|
-
import { homedir } from "os";
|
|
147
|
-
import { join as join2 } from "path";
|
|
148
|
-
import process4 from "process";
|
|
149
|
-
function configBase(where = {}) {
|
|
150
|
-
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
151
|
-
return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
|
|
152
|
-
}
|
|
153
|
-
function userConfigPath(bin, where = {}) {
|
|
154
|
-
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
// ../kit/src/theme.ts
|
|
158
|
-
var ENDS = new Map;
|
|
159
|
-
var DEFAULT = {
|
|
160
|
-
colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
|
|
161
|
-
glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
|
|
162
|
-
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
163
|
-
bins: {},
|
|
164
|
-
gradient: ["#c084fc", "#67e8f9"]
|
|
165
|
-
};
|
|
166
|
-
var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
|
|
167
|
-
var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
|
|
168
|
-
var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
169
|
-
var PRESETS = {
|
|
170
|
-
default: {},
|
|
171
|
-
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
172
|
-
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
173
|
-
ascii: { glyphs: ASCII }
|
|
174
|
-
};
|
|
175
|
-
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"]);
|
|
176
|
-
var HEX = /^#[0-9a-f]{6}$/i;
|
|
177
|
-
var CONTROL = /\p{Cc}/u;
|
|
178
|
-
var MAX_FILE_BYTES = 64 * 1024;
|
|
179
|
-
var SPACES = /\s+/;
|
|
180
|
-
function isColorSpec(spec) {
|
|
181
|
-
if (typeof spec === "number")
|
|
182
|
-
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
183
|
-
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
184
|
-
}
|
|
185
|
-
var CUBE = [0, 95, 135, 175, 215, 255];
|
|
186
|
-
function cubeLevel(channel) {
|
|
187
|
-
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
188
|
-
}
|
|
189
|
-
function nearest256(hex) {
|
|
190
|
-
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
191
|
-
const levels = rgb.map(cubeLevel);
|
|
192
|
-
const cube = levels.map((level) => CUBE[level]);
|
|
193
|
-
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
194
|
-
const greyValue = 8 + grey * 10;
|
|
195
|
-
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
196
|
-
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
197
|
-
}
|
|
198
|
-
function hasTrueColor(env) {
|
|
199
|
-
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
200
|
-
}
|
|
201
|
-
function tinted(colors, spec, env = process5.env) {
|
|
202
|
-
if (typeof spec === "number")
|
|
203
|
-
return colors.ansi256(spec);
|
|
204
|
-
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
205
|
-
if (HEX.test(token))
|
|
206
|
-
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
207
|
-
return chain[token] ?? chain;
|
|
208
|
-
}, colors);
|
|
209
|
-
}
|
|
210
|
-
function isRecord(value) {
|
|
211
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
212
|
-
}
|
|
213
|
-
function readThemeFile(path, warn) {
|
|
214
|
-
try {
|
|
215
|
-
const stat = statSync(path, { throwIfNoEntry: false });
|
|
216
|
-
if (stat === undefined)
|
|
217
|
-
return;
|
|
218
|
-
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
219
|
-
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
220
|
-
return;
|
|
221
|
-
}
|
|
222
|
-
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
223
|
-
if (isRecord(parsed))
|
|
224
|
-
return parsed;
|
|
225
|
-
warn(`${path} is not a JSON object, theme ignored`);
|
|
226
|
-
} catch (error) {
|
|
227
|
-
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
228
|
-
}
|
|
229
|
-
return;
|
|
230
|
-
}
|
|
231
|
-
function applyPreset(theme, name, warn, where) {
|
|
232
|
-
if (name === undefined)
|
|
233
|
-
return;
|
|
234
|
-
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
235
|
-
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
236
|
-
return;
|
|
237
|
-
}
|
|
238
|
-
const preset = PRESETS[name];
|
|
239
|
-
Object.assign(theme.colors, preset.colors);
|
|
240
|
-
Object.assign(theme.glyphs, preset.glyphs);
|
|
241
|
-
if (preset.accents !== undefined)
|
|
242
|
-
theme.accents = [...preset.accents];
|
|
243
|
-
if (Object.hasOwn(preset, "gradient"))
|
|
244
|
-
theme.gradient = preset.gradient;
|
|
245
|
-
return name;
|
|
246
|
-
}
|
|
247
|
-
function applyFile(theme, file, where, warn) {
|
|
248
|
-
if (isRecord(file.colors)) {
|
|
249
|
-
for (const [key, value] of Object.entries(file.colors)) {
|
|
250
|
-
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
251
|
-
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
252
|
-
else if (!isColorSpec(value))
|
|
253
|
-
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
254
|
-
else
|
|
255
|
-
theme.colors[key] = value;
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
if (isRecord(file.glyphs)) {
|
|
259
|
-
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
260
|
-
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
261
|
-
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
262
|
-
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
263
|
-
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
264
|
-
else
|
|
265
|
-
theme.glyphs[key] = value;
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
269
|
-
theme.accents = [...file.accents];
|
|
270
|
-
else if (file.accents !== undefined)
|
|
271
|
-
warn(`${where}: accents must be a non-empty list of colours`);
|
|
272
|
-
if (file.gradient === null)
|
|
273
|
-
theme.gradient = undefined;
|
|
274
|
-
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
275
|
-
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
276
|
-
else if (file.gradient !== undefined)
|
|
277
|
-
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
278
|
-
if (isRecord(file.bins)) {
|
|
279
|
-
for (const [bin, value] of Object.entries(file.bins)) {
|
|
280
|
-
if (isColorSpec(value))
|
|
281
|
-
theme.bins[bin] = value;
|
|
282
|
-
else
|
|
283
|
-
warn(`${where}: bin ${bin} has no valid colour`);
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
function endsWalk(home) {
|
|
288
|
-
return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
|
|
289
|
-
}
|
|
290
|
-
var warned = new Set;
|
|
291
|
-
function warnOnce(message) {
|
|
292
|
-
if (warned.has(message))
|
|
293
|
-
return;
|
|
294
|
-
warned.add(message);
|
|
295
|
-
console.error(`warning: theme ${message}`);
|
|
296
|
-
}
|
|
297
|
-
function isPath(chosen) {
|
|
298
|
-
return chosen.includes("/") || chosen.endsWith(".json");
|
|
299
|
-
}
|
|
300
|
-
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
301
|
-
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
302
|
-
const sources = [];
|
|
303
|
-
const chosen = env.KIT_THEME ?? "";
|
|
304
|
-
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
305
|
-
if (isPath(chosen))
|
|
306
|
-
wanted.push(resolve2(from, chosen));
|
|
307
|
-
const files = [];
|
|
308
|
-
for (const path of wanted) {
|
|
309
|
-
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
310
|
-
if (path !== undefined && file !== undefined)
|
|
311
|
-
files.push({ path, file });
|
|
312
|
-
}
|
|
313
|
-
let preset = "default";
|
|
314
|
-
if (chosen !== "" && !isPath(chosen)) {
|
|
315
|
-
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
316
|
-
} else {
|
|
317
|
-
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
318
|
-
if (named !== undefined)
|
|
319
|
-
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
320
|
-
}
|
|
321
|
-
for (const { path, file } of files) {
|
|
322
|
-
applyFile(theme, file, path, warn);
|
|
323
|
-
sources.push(path);
|
|
324
|
-
}
|
|
325
|
-
return { theme, sources, preset };
|
|
326
|
-
}
|
|
327
|
-
var current;
|
|
328
|
-
var currentKey = "";
|
|
329
|
-
function activeTheme() {
|
|
330
|
-
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
331
|
-
if (current === undefined || key !== currentKey) {
|
|
332
|
-
current = loadTheme();
|
|
333
|
-
currentKey = key;
|
|
334
|
-
}
|
|
335
|
-
return current;
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
// ../kit/src/style.ts
|
|
339
|
-
var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
|
|
340
|
-
function takesControlCodes(stream, env = process6.env) {
|
|
341
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
342
|
-
}
|
|
343
|
-
function paint(stream, env = process6.env) {
|
|
344
|
-
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
345
|
-
}
|
|
346
|
-
function marked(mark, text, stream, detail, env = process6.env) {
|
|
347
|
-
const colors = paint(stream, env);
|
|
348
|
-
let head = MARK_WORDS[mark];
|
|
349
|
-
if (takesControlCodes(stream, env)) {
|
|
350
|
-
const { theme } = activeTheme();
|
|
351
|
-
head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
|
|
352
|
-
}
|
|
353
|
-
return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
|
|
354
|
-
}
|
|
355
|
-
function problem(text, detail) {
|
|
356
|
-
console.error(marked("problem", text, process6.stderr, detail));
|
|
357
|
-
}
|
|
358
|
-
var STATUS_WORDS = {
|
|
359
|
-
passed: ["passed", "success", "succeeded", "ok"],
|
|
360
|
-
failed: ["failed", "failure", "error", "errored"],
|
|
361
|
-
running: ["running", "in_progress", "started", "holding"],
|
|
362
|
-
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
363
|
-
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
364
|
-
};
|
|
365
|
-
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
366
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-knqbxp56.js
|
|
367
|
-
function tt(i, { units: r = "iec", dp: t = 1, locale: n } = {}) {
|
|
368
|
-
let e = r === "si" ? 1000 : 1024;
|
|
369
|
-
if (Math.abs(i) < e)
|
|
370
|
-
return `${i} B`;
|
|
371
|
-
let s = r === "iec" ? ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] : ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], o = -1, a = 10 ** t;
|
|
372
|
-
do
|
|
373
|
-
i /= e, ++o;
|
|
374
|
-
while (Math.round(Math.abs(i) * a) / a >= e && o < s.length - 1);
|
|
375
|
-
return `${n ? y(n, { minimumFractionDigits: t, maximumFractionDigits: t }).format(i) : i.toFixed(t)} ${s[o]}`;
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
// ../kit/src/format.ts
|
|
379
|
-
var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
380
|
-
function formatSeconds(total) {
|
|
381
|
-
let rest = Math.max(0, Math.round(total));
|
|
382
|
-
const amounts = UNITS.map(([unit, size]) => {
|
|
383
|
-
const amount = Math.floor(rest / size);
|
|
384
|
-
rest -= amount * size;
|
|
385
|
-
return `${amount}${unit}`;
|
|
386
|
-
});
|
|
387
|
-
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
388
|
-
if (first === -1)
|
|
389
|
-
return "0s";
|
|
390
|
-
const next = amounts[first + 1];
|
|
391
|
-
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
392
|
-
}
|
|
393
|
-
function formatDuration(ms) {
|
|
394
|
-
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
395
|
-
}
|
|
396
|
-
function upTo(text, separator) {
|
|
397
|
-
const end = text.indexOf(separator);
|
|
398
|
-
return end === -1 ? text : text.slice(0, end);
|
|
399
|
-
}
|
|
400
|
-
function truncate(text, width) {
|
|
401
|
-
return ko(text, width, { suffix: "\u2026", includeSuffix: true });
|
|
402
|
-
}
|
|
403
|
-
var LINE_BREAKS = /\s*\n\s*/g;
|
|
404
|
-
var ESCAPE = String.fromCharCode(27);
|
|
405
|
-
function textWidth(text) {
|
|
406
|
-
return Bun.stringWidth(text);
|
|
407
|
-
}
|
|
408
|
-
function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
|
|
409
|
-
const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
|
|
410
|
-
if (outputMode(stream, env) === "agent")
|
|
411
|
-
return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
|
|
412
|
-
`);
|
|
413
|
-
const widths = [];
|
|
414
|
-
for (const row of cells) {
|
|
415
|
-
for (const [index, cell] of row.entries())
|
|
416
|
-
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
417
|
-
}
|
|
418
|
-
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
419
|
-
const colors = paint(stream);
|
|
420
|
-
const lines = shown.map((row) => row.map((cell, index) => {
|
|
421
|
-
const width = widths[index] ?? 0;
|
|
422
|
-
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
423
|
-
if (align[index] === "right")
|
|
424
|
-
return `${gap}${cell}`;
|
|
425
|
-
return index === row.length - 1 ? cell : `${cell}${gap}`;
|
|
426
|
-
}).join(" ").trimEnd());
|
|
427
|
-
const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
|
|
428
|
-
return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
|
|
429
|
-
`);
|
|
430
|
-
}
|
|
431
|
-
function narrow(rows, widths, limit) {
|
|
432
|
-
const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
|
|
433
|
-
const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
|
|
434
|
-
const floor = 8;
|
|
435
|
-
while (used() > limit) {
|
|
436
|
-
let widest = -1;
|
|
437
|
-
for (const [index, width] of widths.entries()) {
|
|
438
|
-
if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
|
|
439
|
-
widest = index;
|
|
440
|
-
}
|
|
441
|
-
if (widest === -1)
|
|
442
|
-
break;
|
|
443
|
-
widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
|
|
444
|
-
}
|
|
445
|
-
return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
|
|
446
|
-
}
|
|
447
|
-
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
448
|
-
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
449
|
-
}
|
|
450
|
-
function printJson(value) {
|
|
451
|
-
console.log(jsonText(value));
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
// ../kit/src/help.ts
|
|
455
|
-
import process8 from "process";
|
|
456
|
-
var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
457
|
-
var USAGE_PREFIX = /^usage:\s*/i;
|
|
458
|
-
var FULL_STOP = /\.$/;
|
|
459
|
-
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
460
|
-
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
461
|
-
}
|
|
462
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
463
|
-
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
464
|
-
`);
|
|
465
|
-
}
|
|
466
|
-
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
467
|
-
if (exits.length === 0)
|
|
468
|
-
return [];
|
|
469
|
-
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
470
|
-
}
|
|
471
|
-
function wantsHelpJson(env = process8.env) {
|
|
472
|
-
return env.KIT_HELP === "json";
|
|
473
|
-
}
|
|
474
|
-
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
475
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
476
|
-
`);
|
|
477
|
-
const first = lines[0];
|
|
478
|
-
const colon = first.indexOf(": ");
|
|
479
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
480
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
481
|
-
return {
|
|
482
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
483
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
484
|
-
...replaces === undefined ? {} : { replaces },
|
|
485
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
486
|
-
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
487
|
-
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
488
|
-
};
|
|
489
|
-
}
|
|
490
|
-
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
491
|
-
if (examples.length === 0 || outputMode() === "agent")
|
|
492
|
-
return [];
|
|
493
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
494
|
-
}
|
|
495
|
-
var MAX_INLINE_CHOICES = 24;
|
|
496
|
-
function optionRows(options, colors = paint(process8.stdout)) {
|
|
497
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
498
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
499
|
-
const choices = option.choices?.join("|");
|
|
500
|
-
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
501
|
-
const named = inline ? `<${choices}>` : "<value>";
|
|
502
|
-
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
503
|
-
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
504
|
-
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
505
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
506
|
-
});
|
|
507
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
508
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
// ../kit/src/text.ts
|
|
512
|
-
function distance(a, b) {
|
|
513
|
-
const left = [...a];
|
|
514
|
-
const right = [...b];
|
|
515
|
-
let before = [];
|
|
516
|
-
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
517
|
-
for (const [i, x] of left.entries()) {
|
|
518
|
-
const current = [i + 1];
|
|
519
|
-
for (const [j, y] of right.entries()) {
|
|
520
|
-
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
521
|
-
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
522
|
-
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
523
|
-
current.push(cost);
|
|
524
|
-
}
|
|
525
|
-
before = previous;
|
|
526
|
-
previous = current;
|
|
527
|
-
}
|
|
528
|
-
return previous[right.length] ?? 0;
|
|
529
|
-
}
|
|
530
|
-
function closest(name, names) {
|
|
531
|
-
const started = names.find((known) => known.startsWith(name));
|
|
532
|
-
if (started !== undefined)
|
|
533
|
-
return started;
|
|
534
|
-
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
535
|
-
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
536
|
-
}
|
|
537
|
-
// ../kit/src/input.ts
|
|
538
|
-
var WHOLE = /^\d+$/;
|
|
539
|
-
function wholeNumber(value, name, fallback, min = 1) {
|
|
540
|
-
if (value === undefined)
|
|
541
|
-
return fallback;
|
|
542
|
-
const number = Number(value);
|
|
543
|
-
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
544
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
545
|
-
return number;
|
|
546
|
-
}
|
|
547
|
-
var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
|
|
548
|
-
var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
|
|
549
|
-
function duration(value, name, fallback, unit = "s") {
|
|
550
|
-
if (value === undefined)
|
|
551
|
-
return fallback;
|
|
552
|
-
const match = DURATION.exec(value.trim());
|
|
553
|
-
const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
|
|
554
|
-
if (ms < 1)
|
|
555
|
-
badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
|
|
556
|
-
return ms;
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
// ../kit/src/args.ts
|
|
560
|
-
var DASHES = /^-+/;
|
|
561
|
-
function jsonOption(holds) {
|
|
562
|
-
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
563
|
-
}
|
|
564
|
-
class Exit extends Error {
|
|
565
|
-
code;
|
|
566
|
-
hint;
|
|
567
|
-
constructor(message, code, hint) {
|
|
568
|
-
super(message);
|
|
569
|
-
this.code = code;
|
|
570
|
-
this.hint = hint;
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
function fail(message, code = 2, hint) {
|
|
574
|
-
throw new Exit(message, code, hint);
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
class UsageError extends Exit {
|
|
578
|
-
constructor(message, hint) {
|
|
579
|
-
super(message, 2, hint);
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
function badUsage(message) {
|
|
583
|
-
throw new UsageError(message);
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
class HelpShown extends Exit {
|
|
587
|
-
constructor() {
|
|
588
|
-
super("help shown", 0);
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
class Completing {
|
|
593
|
-
options;
|
|
594
|
-
positionals;
|
|
595
|
-
candidates;
|
|
596
|
-
constructor(options, positionals = [], candidates = {}) {
|
|
597
|
-
this.options = options;
|
|
598
|
-
this.positionals = positionals;
|
|
599
|
-
this.candidates = candidates;
|
|
600
|
-
}
|
|
601
|
-
}
|
|
602
|
-
var completion = { active: false };
|
|
603
|
-
var OUTPUT_OPTIONS = {
|
|
604
|
-
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
605
|
-
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
606
|
-
};
|
|
607
|
-
function applyOutput(color, plain, env = process9.env) {
|
|
608
|
-
const when = plain === true ? "never" : color ?? "auto";
|
|
609
|
-
if (when === "auto")
|
|
610
|
-
return;
|
|
611
|
-
if (when !== "always" && when !== "never")
|
|
612
|
-
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
613
|
-
if (when === "always") {
|
|
614
|
-
env.FORCE_COLOR = "1";
|
|
615
|
-
delete env.NO_COLOR;
|
|
616
|
-
} else {
|
|
617
|
-
env.NO_COLOR = "1";
|
|
618
|
-
delete env.FORCE_COLOR;
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
function parse(args, usage, options, settings = {}) {
|
|
622
|
-
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
623
|
-
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
624
|
-
const listing = listed(all, settings.allowNegative === true);
|
|
625
|
-
if (completion.active)
|
|
626
|
-
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
627
|
-
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
628
|
-
let parsed;
|
|
629
|
-
try {
|
|
630
|
-
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
631
|
-
} catch (error) {
|
|
632
|
-
const message = parseError(error);
|
|
633
|
-
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
634
|
-
}
|
|
635
|
-
const values = parsed.values;
|
|
636
|
-
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
637
|
-
if (values.help === true) {
|
|
638
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
639
|
-
throw new HelpShown;
|
|
640
|
-
}
|
|
641
|
-
checkChoices(parsed.values, all);
|
|
642
|
-
checkConflicts(parsed.values, all);
|
|
643
|
-
if (settings.positionals !== undefined)
|
|
644
|
-
checkPositionals(parsed.positionals, settings.positionals);
|
|
645
|
-
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
646
|
-
}
|
|
647
|
-
function splitRest(args, passes) {
|
|
648
|
-
const separator = passes ? args.indexOf("--") : -1;
|
|
649
|
-
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
650
|
-
}
|
|
651
|
-
function splitTrailing(args, options, count) {
|
|
652
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
653
|
-
let seen = 0;
|
|
654
|
-
if (count === 0)
|
|
655
|
-
return { own: args, rest: undefined };
|
|
656
|
-
for (let at = 0;at < args.length; at++) {
|
|
657
|
-
const word = args[at];
|
|
658
|
-
if (word === "--")
|
|
659
|
-
break;
|
|
660
|
-
if (word.startsWith("-")) {
|
|
661
|
-
if (takesValue(word))
|
|
662
|
-
at++;
|
|
663
|
-
continue;
|
|
664
|
-
}
|
|
665
|
-
seen++;
|
|
666
|
-
if (seen === count)
|
|
667
|
-
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
668
|
-
}
|
|
669
|
-
return { own: args, rest: undefined };
|
|
670
|
-
}
|
|
671
|
-
function listed(options, allowNegative) {
|
|
672
|
-
if (!allowNegative)
|
|
673
|
-
return options;
|
|
674
|
-
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
675
|
-
if (option.type !== "boolean" || option.negative === undefined)
|
|
676
|
-
return [[name, option]];
|
|
677
|
-
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
678
|
-
}));
|
|
679
|
-
}
|
|
680
|
-
function withAliases(args, options) {
|
|
681
|
-
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
682
|
-
if (named.size === 0)
|
|
683
|
-
return args;
|
|
684
|
-
const separator = args.indexOf("--");
|
|
685
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
686
|
-
return [...own.map((arg) => {
|
|
687
|
-
const at = arg.indexOf("=");
|
|
688
|
-
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
689
|
-
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
690
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
691
|
-
}
|
|
692
|
-
function withBare(args, options) {
|
|
693
|
-
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
694
|
-
if (bare.size === 0)
|
|
695
|
-
return args;
|
|
696
|
-
const separator = args.indexOf("--");
|
|
697
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
698
|
-
return [...own.flatMap((arg, index) => {
|
|
699
|
-
const optional = bare.get(arg);
|
|
700
|
-
const next = own[index + 1];
|
|
701
|
-
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
702
|
-
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
703
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
704
|
-
}
|
|
705
|
-
function checkConflicts(values, options) {
|
|
706
|
-
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
707
|
-
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
708
|
-
const other = given(name) ? conflicts.find(given) : undefined;
|
|
709
|
-
if (other !== undefined)
|
|
710
|
-
badUsage(`--${name} cannot be used with --${other}`);
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
function checkChoices(values, options) {
|
|
714
|
-
for (const [name, option] of Object.entries(options)) {
|
|
715
|
-
if (option.choices === undefined)
|
|
716
|
-
continue;
|
|
717
|
-
const given = values[name];
|
|
718
|
-
for (const value of Array.isArray(given) ? given : [given]) {
|
|
719
|
-
if (typeof value === "string")
|
|
720
|
-
oneOf(value, name, option.choices);
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
}
|
|
724
|
-
function oneOf(value, name, choices) {
|
|
725
|
-
if (!choices.includes(value))
|
|
726
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
727
|
-
return value;
|
|
728
|
-
}
|
|
729
|
-
function checkPositionals(given, names) {
|
|
730
|
-
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
731
|
-
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
732
|
-
if (given.length < required)
|
|
733
|
-
badUsage(`missing ${names[given.length]}`);
|
|
734
|
-
if (!variadic && given.length > names.length)
|
|
735
|
-
badUsage(`unexpected argument ${given[names.length]}`);
|
|
736
|
-
}
|
|
737
|
-
function joinDashValues(args, options) {
|
|
738
|
-
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
739
|
-
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
740
|
-
const joined = [];
|
|
741
|
-
for (let i = 0;i < args.length; i++) {
|
|
742
|
-
const arg = args[i] ?? "";
|
|
743
|
-
if (arg === "--")
|
|
744
|
-
return [...joined, ...args.slice(i)];
|
|
745
|
-
const name = longOf.get(arg);
|
|
746
|
-
const next = args[i + 1];
|
|
747
|
-
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
748
|
-
joined.push(`--${name}=${next}`);
|
|
749
|
-
i++;
|
|
750
|
-
} else {
|
|
751
|
-
joined.push(arg);
|
|
752
|
-
}
|
|
753
|
-
}
|
|
754
|
-
return joined;
|
|
755
|
-
}
|
|
756
|
-
function parseError(error) {
|
|
757
|
-
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
758
|
-
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
759
|
-
}
|
|
760
|
-
var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
761
|
-
function nearestOption(message, options, allowNegative) {
|
|
762
|
-
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
763
|
-
if (typed === undefined)
|
|
764
|
-
return;
|
|
765
|
-
const word = typed.replace(DASHES, "");
|
|
766
|
-
if (word.length < 2 && !typed.startsWith("--"))
|
|
767
|
-
return;
|
|
768
|
-
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
769
|
-
...option.short === undefined ? [] : [`-${option.short}`],
|
|
770
|
-
`--${name}`,
|
|
771
|
-
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
772
|
-
]);
|
|
773
|
-
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
774
|
-
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
775
|
-
}
|
|
776
|
-
// ../kit/src/argv.ts
|
|
777
|
-
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
778
|
-
import { resolve as resolve3 } from "path";
|
|
779
|
-
import process10 from "process";
|
|
780
|
-
function commandLine() {
|
|
781
|
-
try {
|
|
782
|
-
return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
783
|
-
} catch {
|
|
784
|
-
return;
|
|
785
|
-
}
|
|
786
|
-
}
|
|
787
|
-
function realPath(word) {
|
|
788
|
-
try {
|
|
789
|
-
return realpathSync(resolve3(word));
|
|
790
|
-
} catch {
|
|
791
|
-
return;
|
|
792
|
-
}
|
|
793
|
-
}
|
|
794
|
-
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
795
|
-
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
796
|
-
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
797
|
-
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
798
|
-
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
799
|
-
}
|
|
800
|
-
// ../kit/src/process.ts
|
|
801
|
-
import { constants } from "os";
|
|
802
|
-
import process11 from "process";
|
|
803
|
-
var KILL_GRACE_MS = 2000;
|
|
804
|
-
function exitCodeOf(code, signal) {
|
|
805
|
-
if (code !== null)
|
|
806
|
-
return code;
|
|
807
|
-
if (typeof signal === "number")
|
|
808
|
-
return 128 + signal;
|
|
809
|
-
return signal === null ? 129 : 128 + constants.signals[signal];
|
|
810
|
-
}
|
|
811
|
-
async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
812
|
-
const chunks = [];
|
|
813
|
-
const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
|
|
814
|
-
const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
|
|
815
|
-
const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
|
|
816
|
-
const timers = [];
|
|
817
|
-
const killGroup = (killing) => {
|
|
818
|
-
if (state.done)
|
|
819
|
-
return;
|
|
820
|
-
try {
|
|
821
|
-
if (grouped)
|
|
822
|
-
process11.kill(-proc.pid, killing);
|
|
823
|
-
else
|
|
824
|
-
proc.kill(killing);
|
|
825
|
-
} catch {}
|
|
826
|
-
};
|
|
827
|
-
const stop = () => {
|
|
828
|
-
killGroup("SIGTERM");
|
|
829
|
-
timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
|
|
830
|
-
};
|
|
831
|
-
const onAbort = () => stop();
|
|
832
|
-
if (timeoutMs !== undefined) {
|
|
833
|
-
timers.push(setTimeout(() => {
|
|
834
|
-
state.timedOut = true;
|
|
835
|
-
stop();
|
|
836
|
-
}, timeoutMs));
|
|
837
|
-
}
|
|
838
|
-
if (signal?.aborted === true)
|
|
839
|
-
onAbort();
|
|
840
|
-
else
|
|
841
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
842
|
-
onStart?.({ kill: (killing) => killGroup(killing) });
|
|
843
|
-
const drain = async (stream, name) => {
|
|
844
|
-
for await (const data of stream) {
|
|
845
|
-
if (state.failure !== undefined)
|
|
846
|
-
continue;
|
|
847
|
-
try {
|
|
848
|
-
onChunk?.({ stream: name, data });
|
|
849
|
-
} catch (error) {
|
|
850
|
-
state.failure = error;
|
|
851
|
-
stop();
|
|
852
|
-
continue;
|
|
853
|
-
}
|
|
854
|
-
if (state.kept + data.length > maxBytes) {
|
|
855
|
-
state.truncated = true;
|
|
856
|
-
continue;
|
|
857
|
-
}
|
|
858
|
-
state.kept += data.length;
|
|
859
|
-
chunks.push({ stream: name, data });
|
|
860
|
-
}
|
|
861
|
-
};
|
|
862
|
-
try {
|
|
863
|
-
await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
|
|
864
|
-
await proc.exited;
|
|
865
|
-
} finally {
|
|
866
|
-
state.done = true;
|
|
867
|
-
for (const timer of timers)
|
|
868
|
-
clearTimeout(timer);
|
|
869
|
-
signal?.removeEventListener("abort", onAbort);
|
|
870
|
-
}
|
|
871
|
-
if (state.failure !== undefined)
|
|
872
|
-
throw state.failure;
|
|
873
|
-
const joined = () => Buffer.concat(chunks.map(({ data }) => data));
|
|
874
|
-
let output;
|
|
875
|
-
let text;
|
|
876
|
-
return {
|
|
877
|
-
code: exitCodeOf(proc.exitCode, proc.signalCode),
|
|
878
|
-
chunks,
|
|
879
|
-
timedOut: state.timedOut,
|
|
880
|
-
truncated: state.truncated,
|
|
881
|
-
get output() {
|
|
882
|
-
return output ??= joined();
|
|
883
|
-
},
|
|
884
|
-
get text() {
|
|
885
|
-
return text ??= (output ??= joined()).toString();
|
|
886
|
-
}
|
|
887
|
-
};
|
|
888
|
-
}
|
|
889
|
-
|
|
890
|
-
// ../kit/src/progress.ts
|
|
891
|
-
var ESC = String.fromCharCode(27);
|
|
892
|
-
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
893
|
-
var RESET_STYLE = `${ESC}[0m`;
|
|
894
|
-
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
895
|
-
// ../kit/src/cli.ts
|
|
896
|
-
import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
|
|
897
|
-
import { dirname as dirname3, join as join5 } from "path";
|
|
898
|
-
import process14 from "process";
|
|
899
|
-
|
|
900
|
-
// ../kit/src/completions.ts
|
|
901
|
-
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
902
|
-
var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
|
|
903
|
-
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
904
|
-
set -l current (commandline -ct)
|
|
905
|
-
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
906
|
-
if test "$line" = __files__
|
|
907
|
-
__fish_complete_path $current
|
|
908
|
-
else
|
|
909
|
-
echo $line
|
|
910
|
-
end
|
|
911
|
-
end
|
|
912
|
-
end`;
|
|
913
|
-
var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
914
|
-
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
915
|
-
local -a lines
|
|
916
|
-
COMPREPLY=()
|
|
917
|
-
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
918
|
-
for line in "\${lines[@]}"; do
|
|
919
|
-
if [[ $line == __files__ ]]; then
|
|
920
|
-
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
921
|
-
else
|
|
922
|
-
words+="\${line%%$'\\t'*}"$'\\n'
|
|
923
|
-
fi
|
|
924
|
-
done
|
|
925
|
-
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
926
|
-
}`;
|
|
927
|
-
var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
928
|
-
local line
|
|
929
|
-
local -a described plain
|
|
930
|
-
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
931
|
-
if [[ $line == __files__ ]]; then
|
|
932
|
-
_files
|
|
933
|
-
elif [[ $line == *$'\\t'* ]]; then
|
|
934
|
-
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
935
|
-
else
|
|
936
|
-
plain+=("$line")
|
|
937
|
-
fi
|
|
938
|
-
done
|
|
939
|
-
(( \${#described} )) && _describe -V value described
|
|
940
|
-
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
941
|
-
return 0
|
|
942
|
-
}`;
|
|
943
|
-
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
944
|
-
if (shell === "fish")
|
|
945
|
-
return `${header}
|
|
946
|
-
${FISH_FUNCTION}
|
|
947
|
-
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
948
|
-
`).join("")}`;
|
|
949
|
-
if (shell === "bash")
|
|
950
|
-
return `${header}
|
|
951
|
-
${BASH_FUNCTION}
|
|
952
|
-
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
953
|
-
`;
|
|
954
|
-
return `${header}
|
|
955
|
-
${ZSH_FUNCTION}
|
|
956
|
-
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
957
|
-
`;
|
|
958
|
-
}
|
|
959
|
-
|
|
960
|
-
// ../kit/src/notify.ts
|
|
961
|
-
import process12 from "process";
|
|
962
|
-
var NOTIFY_AFTER_MS = 1e4;
|
|
963
|
-
var CANCELLED = 130;
|
|
964
|
-
function base64(text) {
|
|
965
|
-
return Buffer.from(text).toString("base64");
|
|
966
|
-
}
|
|
967
|
-
function notification(title, body, env = process12.env) {
|
|
968
|
-
const id = `kit${process12.pid}`;
|
|
969
|
-
const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
|
|
970
|
-
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
971
|
-
}
|
|
972
|
-
function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
|
|
973
|
-
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
974
|
-
return;
|
|
975
|
-
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
976
|
-
}
|
|
977
|
-
|
|
978
|
-
// ../kit/src/usage.ts
|
|
979
|
-
import { appendFileSync, mkdirSync } from "fs";
|
|
980
|
-
import { homedir as homedir3 } from "os";
|
|
981
|
-
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
982
|
-
import process13 from "process";
|
|
983
|
-
|
|
984
|
-
// ../kit/src/logs.ts
|
|
985
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
986
|
-
var CLI_FOLDER = "kaynooo-cli";
|
|
987
|
-
|
|
988
|
-
// ../kit/src/usage.ts
|
|
989
|
-
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
990
|
-
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
991
|
-
var LONGEST_NAME = 40;
|
|
992
|
-
var usageError;
|
|
993
|
-
function noteUsageError(message) {
|
|
994
|
-
usageError = message;
|
|
995
|
-
}
|
|
996
|
-
function stateHome(env = process13.env) {
|
|
997
|
-
const dir = env.XDG_STATE_HOME;
|
|
998
|
-
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
999
|
-
}
|
|
1000
|
-
function usagePath(env = process13.env) {
|
|
1001
|
-
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1002
|
-
}
|
|
1003
|
-
function usageRecorded(env = process13.env) {
|
|
1004
|
-
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1005
|
-
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1006
|
-
}
|
|
1007
|
-
function flagNames(argv) {
|
|
1008
|
-
const end = argv.indexOf("--");
|
|
1009
|
-
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
1010
|
-
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
1011
|
-
}
|
|
1012
|
-
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
1013
|
-
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
1014
|
-
usageError = undefined;
|
|
1015
|
-
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
1016
|
-
}
|
|
1017
|
-
function recordUsage(entry, env = process13.env) {
|
|
1018
|
-
if (!usageRecorded(env))
|
|
1019
|
-
return;
|
|
1020
|
-
try {
|
|
1021
|
-
const path = usagePath(env);
|
|
1022
|
-
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
1023
|
-
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1024
|
-
`, { mode: 384 });
|
|
1025
|
-
} catch {}
|
|
1026
|
-
}
|
|
1027
|
-
|
|
1028
|
-
// ../kit/src/cli.ts
|
|
1029
|
-
var LEVEL_OPTIONS = {
|
|
1030
|
-
...OUTPUT_OPTIONS,
|
|
1031
|
-
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1032
|
-
};
|
|
1033
|
-
var TOP_OPTIONS = {
|
|
1034
|
-
...LEVEL_OPTIONS,
|
|
1035
|
-
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1036
|
-
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1037
|
-
};
|
|
1038
|
-
async function commandRows(all, colors) {
|
|
1039
|
-
const commands = shown(all);
|
|
1040
|
-
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
1041
|
-
const groups = new Map([["Commands:", []]]);
|
|
1042
|
-
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
1043
|
-
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
1044
|
-
const heading = group === undefined ? "Commands:" : `${group}:`;
|
|
1045
|
-
const rows = groups.get(heading) ?? [];
|
|
1046
|
-
rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
|
|
1047
|
-
groups.set(heading, rows);
|
|
1048
|
-
}
|
|
1049
|
-
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
1050
|
-
}
|
|
1051
|
-
function shown(commands) {
|
|
1052
|
-
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
1053
|
-
}
|
|
1054
|
-
function takeOutputFlags(argv) {
|
|
1055
|
-
let index = 0;
|
|
1056
|
-
for (;index < argv.length; index++) {
|
|
1057
|
-
const word = argv[index];
|
|
1058
|
-
if (word === "--plain")
|
|
1059
|
-
applyOutput(undefined, true);
|
|
1060
|
-
else if (word.startsWith("--color="))
|
|
1061
|
-
applyOutput(word.slice("--color=".length), undefined);
|
|
1062
|
-
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
1063
|
-
applyOutput(argv[++index], undefined);
|
|
1064
|
-
else
|
|
1065
|
-
break;
|
|
1066
|
-
}
|
|
1067
|
-
return argv.slice(index);
|
|
1068
|
-
}
|
|
1069
|
-
async function resolveSummary(summary) {
|
|
1070
|
-
return typeof summary === "string" ? summary : summary();
|
|
1071
|
-
}
|
|
1072
|
-
function scopeOf(commands, extra, aliases) {
|
|
1073
|
-
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
1074
|
-
}
|
|
1075
|
-
async function expand(scope, words) {
|
|
1076
|
-
if (scope.lazy.length === 0)
|
|
1077
|
-
return scope;
|
|
1078
|
-
const commands = { ...scope.commands };
|
|
1079
|
-
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
1080
|
-
for (const [name, command] of Object.entries(added))
|
|
1081
|
-
commands[name] ??= command;
|
|
1082
|
-
}
|
|
1083
|
-
return { ...scope, commands, lazy: [] };
|
|
1084
|
-
}
|
|
1085
|
-
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
1086
|
-
const colors = paint(stream);
|
|
1087
|
-
const prefix = path.join(" ");
|
|
1088
|
-
const summary = await resolveSummary(lazySummary);
|
|
1089
|
-
if (wantsHelpJson())
|
|
1090
|
-
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
1091
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1092
|
-
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
1093
|
-
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
1094
|
-
return [
|
|
1095
|
-
header(colors, summary),
|
|
1096
|
-
"",
|
|
1097
|
-
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
1098
|
-
"",
|
|
1099
|
-
...await commandRows(commands, colors),
|
|
1100
|
-
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
1101
|
-
"",
|
|
1102
|
-
colors.bold("Options:"),
|
|
1103
|
-
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
1104
|
-
...exampleRows(examples ?? [], colors),
|
|
1105
|
-
"",
|
|
1106
|
-
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
1107
|
-
].join(`
|
|
1108
|
-
`);
|
|
1109
|
-
}
|
|
1110
|
-
function printError(prefix, message, hint, cause) {
|
|
1111
|
-
const colors = paint(process14.stderr);
|
|
1112
|
-
const styled = takesControlCodes(process14.stderr);
|
|
1113
|
-
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1114
|
-
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1115
|
-
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1116
|
-
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1117
|
-
}
|
|
1118
|
-
function printJsonError(message, hint, cause) {
|
|
1119
|
-
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1120
|
-
}
|
|
1121
|
-
function wantsJson(argv) {
|
|
1122
|
-
const end = argv.indexOf("--");
|
|
1123
|
-
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1124
|
-
}
|
|
1125
|
-
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1126
|
-
if (error instanceof HelpShown)
|
|
1127
|
-
return 0;
|
|
1128
|
-
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1129
|
-
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1130
|
-
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1131
|
-
if (error instanceof Exit && error.code === 2)
|
|
1132
|
-
noteUsageError(error.message);
|
|
1133
|
-
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1134
|
-
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
1135
|
-
return error instanceof Exit ? error.code : 1;
|
|
1136
|
-
}
|
|
1137
|
-
async function dispatch(level, typed, { version, redact }) {
|
|
1138
|
-
const prefix = level.path.join(" ");
|
|
1139
|
-
let argv;
|
|
1140
|
-
try {
|
|
1141
|
-
argv = takeOutputFlags(typed);
|
|
1142
|
-
} catch (error) {
|
|
1143
|
-
return reportThrown(prefix, error);
|
|
1144
|
-
}
|
|
1145
|
-
const [name, ...args] = argv;
|
|
1146
|
-
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
1147
|
-
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
1148
|
-
try {
|
|
1149
|
-
return await fallback.run([]);
|
|
1150
|
-
} catch (error) {
|
|
1151
|
-
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
1152
|
-
}
|
|
1153
|
-
}
|
|
1154
|
-
if (name === undefined && level.path.length > 1) {
|
|
1155
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
|
|
1156
|
-
return 2;
|
|
1157
|
-
}
|
|
1158
|
-
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1159
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
|
|
1160
|
-
return 0;
|
|
1161
|
-
}
|
|
1162
|
-
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
1163
|
-
console.log(version);
|
|
1164
|
-
return 0;
|
|
1165
|
-
}
|
|
1166
|
-
let command = level.commands[level.aliases?.[name] ?? name];
|
|
1167
|
-
let rest = args;
|
|
1168
|
-
let ran = name;
|
|
1169
|
-
if (command === undefined && level.lazy.length > 0) {
|
|
1170
|
-
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
1171
|
-
command = level.commands[level.aliases?.[name] ?? name];
|
|
1172
|
-
}
|
|
1173
|
-
if (command === undefined && level.defaultCommand !== undefined) {
|
|
1174
|
-
command = level.commands[level.defaultCommand];
|
|
1175
|
-
rest = argv;
|
|
1176
|
-
ran = level.defaultCommand;
|
|
1177
|
-
}
|
|
1178
|
-
if (command === undefined) {
|
|
1179
|
-
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
1180
|
-
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
1181
|
-
return 2;
|
|
1182
|
-
}
|
|
1183
|
-
if ("commands" in command) {
|
|
1184
|
-
const { summary } = command;
|
|
1185
|
-
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 });
|
|
1186
|
-
}
|
|
1187
|
-
try {
|
|
1188
|
-
return await command.run(rest);
|
|
1189
|
-
} catch (error) {
|
|
1190
|
-
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
1191
|
-
}
|
|
1192
|
-
}
|
|
1193
|
-
var COMPLETE = "__complete";
|
|
1194
|
-
var FILES = "__files__";
|
|
1195
|
-
async function completingOf(run) {
|
|
1196
|
-
completion.active = true;
|
|
1197
|
-
try {
|
|
1198
|
-
await run([]);
|
|
1199
|
-
} catch (error) {
|
|
1200
|
-
if (error instanceof Completing)
|
|
1201
|
-
return error;
|
|
1202
|
-
} finally {
|
|
1203
|
-
completion.active = false;
|
|
1204
|
-
}
|
|
1205
|
-
return new Completing({});
|
|
1206
|
-
}
|
|
1207
|
-
async function optionsOf(run) {
|
|
1208
|
-
return (await completingOf(run)).options;
|
|
1209
|
-
}
|
|
1210
|
-
function candidateLine(candidate) {
|
|
1211
|
-
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
1212
|
-
}
|
|
1213
|
-
function positionalBeingTyped(before, { options, positionals }) {
|
|
1214
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1215
|
-
const typed = [];
|
|
1216
|
-
let at = 0;
|
|
1217
|
-
while (at < before.length) {
|
|
1218
|
-
const word = before[at];
|
|
1219
|
-
if (word === "--") {
|
|
1220
|
-
typed.push(...before.slice(at + 1));
|
|
1221
|
-
break;
|
|
1222
|
-
}
|
|
1223
|
-
if (!word.startsWith("-"))
|
|
1224
|
-
typed.push(word);
|
|
1225
|
-
else if (takesValue(word))
|
|
1226
|
-
at++;
|
|
1227
|
-
at++;
|
|
1228
|
-
}
|
|
1229
|
-
const last = positionals.at(-1);
|
|
1230
|
-
if (typed.length < positionals.length)
|
|
1231
|
-
return { name: positionals[typed.length], typed };
|
|
1232
|
-
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1233
|
-
}
|
|
1234
|
-
async function leafCandidates(run, words) {
|
|
1235
|
-
const completing = await completingOf(run);
|
|
1236
|
-
if ((words.at(-1) ?? "").startsWith("-"))
|
|
1237
|
-
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1238
|
-
const flag = words.at(-2);
|
|
1239
|
-
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1240
|
-
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1241
|
-
if (option?.type === "string") {
|
|
1242
|
-
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1243
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1244
|
-
}
|
|
1245
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1246
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1247
|
-
}
|
|
1248
|
-
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1249
|
-
const [word = "", ...rest] = words;
|
|
1250
|
-
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1251
|
-
let { commands, aliases } = scope;
|
|
1252
|
-
let command = commands[aliases?.[word] ?? word];
|
|
1253
|
-
if (listing || command === undefined) {
|
|
1254
|
-
({ commands, aliases } = await expand(scope, [...before, ...words]));
|
|
1255
|
-
command = commands[aliases?.[word] ?? word];
|
|
1256
|
-
}
|
|
1257
|
-
if (listing) {
|
|
1258
|
-
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1259
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1260
|
-
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1261
|
-
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1262
|
-
return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
|
|
1263
|
-
}
|
|
1264
|
-
if (command === undefined) {
|
|
1265
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1266
|
-
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
1267
|
-
}
|
|
1268
|
-
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1269
|
-
}
|
|
1270
|
-
var COMPLETIONS = "--completions";
|
|
1271
|
-
function flagValue([flag = "", ...rest]) {
|
|
1272
|
-
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1273
|
-
}
|
|
1274
|
-
function printCompletionScript(name, args) {
|
|
1275
|
-
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1276
|
-
if (shell === undefined || args.length !== 1) {
|
|
1277
|
-
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1278
|
-
return 2;
|
|
1279
|
-
}
|
|
1280
|
-
console.log(completionScript(shell, [name]).trimEnd());
|
|
1281
|
-
return 0;
|
|
1282
|
-
}
|
|
1283
|
-
async function printCandidates(found) {
|
|
1284
|
-
for (const line of await found)
|
|
1285
|
-
console.log(line);
|
|
1286
|
-
return 0;
|
|
1287
|
-
}
|
|
1288
|
-
function packageVersion(entry = Bun.main) {
|
|
1289
|
-
let resolved = entry;
|
|
1290
|
-
try {
|
|
1291
|
-
resolved = realpathSync2(entry);
|
|
1292
|
-
} catch {}
|
|
1293
|
-
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1294
|
-
try {
|
|
1295
|
-
const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
|
|
1296
|
-
if (typeof version === "string")
|
|
1297
|
-
return version;
|
|
1298
|
-
} catch {}
|
|
1299
|
-
if (dirname3(dir) === dir)
|
|
1300
|
-
return "0.0.0";
|
|
1301
|
-
}
|
|
1302
|
-
}
|
|
1303
|
-
async function runCli(cli, argv = scriptArgs()) {
|
|
1304
|
-
const version = cli.version ?? packageVersion();
|
|
1305
|
-
if (argv[0] === COMPLETE)
|
|
1306
|
-
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1307
|
-
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1308
|
-
return printCompletionScript(cli.name, flagValue(argv));
|
|
1309
|
-
const started = performance.now();
|
|
1310
|
-
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 });
|
|
1311
|
-
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1312
|
-
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1313
|
-
if (cli.usage !== false) {
|
|
1314
|
-
try {
|
|
1315
|
-
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1316
|
-
} catch {}
|
|
1317
|
-
}
|
|
1318
|
-
return code;
|
|
1319
|
-
}
|
|
1320
|
-
function commandPath(scope, argv) {
|
|
1321
|
-
const path = [];
|
|
1322
|
-
let level = scope;
|
|
1323
|
-
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1324
|
-
const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
|
|
1325
|
-
const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
|
|
1326
|
-
if (command === undefined)
|
|
1327
|
-
break;
|
|
1328
|
-
path.push(word);
|
|
1329
|
-
if (!("commands" in command))
|
|
1330
|
-
break;
|
|
1331
|
-
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
1332
|
-
}
|
|
1333
|
-
return path.length === 0 ? undefined : path.join(" ");
|
|
1334
|
-
}
|
|
1335
|
-
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1336
|
-
if (argv[0] === COMPLETE)
|
|
1337
|
-
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1338
|
-
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1339
|
-
return printCompletionScript(name, flagValue(argv));
|
|
1340
|
-
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
1341
|
-
console.log(version ?? packageVersion());
|
|
1342
|
-
return 0;
|
|
1343
|
-
}
|
|
1344
|
-
let code;
|
|
1345
|
-
const started = performance.now();
|
|
1346
|
-
try {
|
|
1347
|
-
code = await run(argv);
|
|
1348
|
-
} catch (error) {
|
|
1349
|
-
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1350
|
-
}
|
|
1351
|
-
notifyEnd(name, code, performance.now() - started);
|
|
1352
|
-
if (usage !== false) {
|
|
1353
|
-
try {
|
|
1354
|
-
recordUsage(usageEntry(name, undefined, argv, code));
|
|
1355
|
-
} catch {}
|
|
1356
|
-
}
|
|
1357
|
-
return code;
|
|
1358
|
-
}
|
|
1359
|
-
// ../kit/src/folders.ts
|
|
1360
|
-
var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
1361
|
-
// ../kit/src/secrets.ts
|
|
1362
|
-
var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
|
|
1363
|
-
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1364
|
-
var WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
|
|
1365
|
-
function isSecretName(name) {
|
|
1366
|
-
return SECRET_PART.test(name) || name.split(WORD_BREAKS).some((word) => SECRET_WORDS.has(word.toLowerCase()));
|
|
1367
|
-
}
|
|
1368
|
-
// ../kit/src/sessions.ts
|
|
1369
|
-
var {Glob } = globalThis.Bun;
|
|
1370
|
-
var SESSION_FILES = new Glob("*.json");
|
|
1371
|
-
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1372
|
-
// ../kit/src/size.ts
|
|
1373
|
-
var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
|
|
1374
|
-
var POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
|
|
1375
|
-
function parseSize(text, bareUnit = 1) {
|
|
1376
|
-
const match = SIZE.exec(text.trim());
|
|
1377
|
-
if (match === null)
|
|
1378
|
-
return;
|
|
1379
|
-
const suffix = match[2].toLowerCase();
|
|
1380
|
-
return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
|
|
1381
|
-
}
|
|
1382
|
-
// ../kit/src/watch.ts
|
|
1383
|
-
import process15 from "process";
|
|
1384
|
-
import { format } from "util";
|
|
1385
|
-
var CLEAR_SCREEN = "\x1B[H\x1B[2J";
|
|
1386
|
-
var DEFAULT_SECONDS = 2;
|
|
1387
|
-
var ATTACHED_SHORT = /^-w./;
|
|
1388
|
-
var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
|
|
1389
|
-
function watchOption(what) {
|
|
1390
|
-
return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
|
|
1391
|
-
}
|
|
1392
|
-
function withoutWatch(args) {
|
|
1393
|
-
const rest = [];
|
|
1394
|
-
for (let at = 0;at < args.length; at++) {
|
|
1395
|
-
const arg = args[at];
|
|
1396
|
-
if (arg === "--watch" || arg === "-w") {
|
|
1397
|
-
if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
|
|
1398
|
-
at++;
|
|
1399
|
-
} else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
|
|
1400
|
-
rest.push(arg);
|
|
1401
|
-
}
|
|
1402
|
-
}
|
|
1403
|
-
return rest;
|
|
1404
|
-
}
|
|
1405
|
-
async function watching(value, step, stream = process15.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
|
|
1406
|
-
const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
|
|
1407
|
-
if (!takesControlCodes(stream))
|
|
1408
|
-
badUsage("--watch redraws the screen, so it needs a terminal");
|
|
1409
|
-
let code = 0;
|
|
1410
|
-
for (let round = 0;round < rounds; round++) {
|
|
1411
|
-
const held = [];
|
|
1412
|
-
const { log, info } = console;
|
|
1413
|
-
const write = process15.stdout.write.bind(process15.stdout);
|
|
1414
|
-
const hold = (...parts) => void held.push(`${format(...parts)}
|
|
1415
|
-
`);
|
|
1416
|
-
console.log = hold;
|
|
1417
|
-
console.info = hold;
|
|
1418
|
-
process15.stdout.write = (text) => {
|
|
1419
|
-
held.push(typeof text === "string" ? text : Buffer.from(text).toString());
|
|
1420
|
-
return true;
|
|
1421
|
-
};
|
|
1422
|
-
try {
|
|
1423
|
-
code = await step();
|
|
1424
|
-
} finally {
|
|
1425
|
-
console.log = log;
|
|
1426
|
-
console.info = info;
|
|
1427
|
-
process15.stdout.write = write;
|
|
1428
|
-
}
|
|
1429
|
-
stream.write(`${CLEAR_SCREEN}${held.join("")}`);
|
|
1430
|
-
await sleep(interval);
|
|
1431
|
-
}
|
|
1432
|
-
return code;
|
|
1433
|
-
}
|
|
1434
|
-
// src/pid.ts
|
|
1435
|
-
import process17 from "process";
|
|
1436
|
-
|
|
1437
|
-
// src/mask.ts
|
|
1438
|
-
import { basename } from "path";
|
|
1439
|
-
var MASK = "***";
|
|
1440
|
-
var URL_PASSWORD = /(?<![a-z0-9+.-])([a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:)[^\s'"@]{1,1024}@/gi;
|
|
1441
|
-
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;
|
|
1442
|
-
var OPAQUE = /(?<![\w-])(?=[\w-]{32,}(?![\w-]))(?=[\w-]*[A-Z])(?=[\w-]*\d)[\w-]+/gi;
|
|
1443
|
-
var PEM = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*/;
|
|
1444
|
-
function maskText(value) {
|
|
1445
|
-
return value.replace(PEM, MASK).replace(URL_PASSWORD, `$1${MASK}@`).replace(TOKEN, MASK).replace(OPAQUE, MASK);
|
|
1446
|
-
}
|
|
1447
|
-
function maskValue(name, value) {
|
|
1448
|
-
if (value === "")
|
|
1449
|
-
return value;
|
|
1450
|
-
return isSecretName(name) ? MASK : maskText(value);
|
|
1451
|
-
}
|
|
1452
|
-
function maskEnviron(entries) {
|
|
1453
|
-
return entries.map(([name, value]) => [name, maskValue(name, value)]);
|
|
1454
|
-
}
|
|
1455
|
-
var FLAG = /^-{1,2}([\w.-]+)(=|$)/;
|
|
1456
|
-
var ASSIGNMENT_NAME = /^[\w.-]+$/;
|
|
1457
|
-
var PASSWORD_SPLIT = new Set(["sshpass"]);
|
|
1458
|
-
var PASSWORD_JOINED = new Set(["mysql", "mysqldump", "mysqladmin", "mariadb", "mariadb-dump"]);
|
|
1459
|
-
function maskArgs(args) {
|
|
1460
|
-
const command = basename(args[0] ?? "");
|
|
1461
|
-
let hidden = false;
|
|
1462
|
-
return args.map((arg, index) => {
|
|
1463
|
-
if (hidden) {
|
|
1464
|
-
hidden = false;
|
|
1465
|
-
return arg.startsWith("-") ? maskText(arg) : MASK;
|
|
1466
|
-
}
|
|
1467
|
-
if (index > 0 && arg === "-p" && PASSWORD_SPLIT.has(command)) {
|
|
1468
|
-
hidden = true;
|
|
1469
|
-
return arg;
|
|
1470
|
-
}
|
|
1471
|
-
if (index > 0 && arg.length > 2 && arg.startsWith("-p") && PASSWORD_JOINED.has(command))
|
|
1472
|
-
return `-p${MASK}`;
|
|
1473
|
-
const flag = FLAG.exec(arg);
|
|
1474
|
-
if (flag !== null) {
|
|
1475
|
-
if (flag[2] === "=")
|
|
1476
|
-
return isSecretName(flag[1]) ? `${arg.slice(0, flag[0].length)}${MASK}` : maskText(arg);
|
|
1477
|
-
hidden = isSecretName(flag[1]);
|
|
1478
|
-
return arg;
|
|
1479
|
-
}
|
|
1480
|
-
const equals = arg.indexOf("=");
|
|
1481
|
-
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);
|
|
1482
|
-
});
|
|
1483
|
-
}
|
|
1484
|
-
|
|
1485
|
-
// src/parse.ts
|
|
1486
|
-
var LISTENING = { tcp: "0A", udp: "07" };
|
|
1487
|
-
var WHITESPACE = /\s+/;
|
|
1488
|
-
var HEX_PAIR = /../g;
|
|
1489
|
-
var SOCKET_LINK = /^socket:\[(\d+)\]$/;
|
|
1490
|
-
var UNIT_SCOPE = /\.(?:service|scope)$/;
|
|
1491
|
-
var CONTAINER_ID = /(?:docker-|libpod-|\/docker\/)([0-9a-f]{64})/;
|
|
1492
|
-
var DOCKER_PORT = /:(\d+)(?:-(\d+))?->[\d-]+\/(tcp|udp)/;
|
|
1493
|
-
function word(hex) {
|
|
1494
|
-
const bytes = (hex.match(HEX_PAIR) ?? []).reverse().map((byte) => Number.parseInt(byte, 16));
|
|
1495
|
-
return [bytes[0] << 8 | bytes[1], bytes[2] << 8 | bytes[3]];
|
|
1496
|
-
}
|
|
1497
|
-
function parseAddress(hex) {
|
|
1498
|
-
if (hex.length === 8) {
|
|
1499
|
-
const [high, low] = word(hex);
|
|
1500
|
-
return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
|
|
1501
|
-
}
|
|
1502
|
-
const hextets = (hex.match(/.{8}/g) ?? []).flatMap(word);
|
|
1503
|
-
if (hextets.length !== 8)
|
|
1504
|
-
return hex;
|
|
1505
|
-
if (hextets.slice(0, 5).every((part) => part === 0) && hextets[5] === 65535)
|
|
1506
|
-
return `::ffff:${hextets[6] >> 8}.${hextets[6] & 255}.${hextets[7] >> 8}.${hextets[7] & 255}`;
|
|
1507
|
-
return compress(hextets);
|
|
1508
|
-
}
|
|
1509
|
-
function compress(hextets) {
|
|
1510
|
-
let best = { start: -1, length: 0 };
|
|
1511
|
-
let run = { start: 0, length: 0 };
|
|
1512
|
-
for (const [at, part] of hextets.entries()) {
|
|
1513
|
-
run = part === 0 ? { start: run.length === 0 ? at : run.start, length: run.length + 1 } : { start: 0, length: 0 };
|
|
1514
|
-
if (run.length > best.length)
|
|
1515
|
-
best = run;
|
|
1516
|
-
}
|
|
1517
|
-
const text = (parts) => parts.map((part) => part.toString(16)).join(":");
|
|
1518
|
-
if (best.length < 2)
|
|
1519
|
-
return text(hextets);
|
|
1520
|
-
return `${text(hextets.slice(0, best.start))}::${text(hextets.slice(best.start + best.length))}`;
|
|
1521
|
-
}
|
|
1522
|
-
function parseNetTable(text, protocol, family) {
|
|
1523
|
-
const sockets = [];
|
|
1524
|
-
for (const line of text.split(`
|
|
1525
|
-
`).slice(1)) {
|
|
1526
|
-
const columns = line.trim().split(WHITESPACE);
|
|
1527
|
-
const [address = "", port = ""] = (columns[1] ?? "").split(":");
|
|
1528
|
-
if (columns.length < 10 || columns[3] !== LISTENING[protocol])
|
|
1529
|
-
continue;
|
|
1530
|
-
const number = Number.parseInt(port, 16);
|
|
1531
|
-
if (number === 0 || Number.isNaN(number))
|
|
1532
|
-
continue;
|
|
1533
|
-
sockets.push({ protocol, family, address: parseAddress(address), port: number, uid: Number(columns[7]), inode: Number(columns[9]) });
|
|
1534
|
-
}
|
|
1535
|
-
return sockets;
|
|
1536
|
-
}
|
|
1537
|
-
function socketInode(link) {
|
|
1538
|
-
const match = SOCKET_LINK.exec(link);
|
|
1539
|
-
return match === null ? undefined : Number(match[1]);
|
|
1540
|
-
}
|
|
1541
|
-
function parseStat(text) {
|
|
1542
|
-
const open = text.indexOf("(");
|
|
1543
|
-
const close = text.lastIndexOf(")");
|
|
1544
|
-
if (open === -1 || close < open)
|
|
1545
|
-
return;
|
|
1546
|
-
const rest = text.slice(close + 2).trim().split(WHITESPACE);
|
|
1547
|
-
const field = (number) => Number(rest[number - 3]);
|
|
1548
|
-
if (rest.length < 20)
|
|
1549
|
-
return;
|
|
1550
|
-
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) };
|
|
1551
|
-
}
|
|
1552
|
-
function parseStatus(text) {
|
|
1553
|
-
const fields = new Map;
|
|
1554
|
-
for (const line of text.split(`
|
|
1555
|
-
`)) {
|
|
1556
|
-
const colon = line.indexOf(":");
|
|
1557
|
-
if (colon > 0)
|
|
1558
|
-
fields.set(line.slice(0, colon), line.slice(colon + 1).trim());
|
|
1559
|
-
}
|
|
1560
|
-
return fields;
|
|
1561
|
-
}
|
|
1562
|
-
function statusBytes(fields, key) {
|
|
1563
|
-
const value = Number.parseInt(fields.get(key) ?? "", 10);
|
|
1564
|
-
return Number.isNaN(value) ? undefined : value * 1024;
|
|
1565
|
-
}
|
|
1566
|
-
function statusUid(fields) {
|
|
1567
|
-
const value = Number.parseInt(fields.get("Uid") ?? "", 10);
|
|
1568
|
-
return Number.isNaN(value) ? undefined : value;
|
|
1569
|
-
}
|
|
1570
|
-
var LIMIT_LINE = /^(\S+(?: \S+)*)\s{2,}(\S+)\s+(\S+)(?:\s+(\S+))?\s*$/;
|
|
1571
|
-
function parseLimits(text) {
|
|
1572
|
-
const limits = [];
|
|
1573
|
-
for (const line of text.split(`
|
|
1574
|
-
`).slice(1)) {
|
|
1575
|
-
const match = LIMIT_LINE.exec(line);
|
|
1576
|
-
if (match !== null)
|
|
1577
|
-
limits.push({ name: match[1], soft: match[2], hard: match[3], units: match[4] ?? "" });
|
|
1578
|
-
}
|
|
1579
|
-
return limits;
|
|
1580
|
-
}
|
|
1581
|
-
function parseCmdline(text) {
|
|
1582
|
-
return text.split("\x00").filter((_, at, parts) => at < parts.length - 1 || parts[at] !== "");
|
|
1583
|
-
}
|
|
1584
|
-
function parseEnviron(text) {
|
|
1585
|
-
return parseCmdline(text).map((entry) => {
|
|
1586
|
-
const equals = entry.indexOf("=");
|
|
1587
|
-
return equals === -1 ? [entry, ""] : [entry.slice(0, equals), entry.slice(equals + 1)];
|
|
1588
|
-
});
|
|
1589
|
-
}
|
|
1590
|
-
function parseCgroup(text) {
|
|
1591
|
-
return text.split(`
|
|
1592
|
-
`).filter((line) => line !== "").map((line) => {
|
|
1593
|
-
const [hierarchy = "", controllers = "", ...path] = line.split(":");
|
|
1594
|
-
return { hierarchy, controllers, path: path.join(":") };
|
|
1595
|
-
});
|
|
1596
|
-
}
|
|
1597
|
-
function cgroupUnit(entries) {
|
|
1598
|
-
const path = (entries.find((entry) => entry.hierarchy === "0") ?? entries[0])?.path ?? "";
|
|
1599
|
-
return path.split("/").reverse().find((part) => UNIT_SCOPE.test(part));
|
|
1600
|
-
}
|
|
1601
|
-
function cgroupContainer(entries) {
|
|
1602
|
-
for (const { path } of entries) {
|
|
1603
|
-
const match = CONTAINER_ID.exec(path);
|
|
1604
|
-
if (match !== null)
|
|
1605
|
-
return match[1];
|
|
1606
|
-
}
|
|
1607
|
-
return;
|
|
1608
|
-
}
|
|
1609
|
-
function userNameOf(passwd, uid) {
|
|
1610
|
-
for (const line of passwd.split(`
|
|
1611
|
-
`)) {
|
|
1612
|
-
const [name, , id] = line.split(":");
|
|
1613
|
-
if (id === String(uid) && name !== undefined && name !== "")
|
|
1614
|
-
return name;
|
|
1615
|
-
}
|
|
1616
|
-
return;
|
|
1617
|
-
}
|
|
1618
|
-
function parseDockerPs(text) {
|
|
1619
|
-
const containers = [];
|
|
1620
|
-
for (const line of text.split(`
|
|
1621
|
-
`)) {
|
|
1622
|
-
const [name = "", ports = "", project = "", service = ""] = line.split("\t");
|
|
1623
|
-
if (name === "")
|
|
1624
|
-
continue;
|
|
1625
|
-
const published = [];
|
|
1626
|
-
for (const entry of ports.split(",")) {
|
|
1627
|
-
const match = DOCKER_PORT.exec(entry);
|
|
1628
|
-
if (match === null)
|
|
1629
|
-
continue;
|
|
1630
|
-
const first = Number(match[1]);
|
|
1631
|
-
for (let host = first;host <= Number(match[2] ?? first); host++)
|
|
1632
|
-
published.push({ host, protocol: match[3] });
|
|
1633
|
-
}
|
|
1634
|
-
containers.push({ name, project: project === "" ? undefined : project, service: service === "" ? undefined : service, published });
|
|
1635
|
-
}
|
|
1636
|
-
return containers;
|
|
1637
|
-
}
|
|
1638
|
-
|
|
1639
|
-
// src/read.ts
|
|
1640
|
-
import { readdir, readFile, readlink } from "fs/promises";
|
|
1641
|
-
var CLOCK_TICKS = 100;
|
|
1642
|
-
async function text2(path) {
|
|
1643
|
-
try {
|
|
1644
|
-
return await readFile(path, "utf8");
|
|
1645
|
-
} catch {
|
|
1646
|
-
return;
|
|
1647
|
-
}
|
|
1648
|
-
}
|
|
1649
|
-
async function link(path) {
|
|
1650
|
-
try {
|
|
1651
|
-
return await readlink(path);
|
|
1652
|
-
} catch {
|
|
1653
|
-
return;
|
|
1654
|
-
}
|
|
1655
|
-
}
|
|
1656
|
-
var DIGITS = /^\d+$/;
|
|
1657
|
-
var BOOT_TIME = /^btime\s+(\d+)/m;
|
|
1658
|
-
async function listPids(root = "/proc") {
|
|
1659
|
-
return (await readdir(root)).filter((name) => DIGITS.test(name)).map(Number);
|
|
1660
|
-
}
|
|
1661
|
-
async function bootMs(root = "/proc") {
|
|
1662
|
-
const match = BOOT_TIME.exec(await text2(`${root}/stat`) ?? "");
|
|
1663
|
-
return match === null ? Date.now() : Number(match[1]) * 1000;
|
|
1664
|
-
}
|
|
1665
|
-
async function readProc(pid, boot, { root = "/proc", detail = true } = {}) {
|
|
1666
|
-
const dir = `${root}/${pid}`;
|
|
1667
|
-
const [statText, statusText, cmdline] = await Promise.all([text2(`${dir}/stat`), text2(`${dir}/status`), text2(`${dir}/cmdline`)]);
|
|
1668
|
-
const stat = statText === undefined ? undefined : parseStat(statText);
|
|
1669
|
-
if (stat === undefined || statusText === undefined)
|
|
1670
|
-
return;
|
|
1671
|
-
const status = parseStatus(statusText);
|
|
1672
|
-
const info = {
|
|
1673
|
-
pid,
|
|
1674
|
-
ppid: stat.ppid,
|
|
1675
|
-
comm: stat.comm,
|
|
1676
|
-
args: parseCmdline(cmdline ?? ""),
|
|
1677
|
-
uid: statusUid(status) ?? -1,
|
|
1678
|
-
state: stat.state,
|
|
1679
|
-
session: stat.session,
|
|
1680
|
-
rss: statusBytes(status, "VmRSS") ?? 0,
|
|
1681
|
-
startMs: boot + stat.startTicks / CLOCK_TICKS * 1000
|
|
1682
|
-
};
|
|
1683
|
-
if (!detail)
|
|
1684
|
-
return info;
|
|
1685
|
-
const [cwd, exe, cgroup] = await Promise.all([link(`${dir}/cwd`), link(`${dir}/exe`), text2(`${dir}/cgroup`)]);
|
|
1686
|
-
const groups = parseCgroup(cgroup ?? "");
|
|
1687
|
-
return { ...info, cwd, exe, unit: cgroupUnit(groups), container: cgroupContainer(groups) };
|
|
1688
|
-
}
|
|
1689
|
-
async function snapshot(root = "/proc", detailed = () => true) {
|
|
1690
|
-
const boot = await bootMs(root);
|
|
1691
|
-
const found = [];
|
|
1692
|
-
for (const pid of await listPids(root)) {
|
|
1693
|
-
const light = await readProc(pid, boot, { root, detail: false });
|
|
1694
|
-
if (light === undefined)
|
|
1695
|
-
continue;
|
|
1696
|
-
found.push(detailed(light.uid) ? await readProc(pid, boot, { root }) ?? light : light);
|
|
1697
|
-
}
|
|
1698
|
-
return found;
|
|
1699
|
-
}
|
|
1700
|
-
function ancestry(pid, byPid) {
|
|
1701
|
-
const chain = [];
|
|
1702
|
-
let at = pid;
|
|
1703
|
-
while (at !== undefined && at > 0 && !chain.includes(at)) {
|
|
1704
|
-
chain.push(at);
|
|
1705
|
-
at = byPid.get(at)?.ppid;
|
|
1706
|
-
}
|
|
1707
|
-
return chain;
|
|
1708
|
-
}
|
|
1709
|
-
async function readSockets(root = "/proc") {
|
|
1710
|
-
const tables = [["tcp", "tcp", 4], ["tcp6", "tcp", 6], ["udp", "udp", 4], ["udp6", "udp", 6]];
|
|
1711
|
-
const sockets = [];
|
|
1712
|
-
for (const [file, protocol, family] of tables)
|
|
1713
|
-
sockets.push(...parseNetTable(await text2(`${root}/net/${file}`) ?? "", protocol, family));
|
|
1714
|
-
return sockets;
|
|
1715
|
-
}
|
|
1716
|
-
async function socketsOf(pid, root = "/proc") {
|
|
1717
|
-
const inodes = new Set;
|
|
1718
|
-
try {
|
|
1719
|
-
for (const fd of await readdir(`${root}/${pid}/fd`)) {
|
|
1720
|
-
const inode = socketInode(await link(`${root}/${pid}/fd/${fd}`) ?? "");
|
|
1721
|
-
if (inode !== undefined)
|
|
1722
|
-
inodes.add(inode);
|
|
1723
|
-
}
|
|
1724
|
-
} catch {}
|
|
1725
|
-
return inodes;
|
|
1726
|
-
}
|
|
1727
|
-
async function socketOwners(root = "/proc") {
|
|
1728
|
-
const holders = new Map;
|
|
1729
|
-
for (const pid of await listPids(root)) {
|
|
1730
|
-
for (const inode of await socketsOf(pid, root))
|
|
1731
|
-
holders.set(inode, [...holders.get(inode) ?? [], pid]);
|
|
1732
|
-
}
|
|
1733
|
-
const owners = new Map;
|
|
1734
|
-
const parents = new Map;
|
|
1735
|
-
for (const [inode, pids] of holders) {
|
|
1736
|
-
const [first = 0] = pids;
|
|
1737
|
-
if (pids.length > 1) {
|
|
1738
|
-
for (const pid of pids) {
|
|
1739
|
-
if (!parents.has(pid))
|
|
1740
|
-
parents.set(pid, parseStat(await text2(`${root}/${pid}/stat`) ?? "")?.ppid);
|
|
1741
|
-
}
|
|
1742
|
-
}
|
|
1743
|
-
owners.set(inode, pids.find((pid) => !pids.includes(parents.get(pid) ?? -1)) ?? first);
|
|
1744
|
-
}
|
|
1745
|
-
return owners;
|
|
1746
|
-
}
|
|
1747
|
-
async function fdCount(pid, root = "/proc") {
|
|
1748
|
-
try {
|
|
1749
|
-
return (await readdir(`${root}/${pid}/fd`)).length;
|
|
1750
|
-
} catch {
|
|
1751
|
-
return;
|
|
1752
|
-
}
|
|
1753
|
-
}
|
|
1754
|
-
var passwd;
|
|
1755
|
-
async function userName(uid) {
|
|
1756
|
-
passwd ??= await text2("/etc/passwd") ?? "";
|
|
1757
|
-
return userNameOf(passwd, uid);
|
|
1758
|
-
}
|
|
1759
|
-
|
|
1760
|
-
// src/pid.ts
|
|
1761
|
-
var usage2 = `pid <pid>
|
|
1762
|
-
|
|
1763
|
-
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.
|
|
1764
|
-
The environment is not shown unless --env is given, with every value that looks like a secret masked.`;
|
|
1765
|
-
var EXITS = [[0, "it showed the process"], [1, "no process has this pid"], [2, "a usage error"]];
|
|
1766
|
-
var DIGITS2 = /^\d+$/;
|
|
1767
|
-
var options = {
|
|
1768
|
-
env: { type: "boolean", description: "show the environment, secrets masked" },
|
|
1769
|
-
json: jsonOption("everything, with the environment under env when --env is given")
|
|
1770
|
-
};
|
|
1771
|
-
async function parentsOf(proc, boot) {
|
|
1772
|
-
const parents = [];
|
|
1773
|
-
const seen = new Set([proc.pid]);
|
|
1774
|
-
let at = proc.ppid;
|
|
1775
|
-
while (at > 0 && !seen.has(at)) {
|
|
1776
|
-
seen.add(at);
|
|
1777
|
-
const parent = await readProc(at, boot, { detail: false });
|
|
1778
|
-
if (parent === undefined)
|
|
1779
|
-
break;
|
|
1780
|
-
parents.push({ pid: parent.pid, comm: parent.comm, command: maskArgs(parent.args).join(" ") });
|
|
1781
|
-
at = parent.ppid;
|
|
1782
|
-
}
|
|
1783
|
-
return parents;
|
|
1784
|
-
}
|
|
1785
|
-
async function report2(pid, showEnv) {
|
|
1786
|
-
const boot = await bootMs();
|
|
1787
|
-
const proc = await readProc(pid, boot);
|
|
1788
|
-
if (proc === undefined)
|
|
1789
|
-
return;
|
|
1790
|
-
const unreadable = [];
|
|
1791
|
-
const status = parseStatus(await text2(`/proc/${pid}/status`) ?? "");
|
|
1792
|
-
const limitsText = await text2(`/proc/${pid}/limits`);
|
|
1793
|
-
const sockets = await socketsOf(pid);
|
|
1794
|
-
const listening = sockets.size === 0 ? [] : (await readSockets()).filter((socket) => sockets.has(socket.inode));
|
|
1795
|
-
const environText = showEnv ? await text2(`/proc/${pid}/environ`) : undefined;
|
|
1796
|
-
const cgroup = parseCgroup(await text2(`/proc/${pid}/cgroup`) ?? "")[0]?.path;
|
|
1797
|
-
const files = await fdCount(pid);
|
|
1798
|
-
const stat = parseStat(await text2(`/proc/${pid}/stat`) ?? "");
|
|
1799
|
-
const uid = proc.uid;
|
|
1800
|
-
if (proc.exe === undefined)
|
|
1801
|
-
unreadable.push("executable");
|
|
1802
|
-
if (proc.cwd === undefined)
|
|
1803
|
-
unreadable.push("working directory");
|
|
1804
|
-
if (files === undefined)
|
|
1805
|
-
unreadable.push("open files");
|
|
1806
|
-
if (limitsText === undefined)
|
|
1807
|
-
unreadable.push("limits");
|
|
1808
|
-
if (showEnv && environText === undefined)
|
|
1809
|
-
unreadable.push("environment");
|
|
1810
|
-
return {
|
|
1811
|
-
pid,
|
|
1812
|
-
comm: proc.comm,
|
|
1813
|
-
state: proc.state,
|
|
1814
|
-
exe: proc.exe,
|
|
1815
|
-
cwd: proc.cwd,
|
|
1816
|
-
command: maskArgs(proc.args),
|
|
1817
|
-
parents: await parentsOf(proc, boot),
|
|
1818
|
-
user: { uid, name: await userName(uid) },
|
|
1819
|
-
startedAt: new Date(proc.startMs).toISOString(),
|
|
1820
|
-
ageSeconds: Math.max(0, (Date.now() - proc.startMs) / 1000),
|
|
1821
|
-
threads: stat?.threads,
|
|
1822
|
-
memory: { rss: statusBytes(status, "VmRSS"), peak: statusBytes(status, "VmHWM"), virtual: statusBytes(status, "VmSize"), swap: statusBytes(status, "VmSwap") },
|
|
1823
|
-
openFiles: files,
|
|
1824
|
-
limits: parseLimits(limitsText ?? ""),
|
|
1825
|
-
listening: listening.map(({ protocol, address, port }) => ({ protocol, address, port })),
|
|
1826
|
-
cgroup: cgroup === "" ? undefined : cgroup,
|
|
1827
|
-
container: proc.container,
|
|
1828
|
-
env: environText === undefined ? undefined : maskEnviron(parseEnviron(environText)).map(([name, value]) => ({ name, value })),
|
|
1829
|
-
unreadable
|
|
1830
|
-
};
|
|
1831
|
-
}
|
|
1832
|
-
function limitLine(limits, name) {
|
|
1833
|
-
const limit = limits.find((candidate) => candidate.name === name);
|
|
1834
|
-
return limit === undefined ? "-" : `soft ${limit.soft}, hard ${limit.hard}`;
|
|
1835
|
-
}
|
|
1836
|
-
function render(info, showEnv) {
|
|
1837
|
-
const colors = paint(process17.stdout);
|
|
1838
|
-
const memory = info.memory;
|
|
1839
|
-
const size = (bytes) => bytes === undefined ? "-" : tt(bytes);
|
|
1840
|
-
const rows = [
|
|
1841
|
-
["Executable", info.exe ?? "-"],
|
|
1842
|
-
["Directory", info.cwd ?? "-"],
|
|
1843
|
-
["Command", info.command.join(" ") || `[${info.comm}]`],
|
|
1844
|
-
["Parents", info.parents.length === 0 ? "none (init)" : info.parents.map((parent) => `${parent.pid} ${parent.comm}`).join(" < ")],
|
|
1845
|
-
["User", `${info.user.name ?? "?"} (${info.user.uid})`],
|
|
1846
|
-
["State", info.state],
|
|
1847
|
-
["Started", `${info.startedAt} (${formatSeconds(info.ageSeconds)} ago)`],
|
|
1848
|
-
["Memory", `rss ${size(memory.rss)}, peak ${size(memory.peak)}, virtual ${size(memory.virtual)}, swap ${size(memory.swap)}`],
|
|
1849
|
-
["Open files", `${info.openFiles ?? "-"} (limit ${limitLine(info.limits, "Max open files")})`],
|
|
1850
|
-
["Processes", `${info.threads ?? "-"} threads (limit ${limitLine(info.limits, "Max processes")})`],
|
|
1851
|
-
["Listening", info.listening.length === 0 ? "nothing" : info.listening.map(({ protocol, address, port }) => `${protocol} ${address.includes(":") ? `[${address}]` : address}:${port}`).join(", ")]
|
|
1852
|
-
];
|
|
1853
|
-
if (info.cgroup !== undefined)
|
|
1854
|
-
rows.push(["Cgroup", info.cgroup]);
|
|
1855
|
-
const lines = [colors.bold(`pid ${info.pid} ${info.comm}`), ...rows.map(([label, value]) => `${colors.dim(label.padEnd(11))} ${value}`)];
|
|
1856
|
-
if (showEnv && info.env !== undefined)
|
|
1857
|
-
lines.push("", colors.bold("Environment"), ...info.env.map(({ name, value }) => `${name}=${value}`));
|
|
1858
|
-
else if (!showEnv)
|
|
1859
|
-
lines.push("", colors.dim("Environment hidden, pass --env to show it with secrets masked"));
|
|
1860
|
-
if (info.unreadable.length > 0)
|
|
1861
|
-
lines.push("", colors.yellow(`Could not read: ${info.unreadable.join(", ")} (a process of another user: rerun as that user)`));
|
|
1862
|
-
return lines.join(`
|
|
1863
|
-
`);
|
|
1864
|
-
}
|
|
1865
|
-
async function pid(args) {
|
|
1866
|
-
const { values, positionals } = parse(args, usage2, options, {
|
|
1867
|
-
exits: EXITS,
|
|
1868
|
-
positionals: ["<pid>"],
|
|
1869
|
-
replaces: "cat /proc/<pid>/{cmdline,environ,limits}, readlink /proc/<pid>/{exe,cwd}, the fish pid function",
|
|
1870
|
-
examples: [
|
|
1871
|
-
["pid 4242", "executable, directory, command, parents, memory, limits and ports"],
|
|
1872
|
-
["pid 4242 --env", "with the environment, secrets masked"],
|
|
1873
|
-
"pid 4242 --json"
|
|
1874
|
-
]
|
|
1875
|
-
});
|
|
1876
|
-
const [given] = positionals;
|
|
1877
|
-
if (!DIGITS2.test(given))
|
|
1878
|
-
fail(`the pid takes a number, not ${given}`, 2);
|
|
1879
|
-
const info = await report2(Number(given), values.env === true);
|
|
1880
|
-
if (info === undefined)
|
|
1881
|
-
return fail(`no process with pid ${given}`, 1);
|
|
1882
|
-
if (values.json === true)
|
|
1883
|
-
printJson(info);
|
|
1884
|
-
else
|
|
1885
|
-
console.log(render(info, values.env === true));
|
|
1886
|
-
return 0;
|
|
1887
|
-
}
|
|
1888
|
-
|
|
1889
|
-
// src/pid-cli.ts
|
|
1890
|
-
process18.exitCode = await runMain({ name: "pid", run: pid });
|