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