@kaynooo/cli-workspace 0.14.3 → 0.14.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +57 -3485
- package/package.json +14 -8
package/dist/cli.js
CHANGED
|
@@ -1,1726 +1,23 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
var __esm = (fn, res, err) => () => {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
if (err)
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
function
|
|
17
|
-
|
|
18
|
-
}
|
|
19
|
-
function
|
|
20
|
-
|
|
21
|
-
if (!n)
|
|
22
|
-
n = new Intl.NumberFormat(e, t), i.set(o, n);
|
|
23
|
-
return n;
|
|
24
|
-
}
|
|
25
|
-
var r, i, l;
|
|
26
|
-
var init_chunk_n6z2kk96 = __esm(() => {
|
|
27
|
-
r = new Map;
|
|
28
|
-
i = new Map;
|
|
29
|
-
l = new Map;
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
|
|
33
|
-
function Ao(t, e, r = "...") {
|
|
34
|
-
let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
|
|
35
|
-
if (t.length <= e)
|
|
36
|
-
return t;
|
|
37
|
-
let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
|
|
38
|
-
if (o && !Y.test(t[c.length] ?? " "))
|
|
39
|
-
c = c.replace(Nt, "") || c;
|
|
40
|
-
if (o)
|
|
41
|
-
c = c.trimEnd();
|
|
42
|
-
return s ? (c + n).slice(0, l) : c + n;
|
|
43
|
-
}
|
|
44
|
-
var N, Nt, Y, be, W;
|
|
45
|
-
var init_chunk_rkhsft4a = __esm(() => {
|
|
46
|
-
N = new Map;
|
|
47
|
-
Nt = /\s+\S*$/;
|
|
48
|
-
Y = /\s/;
|
|
49
|
-
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));
|
|
50
|
-
W = new Map;
|
|
51
|
-
});
|
|
52
|
-
|
|
53
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
|
|
54
|
-
var init_text = __esm(() => {
|
|
55
|
-
init_chunk_rkhsft4a();
|
|
56
|
-
});
|
|
57
|
-
|
|
58
|
-
// ../kit/src/mode.ts
|
|
59
|
-
import process2 from "process";
|
|
60
|
-
function isSet(value) {
|
|
61
|
-
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
62
|
-
}
|
|
63
|
-
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
64
|
-
const chosen = env.KIT_MODE;
|
|
65
|
-
if (chosen !== undefined && MODES.has(chosen))
|
|
66
|
-
return chosen;
|
|
67
|
-
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
68
|
-
return "agent";
|
|
69
|
-
if (stream.isTTY === true)
|
|
70
|
-
return "terminal";
|
|
71
|
-
return isSet(env.CI) ? "ci" : "pipe";
|
|
72
|
-
}
|
|
73
|
-
function isInteractive(streams = process2) {
|
|
74
|
-
return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
|
|
75
|
-
}
|
|
76
|
-
var MODES, AGENT_VARIABLES;
|
|
77
|
-
var init_mode = __esm(() => {
|
|
78
|
-
MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
79
|
-
AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
83
|
-
function b(r) {
|
|
84
|
-
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
85
|
-
if (!G2.test(e))
|
|
86
|
-
return [0, 0, 0];
|
|
87
|
-
if (e.length === 3 || e.length === 4)
|
|
88
|
-
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
89
|
-
if (e.length !== 6 && e.length !== 8)
|
|
90
|
-
throw Error(`Invalid hex color length: ${e.length}`);
|
|
91
|
-
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
92
|
-
}
|
|
93
|
-
function C(r, e = globalThis.process?.env ?? {}) {
|
|
94
|
-
if (e.FORCE_COLOR !== undefined)
|
|
95
|
-
return h.has(e.FORCE_COLOR);
|
|
96
|
-
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
97
|
-
return false;
|
|
98
|
-
return r?.isTTY === true;
|
|
99
|
-
}
|
|
100
|
-
function f(r, e = []) {
|
|
101
|
-
let l = "", n = "";
|
|
102
|
-
for (let t = 0, i = e.length;t < i; t++)
|
|
103
|
-
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
104
|
-
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
105
|
-
return new Proxy(c, { get(t, i) {
|
|
106
|
-
let a = B[i];
|
|
107
|
-
if (Array.isArray(a)) {
|
|
108
|
-
let s = g.get(i);
|
|
109
|
-
if (s === undefined)
|
|
110
|
-
s = f(r, [...e, a]), g.set(i, s);
|
|
111
|
-
return s;
|
|
112
|
-
}
|
|
113
|
-
if (typeof a === "function")
|
|
114
|
-
return (...s) => {
|
|
115
|
-
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
116
|
-
if (u === undefined) {
|
|
117
|
-
if (g.size >= 64)
|
|
118
|
-
g.clear();
|
|
119
|
-
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
120
|
-
}
|
|
121
|
-
return u;
|
|
122
|
-
};
|
|
123
|
-
throw Error(`Unknown style: ${String(i)}`);
|
|
124
|
-
} });
|
|
125
|
-
}
|
|
126
|
-
function Fe(r = {}) {
|
|
127
|
-
return f(r);
|
|
128
|
-
}
|
|
129
|
-
var G2, B, h, o;
|
|
130
|
-
var init_chunk_x450vn3m = __esm(() => {
|
|
131
|
-
G2 = /^[a-f0-9]+$/i;
|
|
132
|
-
B = { 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") => {
|
|
133
|
-
let [l, n, c] = b(r);
|
|
134
|
-
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
135
|
-
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
136
|
-
h = new Set(["", "1", "2", "3", "true"]);
|
|
137
|
-
o = Fe();
|
|
138
|
-
});
|
|
139
|
-
|
|
140
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
|
|
141
|
-
var init_colors = __esm(() => {
|
|
142
|
-
init_chunk_x450vn3m();
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
// ../kit/src/config.ts
|
|
146
|
-
import { existsSync } from "fs";
|
|
147
|
-
import { dirname, join, resolve } from "path";
|
|
148
|
-
import process3 from "process";
|
|
149
|
-
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
150
|
-
const wanted = typeof names === "string" ? [names] : names;
|
|
151
|
-
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
152
|
-
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
153
|
-
if (found !== undefined)
|
|
154
|
-
return found;
|
|
155
|
-
if (stop(dir) || dirname(dir) === dir)
|
|
156
|
-
return;
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
var init_config = __esm(() => {
|
|
160
|
-
init_args();
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
// ../kit/src/user-config.ts
|
|
164
|
-
import { existsSync as existsSync2, readFileSync } from "fs";
|
|
165
|
-
import { homedir } from "os";
|
|
166
|
-
import { isAbsolute, join as join2 } from "path";
|
|
167
|
-
import process4 from "process";
|
|
168
|
-
function xdgFolder(value, fallback) {
|
|
169
|
-
return value !== undefined && isAbsolute(value) ? value : fallback;
|
|
170
|
-
}
|
|
171
|
-
function configBase(where = {}) {
|
|
172
|
-
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
173
|
-
return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
|
|
174
|
-
}
|
|
175
|
-
function userConfigPath(bin, where = {}) {
|
|
176
|
-
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
177
|
-
}
|
|
178
|
-
function userConfigReadPath(bin, legacy = [], where = {}) {
|
|
179
|
-
const current = userConfigPath(bin, where);
|
|
180
|
-
if (existsSync2(current))
|
|
181
|
-
return current;
|
|
182
|
-
const base = configBase(where);
|
|
183
|
-
return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
|
|
184
|
-
}
|
|
185
|
-
function readUserConfig(bin, where = {}, legacy = []) {
|
|
186
|
-
const path = userConfigReadPath(bin, legacy, where);
|
|
187
|
-
if (!existsSync2(path))
|
|
188
|
-
return {};
|
|
189
|
-
try {
|
|
190
|
-
const parsed = Bun.JSONC.parse(readFileSync(path, "utf8"));
|
|
191
|
-
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
|
|
192
|
-
} catch {
|
|
193
|
-
return {};
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
function configuredNumber(bin, key, fallback, where = {}, legacy = []) {
|
|
197
|
-
const value = readUserConfig(bin, where, legacy)[key];
|
|
198
|
-
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
|
|
199
|
-
}
|
|
200
|
-
var init_user_config = () => {};
|
|
201
|
-
|
|
202
|
-
// ../kit/src/theme.ts
|
|
203
|
-
import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
|
|
204
|
-
import { homedir as homedir2 } from "os";
|
|
205
|
-
import { join as join3, resolve as resolve2 } from "path";
|
|
206
|
-
import process5 from "process";
|
|
207
|
-
function toLinear(channel) {
|
|
208
|
-
const value = channel / 255;
|
|
209
|
-
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
|
|
210
|
-
}
|
|
211
|
-
function toOklab(hex) {
|
|
212
|
-
const [r, g, b] = [1, 3, 5].map((at) => toLinear(Number.parseInt(hex.slice(at, at + 2), 16)));
|
|
213
|
-
const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
|
|
214
|
-
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
|
|
215
|
-
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
|
|
216
|
-
return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];
|
|
217
|
-
}
|
|
218
|
-
function fromOklab([lightness, a, b]) {
|
|
219
|
-
const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;
|
|
220
|
-
const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;
|
|
221
|
-
const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;
|
|
222
|
-
const channels = [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s];
|
|
223
|
-
return `#${channels.map((channel) => fromLinear(channel).toString(16).padStart(2, "0")).join("")}`;
|
|
224
|
-
}
|
|
225
|
-
function gradientAt(theme, ratio) {
|
|
226
|
-
if (theme.gradient === undefined)
|
|
227
|
-
return;
|
|
228
|
-
const key = theme.gradient.join();
|
|
229
|
-
let ends = ENDS.get(key);
|
|
230
|
-
if (ends === undefined) {
|
|
231
|
-
ends = [toOklab(theme.gradient[0]), toOklab(theme.gradient[1])];
|
|
232
|
-
ENDS.set(key, ends);
|
|
233
|
-
}
|
|
234
|
-
const at = Math.min(1, Math.max(0, ratio));
|
|
235
|
-
const [from, to] = ends;
|
|
236
|
-
return fromOklab(from.map((start, index) => start + (to[index] - start) * at));
|
|
237
|
-
}
|
|
238
|
-
function isColorSpec(spec) {
|
|
239
|
-
if (typeof spec === "number")
|
|
240
|
-
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
241
|
-
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
242
|
-
}
|
|
243
|
-
function cubeLevel(channel) {
|
|
244
|
-
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
245
|
-
}
|
|
246
|
-
function nearest256(hex) {
|
|
247
|
-
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
248
|
-
const levels = rgb.map(cubeLevel);
|
|
249
|
-
const cube = levels.map((level) => CUBE[level]);
|
|
250
|
-
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
251
|
-
const greyValue = 8 + grey * 10;
|
|
252
|
-
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
253
|
-
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
254
|
-
}
|
|
255
|
-
function hasTrueColor(env) {
|
|
256
|
-
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
257
|
-
}
|
|
258
|
-
function tinted(colors, spec, env = process5.env) {
|
|
259
|
-
if (typeof spec === "number")
|
|
260
|
-
return colors.ansi256(spec);
|
|
261
|
-
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
262
|
-
if (HEX.test(token))
|
|
263
|
-
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
264
|
-
return chain[token] ?? chain;
|
|
265
|
-
}, colors);
|
|
266
|
-
}
|
|
267
|
-
function shaded(theme, colors, glyph, cells, width, env = process5.env) {
|
|
268
|
-
return Array.from({ length: cells }, (_, index) => tinted(colors, gradientAt(theme, width <= 1 ? 0 : index / (width - 1)) ?? theme.colors.accent, env)(glyph)).join("");
|
|
269
|
-
}
|
|
270
|
-
function isRecord(value) {
|
|
271
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
272
|
-
}
|
|
273
|
-
function readThemeFile(path, warn) {
|
|
274
|
-
try {
|
|
275
|
-
const stat = statSync(path, { throwIfNoEntry: false });
|
|
276
|
-
if (stat === undefined)
|
|
277
|
-
return;
|
|
278
|
-
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
279
|
-
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
280
|
-
return;
|
|
281
|
-
}
|
|
282
|
-
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
283
|
-
if (isRecord(parsed))
|
|
284
|
-
return parsed;
|
|
285
|
-
warn(`${path} is not a JSON object, theme ignored`);
|
|
286
|
-
} catch (error) {
|
|
287
|
-
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
288
|
-
}
|
|
289
|
-
return;
|
|
290
|
-
}
|
|
291
|
-
function applyPreset(theme, name, warn, where) {
|
|
292
|
-
if (name === undefined)
|
|
293
|
-
return;
|
|
294
|
-
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
295
|
-
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
296
|
-
return;
|
|
297
|
-
}
|
|
298
|
-
const preset = PRESETS[name];
|
|
299
|
-
Object.assign(theme.colors, preset.colors);
|
|
300
|
-
Object.assign(theme.glyphs, preset.glyphs);
|
|
301
|
-
if (preset.accents !== undefined)
|
|
302
|
-
theme.accents = [...preset.accents];
|
|
303
|
-
if (Object.hasOwn(preset, "gradient"))
|
|
304
|
-
theme.gradient = preset.gradient;
|
|
305
|
-
return name;
|
|
306
|
-
}
|
|
307
|
-
function applyFile(theme, file, where, warn) {
|
|
308
|
-
if (isRecord(file.colors)) {
|
|
309
|
-
for (const [key, value] of Object.entries(file.colors)) {
|
|
310
|
-
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
311
|
-
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
312
|
-
else if (!isColorSpec(value))
|
|
313
|
-
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
314
|
-
else
|
|
315
|
-
theme.colors[key] = value;
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
if (isRecord(file.glyphs)) {
|
|
319
|
-
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
320
|
-
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
321
|
-
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
322
|
-
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
323
|
-
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
324
|
-
else
|
|
325
|
-
theme.glyphs[key] = value;
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
329
|
-
theme.accents = [...file.accents];
|
|
330
|
-
else if (file.accents !== undefined)
|
|
331
|
-
warn(`${where}: accents must be a non-empty list of colours`);
|
|
332
|
-
if (file.gradient === null)
|
|
333
|
-
theme.gradient = undefined;
|
|
334
|
-
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
335
|
-
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
336
|
-
else if (file.gradient !== undefined)
|
|
337
|
-
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
338
|
-
if (isRecord(file.bins)) {
|
|
339
|
-
for (const [bin, value] of Object.entries(file.bins)) {
|
|
340
|
-
if (isColorSpec(value))
|
|
341
|
-
theme.bins[bin] = value;
|
|
342
|
-
else
|
|
343
|
-
warn(`${where}: bin ${bin} has no valid colour`);
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
function endsWalk(home) {
|
|
348
|
-
return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
|
|
349
|
-
}
|
|
350
|
-
function warnOnce(message) {
|
|
351
|
-
if (warned.has(message))
|
|
352
|
-
return;
|
|
353
|
-
warned.add(message);
|
|
354
|
-
console.error(`warning: theme ${message}`);
|
|
355
|
-
}
|
|
356
|
-
function isPath(chosen) {
|
|
357
|
-
return chosen.includes("/") || chosen.endsWith(".json");
|
|
358
|
-
}
|
|
359
|
-
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
360
|
-
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
361
|
-
const sources = [];
|
|
362
|
-
const chosen = env.KIT_THEME ?? "";
|
|
363
|
-
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
364
|
-
if (isPath(chosen))
|
|
365
|
-
wanted.push(resolve2(from, chosen));
|
|
366
|
-
const files = [];
|
|
367
|
-
for (const path of wanted) {
|
|
368
|
-
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
369
|
-
if (path !== undefined && file !== undefined)
|
|
370
|
-
files.push({ path, file });
|
|
371
|
-
}
|
|
372
|
-
let preset = "default";
|
|
373
|
-
if (chosen !== "" && !isPath(chosen)) {
|
|
374
|
-
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
375
|
-
} else {
|
|
376
|
-
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
377
|
-
if (named !== undefined)
|
|
378
|
-
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
379
|
-
}
|
|
380
|
-
for (const { path, file } of files) {
|
|
381
|
-
applyFile(theme, file, path, warn);
|
|
382
|
-
sources.push(path);
|
|
383
|
-
}
|
|
384
|
-
return { theme, sources, preset };
|
|
385
|
-
}
|
|
386
|
-
function activeTheme() {
|
|
387
|
-
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
388
|
-
if (current === undefined || key !== currentKey) {
|
|
389
|
-
current = loadTheme();
|
|
390
|
-
currentKey = key;
|
|
391
|
-
}
|
|
392
|
-
return current;
|
|
393
|
-
}
|
|
394
|
-
var fromLinear = (value) => Math.round(255 * Math.min(1, Math.max(0, value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055))), ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
|
|
395
|
-
var init_theme = __esm(() => {
|
|
396
|
-
init_config();
|
|
397
|
-
init_user_config();
|
|
398
|
-
ENDS = new Map;
|
|
399
|
-
DEFAULT = {
|
|
400
|
-
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" },
|
|
401
|
-
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" },
|
|
402
|
-
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
403
|
-
bins: {},
|
|
404
|
-
gradient: ["#c084fc", "#67e8f9"]
|
|
405
|
-
};
|
|
406
|
-
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" };
|
|
407
|
-
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" };
|
|
408
|
-
ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
409
|
-
PRESETS = {
|
|
410
|
-
default: {},
|
|
411
|
-
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
412
|
-
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
413
|
-
ascii: { glyphs: ASCII }
|
|
414
|
-
};
|
|
415
|
-
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"]);
|
|
416
|
-
HEX = /^#[0-9a-f]{6}$/i;
|
|
417
|
-
CONTROL = /\p{Cc}/u;
|
|
418
|
-
MAX_FILE_BYTES = 64 * 1024;
|
|
419
|
-
SPACES = /\s+/;
|
|
420
|
-
CUBE = [0, 95, 135, 175, 215, 255];
|
|
421
|
-
warned = new Set;
|
|
422
|
-
});
|
|
423
|
-
|
|
424
|
-
// ../kit/src/style.ts
|
|
425
|
-
import process6 from "process";
|
|
426
|
-
function takesControlCodes(stream, env = process6.env) {
|
|
427
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
428
|
-
}
|
|
429
|
-
function paint(stream, env = process6.env) {
|
|
430
|
-
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
431
|
-
}
|
|
432
|
-
function marked(mark, text, stream, detail, env = process6.env) {
|
|
433
|
-
const colors = paint(stream, env);
|
|
434
|
-
let head = MARK_WORDS[mark];
|
|
435
|
-
if (takesControlCodes(stream, env)) {
|
|
436
|
-
const { theme } = activeTheme();
|
|
437
|
-
head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
|
|
438
|
-
}
|
|
439
|
-
return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
|
|
440
|
-
}
|
|
441
|
-
function ok(text, detail) {
|
|
442
|
-
console.log(marked("ok", text, process6.stdout, detail));
|
|
443
|
-
}
|
|
444
|
-
function note(text, detail) {
|
|
445
|
-
console.log(marked("note", text, process6.stdout, detail));
|
|
446
|
-
}
|
|
447
|
-
function problem(text, detail) {
|
|
448
|
-
console.error(marked("problem", text, process6.stderr, detail));
|
|
449
|
-
}
|
|
450
|
-
function role(name, stream, env = process6.env) {
|
|
451
|
-
const colors = paint(stream, env);
|
|
452
|
-
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
453
|
-
}
|
|
454
|
-
function header(bin, context, stream, env = process6.env) {
|
|
455
|
-
if (!takesControlCodes(stream, env))
|
|
456
|
-
return "";
|
|
457
|
-
const colors = paint(stream, env);
|
|
458
|
-
const hash = [...bin].reduce((sum, char) => sum + char.charCodeAt(0), 0);
|
|
459
|
-
const { theme } = activeTheme();
|
|
460
|
-
const spec = theme.bins[bin] ?? theme.accents[hash % theme.accents.length];
|
|
461
|
-
const accent = tinted(typeof spec === "string" && spec.split(" ").includes("bold") ? colors : colors.bold, spec, env);
|
|
462
|
-
return `${accent(bin)}${context === undefined ? "" : colors.dim(` \u203A ${context}`)}`;
|
|
463
|
-
}
|
|
464
|
-
function printHeader(bin, context, stream = process6.stdout, env = process6.env) {
|
|
465
|
-
const line = header(bin, context, stream, env);
|
|
466
|
-
if (line !== "")
|
|
467
|
-
console.log(line);
|
|
468
|
-
}
|
|
469
|
-
var MARK_WORDS, STATUS_WORDS, STATUS_OF;
|
|
470
|
-
var init_style = __esm(() => {
|
|
471
|
-
init_colors();
|
|
472
|
-
init_mode();
|
|
473
|
-
init_theme();
|
|
474
|
-
MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
|
|
475
|
-
STATUS_WORDS = {
|
|
476
|
-
passed: ["passed", "success", "succeeded", "ok"],
|
|
477
|
-
failed: ["failed", "failure", "error", "errored"],
|
|
478
|
-
running: ["running", "in_progress", "started", "holding"],
|
|
479
|
-
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
480
|
-
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
481
|
-
};
|
|
482
|
-
STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
483
|
-
});
|
|
484
|
-
|
|
485
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-knqbxp56.js
|
|
486
|
-
function tt(i, { units: r = "iec", dp: t = 1, locale: n } = {}) {
|
|
487
|
-
let e = r === "si" ? 1000 : 1024;
|
|
488
|
-
if (Math.abs(i) < e)
|
|
489
|
-
return `${i} B`;
|
|
490
|
-
let s = r === "iec" ? ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] : ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], o = -1, a = 10 ** t;
|
|
491
|
-
do
|
|
492
|
-
i /= e, ++o;
|
|
493
|
-
while (Math.round(Math.abs(i) * a) / a >= e && o < s.length - 1);
|
|
494
|
-
return `${n ? y(n, { minimumFractionDigits: t, maximumFractionDigits: t }).format(i) : i.toFixed(t)} ${s[o]}`;
|
|
495
|
-
}
|
|
496
|
-
var init_chunk_knqbxp56 = __esm(() => {
|
|
497
|
-
init_chunk_n6z2kk96();
|
|
498
|
-
});
|
|
499
|
-
|
|
500
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/format/index.js
|
|
501
|
-
var init_format = __esm(() => {
|
|
502
|
-
init_chunk_knqbxp56();
|
|
503
|
-
});
|
|
504
|
-
|
|
505
|
-
// ../kit/src/format.ts
|
|
506
|
-
import process7 from "process";
|
|
507
|
-
function formatSeconds(total) {
|
|
508
|
-
let rest = Math.max(0, Math.round(total));
|
|
509
|
-
const amounts = UNITS.map(([unit, size]) => {
|
|
510
|
-
const amount = Math.floor(rest / size);
|
|
511
|
-
rest -= amount * size;
|
|
512
|
-
return `${amount}${unit}`;
|
|
513
|
-
});
|
|
514
|
-
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
515
|
-
if (first === -1)
|
|
516
|
-
return "0s";
|
|
517
|
-
const next = amounts[first + 1];
|
|
518
|
-
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
519
|
-
}
|
|
520
|
-
function formatDuration(ms) {
|
|
521
|
-
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
522
|
-
}
|
|
523
|
-
function formatElapsed(ms) {
|
|
524
|
-
return formatSeconds(Math.floor(Math.max(0, ms) / 1000));
|
|
525
|
-
}
|
|
526
|
-
function upTo(text, separator) {
|
|
527
|
-
const end = text.indexOf(separator);
|
|
528
|
-
return end === -1 ? text : text.slice(0, end);
|
|
529
|
-
}
|
|
530
|
-
function formatAge(date, now = Date.now()) {
|
|
531
|
-
const at = typeof date === "number" ? date : Date.parse(date);
|
|
532
|
-
if (Number.isNaN(at))
|
|
533
|
-
return "-";
|
|
534
|
-
const seconds = (now - at) / 1000;
|
|
535
|
-
return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
|
|
536
|
-
}
|
|
537
|
-
function truncate(text, width) {
|
|
538
|
-
return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
|
|
539
|
-
}
|
|
540
|
-
function textWidth(text) {
|
|
541
|
-
return Bun.stringWidth(text);
|
|
542
|
-
}
|
|
543
|
-
function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
|
|
544
|
-
const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
|
|
545
|
-
if (outputMode(stream, env) === "agent")
|
|
546
|
-
return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
|
|
547
|
-
`);
|
|
548
|
-
const widths = [];
|
|
549
|
-
for (const row of cells) {
|
|
550
|
-
for (const [index, cell] of row.entries())
|
|
551
|
-
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
552
|
-
}
|
|
553
|
-
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
554
|
-
const colors = paint(stream);
|
|
555
|
-
const lines = shown.map((row) => row.map((cell, index) => {
|
|
556
|
-
const width = widths[index] ?? 0;
|
|
557
|
-
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
558
|
-
if (align[index] === "right")
|
|
559
|
-
return `${gap}${cell}`;
|
|
560
|
-
return index === row.length - 1 ? cell : `${cell}${gap}`;
|
|
561
|
-
}).join(" ").trimEnd());
|
|
562
|
-
const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
|
|
563
|
-
return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
|
|
564
|
-
`);
|
|
565
|
-
}
|
|
566
|
-
function narrow(rows, widths, limit) {
|
|
567
|
-
const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
|
|
568
|
-
const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
|
|
569
|
-
const floor = 8;
|
|
570
|
-
while (used() > limit) {
|
|
571
|
-
let widest = -1;
|
|
572
|
-
for (const [index, width] of widths.entries()) {
|
|
573
|
-
if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
|
|
574
|
-
widest = index;
|
|
575
|
-
}
|
|
576
|
-
if (widest === -1)
|
|
577
|
-
break;
|
|
578
|
-
widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
|
|
579
|
-
}
|
|
580
|
-
return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
|
|
581
|
-
}
|
|
582
|
-
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
583
|
-
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
584
|
-
}
|
|
585
|
-
function printJson(value) {
|
|
586
|
-
console.log(jsonText(value));
|
|
587
|
-
}
|
|
588
|
-
var UNITS, LINE_BREAKS, ESCAPE;
|
|
589
|
-
var init_format2 = __esm(() => {
|
|
590
|
-
init_text();
|
|
591
|
-
init_mode();
|
|
592
|
-
init_style();
|
|
593
|
-
init_format();
|
|
594
|
-
UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
595
|
-
LINE_BREAKS = /\s*\n\s*/g;
|
|
596
|
-
ESCAPE = String.fromCharCode(27);
|
|
597
|
-
});
|
|
598
|
-
|
|
599
|
-
// ../kit/src/help.ts
|
|
600
|
-
import process8 from "process";
|
|
601
|
-
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
602
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
603
|
-
`);
|
|
604
|
-
const blank = lines.indexOf("");
|
|
605
|
-
const synopses = blank === -1 ? lines : lines.slice(0, blank);
|
|
606
|
-
const details = blank === -1 ? [] : lines.slice(blank + 1);
|
|
607
|
-
const colon = synopses[0].indexOf(": ");
|
|
608
|
-
const inline = synopses[0].slice(colon + 2);
|
|
609
|
-
const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
|
|
610
|
-
if (colon !== -1)
|
|
611
|
-
synopses[0] = synopses[0].slice(0, colon);
|
|
612
|
-
const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
|
|
613
|
-
`)}`;
|
|
614
|
-
const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
|
|
615
|
-
const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
|
|
616
|
-
return [head, ...lead, ...rest].join(`
|
|
617
|
-
`);
|
|
618
|
-
}
|
|
619
|
-
function prose(line, colors) {
|
|
620
|
-
if (colors.cyan("x") === "x")
|
|
621
|
-
return line;
|
|
622
|
-
return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
|
|
623
|
-
}
|
|
624
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
625
|
-
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
626
|
-
`);
|
|
627
|
-
}
|
|
628
|
-
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
629
|
-
if (exits.length === 0)
|
|
630
|
-
return [];
|
|
631
|
-
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
632
|
-
}
|
|
633
|
-
function wantsHelpJson(env = process8.env) {
|
|
634
|
-
return env.KIT_HELP === "json";
|
|
635
|
-
}
|
|
636
|
-
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
637
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
638
|
-
`);
|
|
639
|
-
const first = lines[0];
|
|
640
|
-
const colon = first.indexOf(": ");
|
|
641
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
642
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
643
|
-
return {
|
|
644
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
645
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
646
|
-
...replaces === undefined ? {} : { replaces },
|
|
647
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
648
|
-
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
649
|
-
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
650
|
-
};
|
|
651
|
-
}
|
|
652
|
-
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
653
|
-
if (examples.length === 0 || outputMode() === "agent")
|
|
654
|
-
return [];
|
|
655
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
656
|
-
}
|
|
657
|
-
function optionRows(options, colors = paint(process8.stdout)) {
|
|
658
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
659
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
660
|
-
const choices = option.choices?.join("|");
|
|
661
|
-
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
662
|
-
const named = inline ? `<${choices}>` : "<value>";
|
|
663
|
-
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
664
|
-
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
665
|
-
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
666
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
667
|
-
});
|
|
668
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
669
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
670
|
-
}
|
|
671
|
-
var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
|
|
672
|
-
var init_help = __esm(() => {
|
|
673
|
-
init_mode();
|
|
674
|
-
init_style();
|
|
675
|
-
OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
676
|
-
USAGE_PREFIX = /^usage:\s*/i;
|
|
677
|
-
FULL_STOP = /\.$/;
|
|
678
|
-
PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
|
|
679
|
-
});
|
|
680
|
-
|
|
681
|
-
// ../kit/src/text.ts
|
|
682
|
-
function distance(a, b) {
|
|
683
|
-
const left = [...a];
|
|
684
|
-
const right = [...b];
|
|
685
|
-
let before = [];
|
|
686
|
-
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
687
|
-
for (const [i, x] of left.entries()) {
|
|
688
|
-
const current = [i + 1];
|
|
689
|
-
for (const [j, y] of right.entries()) {
|
|
690
|
-
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
691
|
-
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
692
|
-
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
693
|
-
current.push(cost);
|
|
694
|
-
}
|
|
695
|
-
before = previous;
|
|
696
|
-
previous = current;
|
|
697
|
-
}
|
|
698
|
-
return previous[right.length] ?? 0;
|
|
699
|
-
}
|
|
700
|
-
function closest(name, names) {
|
|
701
|
-
const started = names.find((known) => known.startsWith(name));
|
|
702
|
-
if (started !== undefined)
|
|
703
|
-
return started;
|
|
704
|
-
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
705
|
-
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
706
|
-
}
|
|
707
|
-
var init_text2 = () => {};
|
|
708
|
-
|
|
709
|
-
// ../kit/src/input.ts
|
|
710
|
-
function durationMs(text, unit) {
|
|
711
|
-
if (BARE_DURATION.test(text))
|
|
712
|
-
return Number(text) * UNIT_MS[unit];
|
|
713
|
-
if (!DURATION.test(text))
|
|
714
|
-
return 0;
|
|
715
|
-
let ms = 0;
|
|
716
|
-
for (const [, amount, part] of text.matchAll(DURATION_PART))
|
|
717
|
-
ms += Number(amount) * UNIT_MS[part];
|
|
718
|
-
return ms;
|
|
719
|
-
}
|
|
720
|
-
function duration(value, name, fallback, unit = "s") {
|
|
721
|
-
if (value === undefined)
|
|
722
|
-
return fallback;
|
|
723
|
-
const ms = durationMs(value.trim(), unit);
|
|
724
|
-
if (ms < 1)
|
|
725
|
-
badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
|
|
726
|
-
return ms;
|
|
727
|
-
}
|
|
728
|
-
var BARE_DURATION, DURATION, DURATION_PART, UNIT_MS;
|
|
729
|
-
var init_input = __esm(() => {
|
|
730
|
-
init_args();
|
|
731
|
-
BARE_DURATION = /^\d+(?:\.\d+)?$/;
|
|
732
|
-
DURATION = /^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/;
|
|
733
|
-
DURATION_PART = /(\d+(?:\.\d+)?)(ms|min|[smhd])/g;
|
|
734
|
-
UNIT_MS = { ms: 1, s: 1000, m: 60000, min: 60000, h: 3600000, d: 86400000 };
|
|
735
|
-
});
|
|
736
|
-
|
|
737
|
-
// ../kit/src/args.ts
|
|
738
|
-
import process9 from "process";
|
|
739
|
-
import { parseArgs } from "util";
|
|
740
|
-
function jsonOption(holds) {
|
|
741
|
-
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
742
|
-
}
|
|
743
|
-
function fail(message, code = 2, hint) {
|
|
744
|
-
throw new Exit(message, code, hint);
|
|
745
|
-
}
|
|
746
|
-
function badUsage(message) {
|
|
747
|
-
throw new UsageError(message);
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
class Completing {
|
|
751
|
-
options;
|
|
752
|
-
positionals;
|
|
753
|
-
candidates;
|
|
754
|
-
constructor(options, positionals = [], candidates = {}) {
|
|
755
|
-
this.options = options;
|
|
756
|
-
this.positionals = positionals;
|
|
757
|
-
this.candidates = candidates;
|
|
758
|
-
}
|
|
759
|
-
}
|
|
760
|
-
function applyOutput(color, plain, env = process9.env) {
|
|
761
|
-
const when = plain === true ? "never" : color ?? "auto";
|
|
762
|
-
if (when === "auto")
|
|
763
|
-
return;
|
|
764
|
-
if (when !== "always" && when !== "never")
|
|
765
|
-
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
766
|
-
if (when === "always") {
|
|
767
|
-
env.FORCE_COLOR = "1";
|
|
768
|
-
delete env.NO_COLOR;
|
|
769
|
-
} else {
|
|
770
|
-
env.NO_COLOR = "1";
|
|
771
|
-
delete env.FORCE_COLOR;
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
function parse(args, usage, options, settings = {}) {
|
|
775
|
-
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
776
|
-
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
777
|
-
const listing = listed(all, settings.allowNegative === true);
|
|
778
|
-
if (completion.active)
|
|
779
|
-
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
780
|
-
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
781
|
-
let parsed;
|
|
782
|
-
try {
|
|
783
|
-
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
784
|
-
} catch (error) {
|
|
785
|
-
const message = parseError(error);
|
|
786
|
-
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
787
|
-
}
|
|
788
|
-
const values = parsed.values;
|
|
789
|
-
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
790
|
-
if (values.help === true) {
|
|
791
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
792
|
-
throw new HelpShown;
|
|
793
|
-
}
|
|
794
|
-
checkChoices(parsed.values, all);
|
|
795
|
-
checkConflicts(parsed.values, all);
|
|
796
|
-
if (settings.positionals !== undefined)
|
|
797
|
-
checkPositionals(parsed.positionals, settings.positionals);
|
|
798
|
-
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
799
|
-
}
|
|
800
|
-
function splitRest(args, passes) {
|
|
801
|
-
const separator = passes ? args.indexOf("--") : -1;
|
|
802
|
-
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
803
|
-
}
|
|
804
|
-
function splitTrailing(args, options, count) {
|
|
805
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
806
|
-
let seen = 0;
|
|
807
|
-
if (count === 0)
|
|
808
|
-
return { own: args, rest: undefined };
|
|
809
|
-
for (let at = 0;at < args.length; at++) {
|
|
810
|
-
const word = args[at];
|
|
811
|
-
if (word === "--")
|
|
812
|
-
break;
|
|
813
|
-
if (word.startsWith("-")) {
|
|
814
|
-
if (takesValue(word))
|
|
815
|
-
at++;
|
|
816
|
-
continue;
|
|
817
|
-
}
|
|
818
|
-
seen++;
|
|
819
|
-
if (seen === count)
|
|
820
|
-
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
821
|
-
}
|
|
822
|
-
return { own: args, rest: undefined };
|
|
823
|
-
}
|
|
824
|
-
function listed(options, allowNegative) {
|
|
825
|
-
if (!allowNegative)
|
|
826
|
-
return options;
|
|
827
|
-
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
828
|
-
if (option.type !== "boolean" || option.negative === undefined)
|
|
829
|
-
return [[name, option]];
|
|
830
|
-
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
831
|
-
}));
|
|
832
|
-
}
|
|
833
|
-
function withAliases(args, options) {
|
|
834
|
-
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
835
|
-
if (named.size === 0)
|
|
836
|
-
return args;
|
|
837
|
-
const separator = args.indexOf("--");
|
|
838
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
839
|
-
return [...own.map((arg) => {
|
|
840
|
-
const at = arg.indexOf("=");
|
|
841
|
-
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
842
|
-
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
843
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
844
|
-
}
|
|
845
|
-
function withBare(args, options) {
|
|
846
|
-
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
847
|
-
if (bare.size === 0)
|
|
848
|
-
return args;
|
|
849
|
-
const separator = args.indexOf("--");
|
|
850
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
851
|
-
return [...own.flatMap((arg, index) => {
|
|
852
|
-
const optional = bare.get(arg);
|
|
853
|
-
const next = own[index + 1];
|
|
854
|
-
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
855
|
-
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
856
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
857
|
-
}
|
|
858
|
-
function checkConflicts(values, options) {
|
|
859
|
-
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
860
|
-
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
861
|
-
const other = given(name) ? conflicts.find(given) : undefined;
|
|
862
|
-
if (other !== undefined)
|
|
863
|
-
badUsage(`--${name} cannot be used with --${other}`);
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
function checkChoices(values, options) {
|
|
867
|
-
for (const [name, option] of Object.entries(options)) {
|
|
868
|
-
if (option.choices === undefined)
|
|
869
|
-
continue;
|
|
870
|
-
const given = values[name];
|
|
871
|
-
for (const value of Array.isArray(given) ? given : [given]) {
|
|
872
|
-
if (typeof value === "string")
|
|
873
|
-
oneOf(value, name, option.choices);
|
|
874
|
-
}
|
|
875
|
-
}
|
|
876
|
-
}
|
|
877
|
-
function oneOf(value, name, choices) {
|
|
878
|
-
if (!choices.includes(value))
|
|
879
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
880
|
-
return value;
|
|
881
|
-
}
|
|
882
|
-
function checkPositionals(given, names) {
|
|
883
|
-
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
884
|
-
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
885
|
-
if (given.length < required)
|
|
886
|
-
badUsage(`missing ${names[given.length]}`);
|
|
887
|
-
if (!variadic && given.length > names.length)
|
|
888
|
-
badUsage(`unexpected argument ${given[names.length]}`);
|
|
889
|
-
}
|
|
890
|
-
function joinDashValues(args, options) {
|
|
891
|
-
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
892
|
-
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
893
|
-
const joined = [];
|
|
894
|
-
for (let i = 0;i < args.length; i++) {
|
|
895
|
-
const arg = args[i] ?? "";
|
|
896
|
-
if (arg === "--")
|
|
897
|
-
return [...joined, ...args.slice(i)];
|
|
898
|
-
const name = longOf.get(arg);
|
|
899
|
-
const next = args[i + 1];
|
|
900
|
-
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
901
|
-
joined.push(`--${name}=${next}`);
|
|
902
|
-
i++;
|
|
903
|
-
} else {
|
|
904
|
-
joined.push(arg);
|
|
905
|
-
}
|
|
906
|
-
}
|
|
907
|
-
return joined;
|
|
908
|
-
}
|
|
909
|
-
function parseError(error) {
|
|
910
|
-
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
911
|
-
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
912
|
-
}
|
|
913
|
-
function nearestOption(message, options, allowNegative) {
|
|
914
|
-
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
915
|
-
if (typed === undefined)
|
|
916
|
-
return;
|
|
917
|
-
const word = typed.replace(DASHES, "");
|
|
918
|
-
if (word.length < 2 && !typed.startsWith("--"))
|
|
919
|
-
return;
|
|
920
|
-
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
921
|
-
...option.short === undefined ? [] : [`-${option.short}`],
|
|
922
|
-
`--${name}`,
|
|
923
|
-
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
924
|
-
]);
|
|
925
|
-
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
926
|
-
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
927
|
-
}
|
|
928
|
-
var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
|
|
929
|
-
var init_args = __esm(() => {
|
|
930
|
-
init_format2();
|
|
931
|
-
init_help();
|
|
932
|
-
init_text2();
|
|
933
|
-
init_help();
|
|
934
|
-
init_input();
|
|
935
|
-
DASHES = /^-+/;
|
|
936
|
-
EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
|
|
937
|
-
Exit = class Exit extends Error {
|
|
938
|
-
code;
|
|
939
|
-
hint;
|
|
940
|
-
[EXIT] = true;
|
|
941
|
-
constructor(message, code, hint) {
|
|
942
|
-
super(message);
|
|
943
|
-
this.code = code;
|
|
944
|
-
this.hint = hint;
|
|
945
|
-
}
|
|
946
|
-
static [Symbol.hasInstance](value) {
|
|
947
|
-
if (this !== Exit)
|
|
948
|
-
return Function.prototype[Symbol.hasInstance].call(this, value);
|
|
949
|
-
return typeof value === "object" && value !== null && value[EXIT] === true;
|
|
950
|
-
}
|
|
951
|
-
};
|
|
952
|
-
UsageError = class UsageError extends Exit {
|
|
953
|
-
constructor(message, hint) {
|
|
954
|
-
super(message, 2, hint);
|
|
955
|
-
}
|
|
956
|
-
};
|
|
957
|
-
HelpShown = class HelpShown extends Exit {
|
|
958
|
-
constructor() {
|
|
959
|
-
super("help shown", 0);
|
|
960
|
-
}
|
|
961
|
-
};
|
|
962
|
-
completion = { active: false };
|
|
963
|
-
OUTPUT_OPTIONS = {
|
|
964
|
-
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
965
|
-
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
966
|
-
};
|
|
967
|
-
UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
968
|
-
});
|
|
969
|
-
|
|
970
|
-
// ../kit/src/folders.ts
|
|
971
|
-
var SKIPPED_FOLDERS;
|
|
972
|
-
var init_folders = __esm(() => {
|
|
973
|
-
init_user_config();
|
|
974
|
-
SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
975
|
-
});
|
|
976
|
-
|
|
977
|
-
// ../kit/src/answers.ts
|
|
978
|
-
var init_answers = __esm(() => {
|
|
979
|
-
init_folders();
|
|
980
|
-
});
|
|
981
|
-
|
|
982
|
-
// ../kit/src/job.ts
|
|
983
|
-
import process24 from "process";
|
|
984
|
-
function stopJob() {
|
|
985
|
-
process24.kill(0, "SIGTSTP");
|
|
986
|
-
}
|
|
987
|
-
var init_job = () => {};
|
|
988
|
-
|
|
989
|
-
// ../kit/src/picker/line.ts
|
|
990
|
-
function isEditKey(key) {
|
|
991
|
-
return EDIT_KEYS.has(key);
|
|
992
|
-
}
|
|
993
|
-
var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS;
|
|
994
|
-
var init_line = __esm(() => {
|
|
995
|
-
EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
|
|
996
|
-
BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
|
|
997
|
-
FORWARD_KILLS = new Set(["killnext", "killend"]);
|
|
998
|
-
});
|
|
999
|
-
|
|
1000
|
-
// ../kit/src/picker/score.ts
|
|
1001
|
-
var BOUNDARY_AFTER, NONE;
|
|
1002
|
-
var init_score = __esm(() => {
|
|
1003
|
-
BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
|
|
1004
|
-
NONE = Number.NEGATIVE_INFINITY;
|
|
1005
|
-
});
|
|
1006
|
-
|
|
1007
|
-
// ../kit/src/picker/state.ts
|
|
1008
|
-
function repeat(value, count) {
|
|
1009
|
-
return Array.from({ length: count }).fill(value);
|
|
1010
|
-
}
|
|
1011
|
-
function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
1012
|
-
const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
|
|
1013
|
-
return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
|
|
1014
|
-
const wheel = MOUSE.exec(sequence)?.[1];
|
|
1015
|
-
if (wheel !== undefined)
|
|
1016
|
-
return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
|
|
1017
|
-
const named = codes.get(sequence);
|
|
1018
|
-
const key = named === undefined ? KEYS[sequence] : { ctrl: named };
|
|
1019
|
-
if (sequence === PASTE_START || sequence === PASTE_END) {
|
|
1020
|
-
paste.active = sequence === PASTE_START;
|
|
1021
|
-
return [];
|
|
1022
|
-
}
|
|
1023
|
-
if (paste.active && (sequence === "\r" || sequence === `
|
|
1024
|
-
`))
|
|
1025
|
-
return [];
|
|
1026
|
-
if (key !== undefined)
|
|
1027
|
-
return [key];
|
|
1028
|
-
return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
|
|
1029
|
-
});
|
|
1030
|
-
}
|
|
1031
|
-
var IS_CONTROL, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS;
|
|
1032
|
-
var init_state = __esm(() => {
|
|
1033
|
-
init_text2();
|
|
1034
|
-
init_line();
|
|
1035
|
-
init_score();
|
|
1036
|
-
IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
|
|
1037
|
-
KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
|
|
1038
|
-
MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
|
|
1039
|
-
KEYS = {
|
|
1040
|
-
"\x1B[A": "up",
|
|
1041
|
-
"\x1BOA": "up",
|
|
1042
|
-
"\x10": "up",
|
|
1043
|
-
"\x1B[B": "down",
|
|
1044
|
-
"\x1BOB": "down",
|
|
1045
|
-
"\x0E": "down",
|
|
1046
|
-
"\x1B[5~": "pageup",
|
|
1047
|
-
"\x1B[6~": "pagedown",
|
|
1048
|
-
"\x1B[H": "home",
|
|
1049
|
-
"\x1B[1~": "home",
|
|
1050
|
-
"\x1BOH": "home",
|
|
1051
|
-
"\x1B[F": "end",
|
|
1052
|
-
"\x1B[4~": "end",
|
|
1053
|
-
"\x1BOF": "end",
|
|
1054
|
-
"\r": "enter",
|
|
1055
|
-
"\n": "enter",
|
|
1056
|
-
"\x03": "cancel",
|
|
1057
|
-
"\x1B": "cancel",
|
|
1058
|
-
"\x1B[D": "left",
|
|
1059
|
-
"\x1BOD": "left",
|
|
1060
|
-
"\x1B[C": "right",
|
|
1061
|
-
"\x1BOC": "right",
|
|
1062
|
-
"\x1B[1;5D": "wordleft",
|
|
1063
|
-
"\x1B[1;3D": "wordleft",
|
|
1064
|
-
"\x1Bb": "wordleft",
|
|
1065
|
-
"\x1B[1;5C": "wordright",
|
|
1066
|
-
"\x1B[1;3C": "wordright",
|
|
1067
|
-
"\x1Bf": "wordright",
|
|
1068
|
-
"\x01": "linestart",
|
|
1069
|
-
"\x05": "lineend",
|
|
1070
|
-
"\x7F": "erase",
|
|
1071
|
-
"\x1B[3~": "delete",
|
|
1072
|
-
"\b": "killword",
|
|
1073
|
-
"\x1B\x7F": "killword",
|
|
1074
|
-
"\x1B[3;5~": "killnext",
|
|
1075
|
-
"\x1Bd": "killnext",
|
|
1076
|
-
"\x15": "clear",
|
|
1077
|
-
"\v": "killend",
|
|
1078
|
-
"\x17": "word",
|
|
1079
|
-
"\x19": "yank",
|
|
1080
|
-
"\x1A": "suspend",
|
|
1081
|
-
"\t": "tab",
|
|
1082
|
-
"\x1F": "help",
|
|
1083
|
-
"\x1BOP": "help",
|
|
1084
|
-
"\x1B[11~": "help"
|
|
1085
|
-
};
|
|
1086
|
-
});
|
|
1087
|
-
|
|
1088
|
-
// ../kit/src/redraw.ts
|
|
1089
|
-
function overwrite(lines, columns) {
|
|
1090
|
-
return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
|
|
1091
|
-
`);
|
|
1092
|
-
}
|
|
1093
|
-
function rowsTaken(lines, columns) {
|
|
1094
|
-
return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
|
|
1095
|
-
}
|
|
1096
|
-
var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
|
|
1097
|
-
var init_redraw = __esm(() => {
|
|
1098
|
-
init_format2();
|
|
1099
|
-
});
|
|
1100
|
-
|
|
1101
|
-
// ../kit/src/prompt.ts
|
|
1102
|
-
import process25 from "process";
|
|
1103
|
-
function readKeys(input, paste = { active: false }) {
|
|
1104
|
-
return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
|
|
1105
|
-
}
|
|
1106
|
-
async function confirm(question, { default: fallback, ...settings } = {}) {
|
|
1107
|
-
let answered = fallback;
|
|
1108
|
-
const choices = { true: "Y/n", false: "y/N", undefined: "y/n" }[String(fallback)];
|
|
1109
|
-
const accepted = await ask(question, settings, (colors, state) => [state === "asking" ? asking(colors, question, "", choices) : answer(colors, question, state, answered ? "yes" : "no")], (key) => {
|
|
1110
|
-
if (key === "cancel")
|
|
1111
|
-
return "cancel";
|
|
1112
|
-
if (key === "enter")
|
|
1113
|
-
return answered === undefined ? undefined : "enter";
|
|
1114
|
-
const letter = typeof key === "object" ? key.text.toLowerCase() : "";
|
|
1115
|
-
if (letter !== "y" && letter !== "n")
|
|
1116
|
-
return;
|
|
1117
|
-
answered = letter === "y";
|
|
1118
|
-
return "enter";
|
|
1119
|
-
});
|
|
1120
|
-
return accepted ? answered : undefined;
|
|
1121
|
-
}
|
|
1122
|
-
function asking(colors, question, typed, keys) {
|
|
1123
|
-
return `${colors.cyan("?")} ${question} ${typed === "" ? colors.dim(`(${keys})`) : typed}`;
|
|
1124
|
-
}
|
|
1125
|
-
function answer(colors, question, state, picked) {
|
|
1126
|
-
return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
|
|
1127
|
-
}
|
|
1128
|
-
async function ask(question, { hint, terminal = process25 }, render, press) {
|
|
1129
|
-
const { stdin, stderr } = terminal;
|
|
1130
|
-
if (!isInteractive(terminal))
|
|
1131
|
-
fail(`cannot ask "${question}" off a terminal`, 2, hint);
|
|
1132
|
-
const colors = paint(stderr);
|
|
1133
|
-
let current = "asking";
|
|
1134
|
-
let outcome;
|
|
1135
|
-
const columns = () => stderr.columns || 80;
|
|
1136
|
-
const draw = (state, last = false) => {
|
|
1137
|
-
const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
|
|
1138
|
-
const rows = rowsTaken(frame, columns());
|
|
1139
|
-
stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
|
|
1140
|
-
current = state;
|
|
1141
|
-
};
|
|
1142
|
-
const redraw = () => draw(current);
|
|
1143
|
-
const paste = { active: false };
|
|
1144
|
-
const stop = terminal.stop ?? (terminal === process25 ? stopJob : undefined);
|
|
1145
|
-
const suspend = () => {
|
|
1146
|
-
if (stop === undefined)
|
|
1147
|
-
return;
|
|
1148
|
-
stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
|
|
1149
|
-
stdin.setRawMode(false);
|
|
1150
|
-
stop();
|
|
1151
|
-
stdin.setRawMode(true);
|
|
1152
|
-
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
1153
|
-
};
|
|
1154
|
-
try {
|
|
1155
|
-
stderr.on?.("resize", redraw);
|
|
1156
|
-
stdin.setRawMode(true);
|
|
1157
|
-
stdin.resume();
|
|
1158
|
-
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
1159
|
-
draw("asking");
|
|
1160
|
-
return await new Promise((resolve) => {
|
|
1161
|
-
function onData(data) {
|
|
1162
|
-
for (const key of readKeys(data.toString(), paste)) {
|
|
1163
|
-
if (key === "suspend") {
|
|
1164
|
-
suspend();
|
|
1165
|
-
continue;
|
|
1166
|
-
}
|
|
1167
|
-
const pressed = press(key);
|
|
1168
|
-
if (pressed !== undefined) {
|
|
1169
|
-
settle(pressed);
|
|
1170
|
-
return;
|
|
1171
|
-
}
|
|
1172
|
-
}
|
|
1173
|
-
draw("asking");
|
|
1174
|
-
}
|
|
1175
|
-
function onEnd() {
|
|
1176
|
-
settle("cancel");
|
|
1177
|
-
}
|
|
1178
|
-
function settle(settled) {
|
|
1179
|
-
outcome = settled;
|
|
1180
|
-
stdin.off("data", onData);
|
|
1181
|
-
stdin.off("end", onEnd);
|
|
1182
|
-
resolve(settled === "enter");
|
|
1183
|
-
}
|
|
1184
|
-
stdin.on("data", onData);
|
|
1185
|
-
stdin.on("end", onEnd);
|
|
1186
|
-
});
|
|
1187
|
-
} finally {
|
|
1188
|
-
stderr.off?.("resize", redraw);
|
|
1189
|
-
draw(outcome ?? "cancel", true);
|
|
1190
|
-
stderr.write(`
|
|
1191
|
-
\x1B[?25h\x1B[?2004l`);
|
|
1192
|
-
stdin.setRawMode(false);
|
|
1193
|
-
stdin.pause();
|
|
1194
|
-
}
|
|
1195
|
-
}
|
|
1196
|
-
var PROMPT_KEYS;
|
|
1197
|
-
var init_prompt = __esm(() => {
|
|
1198
|
-
init_answers();
|
|
1199
|
-
init_args();
|
|
1200
|
-
init_format2();
|
|
1201
|
-
init_job();
|
|
1202
|
-
init_mode();
|
|
1203
|
-
init_line();
|
|
1204
|
-
init_state();
|
|
1205
|
-
init_redraw();
|
|
1206
|
-
init_style();
|
|
1207
|
-
PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
|
|
1208
|
-
});
|
|
1209
|
-
|
|
1210
|
-
// src/cli.ts
|
|
1211
|
-
import process26 from "process";
|
|
1212
|
-
|
|
1213
|
-
// ../kit/src/advisory.ts
|
|
1214
|
-
var SEVERITIES = ["low", "moderate", "high", "critical"];
|
|
1215
|
-
function severityRank(severity) {
|
|
1216
|
-
return SEVERITIES.indexOf(severity);
|
|
1217
|
-
}
|
|
1218
|
-
function isIgnored(advisory, ignore) {
|
|
1219
|
-
return ignore.includes(advisory.ghsa ?? "") || ignore.includes(String(advisory.id));
|
|
1220
|
-
}
|
|
1221
|
-
|
|
1222
|
-
// ../kit/src/index.ts
|
|
1223
|
-
init_args();
|
|
1224
|
-
|
|
1225
|
-
// ../kit/src/argv.ts
|
|
1226
|
-
import { readFileSync as readFileSync3, realpathSync } from "fs";
|
|
1227
|
-
import { resolve as resolve3 } from "path";
|
|
1228
|
-
import process10 from "process";
|
|
1229
|
-
function commandLine() {
|
|
1230
|
-
try {
|
|
1231
|
-
return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
1232
|
-
} catch {
|
|
1233
|
-
return;
|
|
1234
|
-
}
|
|
1235
|
-
}
|
|
1236
|
-
function realPath(word) {
|
|
1237
|
-
try {
|
|
1238
|
-
return realpathSync(resolve3(word));
|
|
1239
|
-
} catch {
|
|
1240
|
-
return;
|
|
1241
|
-
}
|
|
1242
|
-
}
|
|
1243
|
-
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
1244
|
-
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
1245
|
-
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
1246
|
-
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
1247
|
-
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
1248
|
-
}
|
|
1249
|
-
// ../kit/src/chart.ts
|
|
1250
|
-
init_format2();
|
|
1251
|
-
init_mode();
|
|
1252
|
-
init_style();
|
|
1253
|
-
init_theme();
|
|
1254
|
-
// ../kit/src/ci.ts
|
|
1255
|
-
init_args();
|
|
1256
|
-
init_format2();
|
|
1257
|
-
|
|
1258
|
-
// ../kit/src/progress.ts
|
|
1259
|
-
init_format2();
|
|
1260
|
-
import process12 from "process";
|
|
1261
|
-
|
|
1262
|
-
// ../kit/src/process.ts
|
|
1263
|
-
import { readFileSync as readFileSync4 } from "fs";
|
|
1264
|
-
import { constants } from "os";
|
|
1265
|
-
import process11 from "process";
|
|
1266
|
-
var KILL_GRACE_MS = 2000;
|
|
1267
|
-
var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
1268
|
-
var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
|
|
1269
|
-
function exitCodeOf(code, signal) {
|
|
1270
|
-
if (code !== null)
|
|
1271
|
-
return code;
|
|
1272
|
-
if (typeof signal === "number")
|
|
1273
|
-
return 128 + signal;
|
|
1274
|
-
return signal === null ? 129 : 128 + constants.signals[signal];
|
|
1275
|
-
}
|
|
1276
|
-
function groupsOf(pid) {
|
|
1277
|
-
try {
|
|
1278
|
-
const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
|
|
1279
|
-
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
1280
|
-
return { group: Number(fields[2]), foreground: Number(fields[5]) };
|
|
1281
|
-
} catch {
|
|
1282
|
-
return;
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
function heardTheTerminal(child) {
|
|
1286
|
-
if (child.pid === undefined)
|
|
1287
|
-
return false;
|
|
1288
|
-
const own = groupsOf("self");
|
|
1289
|
-
return own !== undefined && own.group === own.foreground && groupsOf(child.pid)?.group === own.group;
|
|
1290
|
-
}
|
|
1291
|
-
function holdSignals(cleanup) {
|
|
1292
|
-
let received;
|
|
1293
|
-
let child;
|
|
1294
|
-
const held = {
|
|
1295
|
-
get signal() {
|
|
1296
|
-
return received;
|
|
1297
|
-
},
|
|
1298
|
-
forward: (to) => {
|
|
1299
|
-
child = to;
|
|
1300
|
-
},
|
|
1301
|
-
release: () => {
|
|
1302
|
-
for (const signal of SIGNALS)
|
|
1303
|
-
process11.off(signal, onSignal);
|
|
1304
|
-
}
|
|
1305
|
-
};
|
|
1306
|
-
function onSignal(signal) {
|
|
1307
|
-
received = signal;
|
|
1308
|
-
if (child !== undefined) {
|
|
1309
|
-
if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
|
|
1310
|
-
child.kill(signal);
|
|
1311
|
-
return;
|
|
1312
|
-
}
|
|
1313
|
-
if (cleanup === undefined)
|
|
1314
|
-
return;
|
|
1315
|
-
held.release();
|
|
1316
|
-
cleanup(signal);
|
|
1317
|
-
process11.kill(process11.pid, signal);
|
|
1318
|
-
}
|
|
1319
|
-
for (const signal of SIGNALS)
|
|
1320
|
-
process11.on(signal, onSignal);
|
|
1321
|
-
return held;
|
|
1322
|
-
}
|
|
1323
|
-
async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
1324
|
-
const chunks = [];
|
|
1325
|
-
const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
|
|
1326
|
-
const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin: input === undefined ? stdin : new TextEncoder().encode(input), stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
|
|
1327
|
-
const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
|
|
1328
|
-
const timers = [];
|
|
1329
|
-
const killGroup = (killing) => {
|
|
1330
|
-
if (state.done)
|
|
1331
|
-
return;
|
|
1332
|
-
try {
|
|
1333
|
-
if (grouped)
|
|
1334
|
-
process11.kill(-proc.pid, killing);
|
|
1335
|
-
else
|
|
1336
|
-
proc.kill(killing);
|
|
1337
|
-
} catch {}
|
|
1338
|
-
};
|
|
1339
|
-
const stop = () => {
|
|
1340
|
-
killGroup("SIGTERM");
|
|
1341
|
-
timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
|
|
1342
|
-
};
|
|
1343
|
-
const onAbort = () => stop();
|
|
1344
|
-
if (timeoutMs !== undefined) {
|
|
1345
|
-
timers.push(setTimeout(() => {
|
|
1346
|
-
state.timedOut = true;
|
|
1347
|
-
stop();
|
|
1348
|
-
}, timeoutMs));
|
|
1349
|
-
}
|
|
1350
|
-
if (signal?.aborted === true)
|
|
1351
|
-
onAbort();
|
|
1352
|
-
else
|
|
1353
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1354
|
-
onStart?.({ kill: (killing) => killGroup(killing) });
|
|
1355
|
-
const drain = async (stream, name) => {
|
|
1356
|
-
for await (const data of stream) {
|
|
1357
|
-
if (state.failure !== undefined)
|
|
1358
|
-
continue;
|
|
1359
|
-
try {
|
|
1360
|
-
onChunk?.({ stream: name, data });
|
|
1361
|
-
} catch (error) {
|
|
1362
|
-
state.failure = error;
|
|
1363
|
-
stop();
|
|
1364
|
-
continue;
|
|
1365
|
-
}
|
|
1366
|
-
if (state.truncated)
|
|
1367
|
-
continue;
|
|
1368
|
-
let kept = data;
|
|
1369
|
-
if (state.kept + data.length > maxBytes) {
|
|
1370
|
-
let cut = maxBytes - state.kept;
|
|
1371
|
-
while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
|
|
1372
|
-
cut--;
|
|
1373
|
-
kept = data.subarray(0, cut);
|
|
1374
|
-
state.truncated = true;
|
|
1375
|
-
}
|
|
1376
|
-
state.kept += kept.length;
|
|
1377
|
-
if (kept.length > 0)
|
|
1378
|
-
chunks.push({ stream: name, data: kept });
|
|
1379
|
-
}
|
|
1380
|
-
};
|
|
1381
|
-
try {
|
|
1382
|
-
await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
|
|
1383
|
-
await proc.exited;
|
|
1384
|
-
} finally {
|
|
1385
|
-
state.done = true;
|
|
1386
|
-
for (const timer of timers)
|
|
1387
|
-
clearTimeout(timer);
|
|
1388
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1389
|
-
}
|
|
1390
|
-
if (state.failure !== undefined)
|
|
1391
|
-
throw state.failure;
|
|
1392
|
-
const joined = () => Buffer.concat(chunks.map(({ data }) => data));
|
|
1393
|
-
let output;
|
|
1394
|
-
let text;
|
|
1395
|
-
let stdout;
|
|
1396
|
-
return {
|
|
1397
|
-
code: exitCodeOf(proc.exitCode, proc.signalCode),
|
|
1398
|
-
chunks,
|
|
1399
|
-
timedOut: state.timedOut,
|
|
1400
|
-
truncated: state.truncated,
|
|
1401
|
-
get output() {
|
|
1402
|
-
return output ??= joined();
|
|
1403
|
-
},
|
|
1404
|
-
get text() {
|
|
1405
|
-
return text ??= (output ??= joined()).toString();
|
|
1406
|
-
},
|
|
1407
|
-
get stdout() {
|
|
1408
|
-
return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
|
|
1409
|
-
}
|
|
1410
|
-
};
|
|
1411
|
-
}
|
|
1412
|
-
|
|
1413
|
-
// ../kit/src/progress.ts
|
|
1414
|
-
init_style();
|
|
1415
|
-
init_theme();
|
|
1416
|
-
var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
1417
|
-
var FRAME_MS = 200;
|
|
1418
|
-
var BAR_WIDTH = 20;
|
|
1419
|
-
var CLEAR_BELOW = "\r\x1B[J";
|
|
1420
|
-
var ESC = String.fromCharCode(27);
|
|
1421
|
-
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
1422
|
-
var RESET_STYLE = `${ESC}[0m`;
|
|
1423
|
-
var CTRL_C = 3;
|
|
1424
|
-
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
1425
|
-
var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
|
|
1426
|
-
function liveRegion(render, stream = process12.stderr, env = process12.env) {
|
|
1427
|
-
if (!takesControlCodes(stream, env))
|
|
1428
|
-
return { redraw: () => {
|
|
1429
|
-
return;
|
|
1430
|
-
}, print: (text) => void stream.write(`${text}
|
|
1431
|
-
`), stop: () => {
|
|
1432
|
-
return;
|
|
1433
|
-
}, pause: () => () => {
|
|
1434
|
-
return;
|
|
1435
|
-
} };
|
|
1436
|
-
const write = stream.write.bind(stream);
|
|
1437
|
-
let frame = 0;
|
|
1438
|
-
let drawn = false;
|
|
1439
|
-
let paused = false;
|
|
1440
|
-
let stopped = false;
|
|
1441
|
-
const columns = () => {
|
|
1442
|
-
const now = stream.getWindowSize?.()[0] ?? stream.columns;
|
|
1443
|
-
return now === undefined || now === 0 ? 80 : now;
|
|
1444
|
-
};
|
|
1445
|
-
const clear = () => {
|
|
1446
|
-
if (drawn)
|
|
1447
|
-
write(CLEAR_BELOW);
|
|
1448
|
-
drawn = false;
|
|
1449
|
-
};
|
|
1450
|
-
const draw = () => {
|
|
1451
|
-
if (paused)
|
|
1452
|
-
return;
|
|
1453
|
-
const width = columns() - 1;
|
|
1454
|
-
const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
|
|
1455
|
-
const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
|
|
1456
|
-
if (lines.length === 0) {
|
|
1457
|
-
clear();
|
|
1458
|
-
return;
|
|
1459
|
-
}
|
|
1460
|
-
write(`${CLEAR_BELOW}${lines.join(`
|
|
1461
|
-
`)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
|
|
1462
|
-
drawn = true;
|
|
1463
|
-
};
|
|
1464
|
-
let timer = setInterval(draw, FRAME_MS);
|
|
1465
|
-
stream.on?.("resize", draw);
|
|
1466
|
-
let restore = interceptOutput(clear);
|
|
1467
|
-
let release = swallowInput();
|
|
1468
|
-
const onExit = () => {
|
|
1469
|
-
clear();
|
|
1470
|
-
release();
|
|
1471
|
-
};
|
|
1472
|
-
const signals = holdSignals(stop);
|
|
1473
|
-
function stop() {
|
|
1474
|
-
stopped = true;
|
|
1475
|
-
clearInterval(timer);
|
|
1476
|
-
stream.off?.("resize", draw);
|
|
1477
|
-
clear();
|
|
1478
|
-
restore();
|
|
1479
|
-
release();
|
|
1480
|
-
process12.off("exit", onExit);
|
|
1481
|
-
signals.release();
|
|
1482
|
-
}
|
|
1483
|
-
function pause() {
|
|
1484
|
-
if (paused || stopped)
|
|
1485
|
-
return () => {
|
|
1486
|
-
return;
|
|
1487
|
-
};
|
|
1488
|
-
paused = true;
|
|
1489
|
-
clearInterval(timer);
|
|
1490
|
-
stream.off?.("resize", draw);
|
|
1491
|
-
clear();
|
|
1492
|
-
restore();
|
|
1493
|
-
release();
|
|
1494
|
-
return () => {
|
|
1495
|
-
if (!paused || stopped)
|
|
1496
|
-
return;
|
|
1497
|
-
paused = false;
|
|
1498
|
-
timer = setInterval(draw, FRAME_MS);
|
|
1499
|
-
timer.unref();
|
|
1500
|
-
stream.on?.("resize", draw);
|
|
1501
|
-
restore = interceptOutput(clear);
|
|
1502
|
-
release = swallowInput();
|
|
1503
|
-
draw();
|
|
1504
|
-
};
|
|
1505
|
-
}
|
|
1506
|
-
timer.unref();
|
|
1507
|
-
process12.on("exit", onExit);
|
|
1508
|
-
return {
|
|
1509
|
-
redraw: draw,
|
|
1510
|
-
print: (text) => {
|
|
1511
|
-
clear();
|
|
1512
|
-
write(`${text}
|
|
1513
|
-
`);
|
|
1514
|
-
draw();
|
|
1515
|
-
},
|
|
1516
|
-
stop,
|
|
1517
|
-
pause
|
|
1518
|
-
};
|
|
1519
|
-
}
|
|
1520
|
-
function progressLine(stream = process12.stderr, env = process12.env) {
|
|
1521
|
-
const colors = paint(stream, env);
|
|
1522
|
-
const write = stream.write.bind(stream);
|
|
1523
|
-
const begun = performance.now();
|
|
1524
|
-
let started = begun;
|
|
1525
|
-
let current;
|
|
1526
|
-
const region = liveRegion((spinner) => current === undefined ? [] : [tintedParts(progressParts(current, spinner, performance.now() - started), colors)], stream, env);
|
|
1527
|
-
const end = (line) => {
|
|
1528
|
-
region.stop();
|
|
1529
|
-
write(`${line}
|
|
1530
|
-
`);
|
|
1531
|
-
};
|
|
1532
|
-
return {
|
|
1533
|
-
update: (progress) => {
|
|
1534
|
-
const step = current?.step;
|
|
1535
|
-
current = progress;
|
|
1536
|
-
if (progress.step !== step) {
|
|
1537
|
-
started = performance.now();
|
|
1538
|
-
region.redraw();
|
|
1539
|
-
}
|
|
1540
|
-
},
|
|
1541
|
-
stop: region.stop,
|
|
1542
|
-
pause: region.pause,
|
|
1543
|
-
done: (text) => end(marked("ok", text, stream, formatDuration(performance.now() - begun), env)),
|
|
1544
|
-
failed: (text) => end(marked("problem", text, stream, undefined, env))
|
|
1545
|
-
};
|
|
1546
|
-
}
|
|
1547
|
-
function progressParts({ step, done, total, unit }, spinner, ms) {
|
|
1548
|
-
const { theme } = activeTheme();
|
|
1549
|
-
const parts = [{ text: spinner, tint: (colors) => tinted(colors, theme.colors.accent) }, { text: ` ${step}`, tint: () => plain }];
|
|
1550
|
-
if (total !== undefined && total > 0) {
|
|
1551
|
-
const counted = Math.min(done ?? 0, total);
|
|
1552
|
-
const filled = Math.round(counted / total * BAR_WIDTH);
|
|
1553
|
-
parts.push({ text: " ", tint: () => plain }, { text: theme.glyphs.bar.repeat(filled), tint: (colors) => () => shaded(theme, colors, theme.glyphs.bar, filled, BAR_WIDTH) }, { text: theme.glyphs.bar.repeat(BAR_WIDTH - filled), tint: (colors) => colors.dim }, { text: ` ${counted}/${total}${unit === undefined ? "" : ` ${unit}`}`, tint: (colors) => colors.dim });
|
|
1554
|
-
}
|
|
1555
|
-
parts.push({ text: ` ${formatElapsed(ms)}`, tint: (colors) => colors.dim });
|
|
1556
|
-
return parts;
|
|
1557
|
-
}
|
|
1558
|
-
function plain(text) {
|
|
1559
|
-
return text;
|
|
1560
|
-
}
|
|
1561
|
-
function tintedParts(parts, colors) {
|
|
1562
|
-
return parts.map(({ text, tint }) => tint(colors)(text)).join("");
|
|
1563
|
-
}
|
|
1564
|
-
function cutToWidth(line, width) {
|
|
1565
|
-
if (Bun.stringWidth(line) <= width)
|
|
1566
|
-
return line;
|
|
1567
|
-
let room = width;
|
|
1568
|
-
let kept = "";
|
|
1569
|
-
let index = 0;
|
|
1570
|
-
let linked = false;
|
|
1571
|
-
while (index < line.length) {
|
|
1572
|
-
ESCAPE_CODE.lastIndex = index;
|
|
1573
|
-
const escape = ESCAPE_CODE.exec(line);
|
|
1574
|
-
if (escape !== null) {
|
|
1575
|
-
kept += escape[0];
|
|
1576
|
-
linked ||= escape[0].startsWith(`${ESC}]`);
|
|
1577
|
-
index = ESCAPE_CODE.lastIndex;
|
|
1578
|
-
continue;
|
|
1579
|
-
}
|
|
1580
|
-
const char = String.fromCodePoint(line.codePointAt(index));
|
|
1581
|
-
const columns = Bun.stringWidth(char);
|
|
1582
|
-
if (columns > room)
|
|
1583
|
-
break;
|
|
1584
|
-
kept += char;
|
|
1585
|
-
room -= columns;
|
|
1586
|
-
index += char.length;
|
|
1587
|
-
}
|
|
1588
|
-
return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
|
|
1589
|
-
}
|
|
1590
|
-
function swallowInput() {
|
|
1591
|
-
const input = process12.stdin;
|
|
1592
|
-
if (!input.isTTY)
|
|
1593
|
-
return () => {
|
|
1594
|
-
return;
|
|
1595
|
-
};
|
|
1596
|
-
const onData = (data) => {
|
|
1597
|
-
if (data.includes(CTRL_C))
|
|
1598
|
-
process12.kill(process12.pid, "SIGINT");
|
|
1599
|
-
};
|
|
1600
|
-
input.setRawMode(true);
|
|
1601
|
-
input.on("data", onData);
|
|
1602
|
-
input.resume();
|
|
1603
|
-
let released = false;
|
|
1604
|
-
return () => {
|
|
1605
|
-
if (released)
|
|
1606
|
-
return;
|
|
1607
|
-
released = true;
|
|
1608
|
-
input.off("data", onData);
|
|
1609
|
-
input.pause();
|
|
1610
|
-
input.setRawMode(false);
|
|
1611
|
-
};
|
|
1612
|
-
}
|
|
1613
|
-
function interceptOutput(clear) {
|
|
1614
|
-
const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
|
|
1615
|
-
const wrapped = targets.map(([target, name]) => {
|
|
1616
|
-
const original = Reflect.get(target, name);
|
|
1617
|
-
const wrapper = (...args) => {
|
|
1618
|
-
clear();
|
|
1619
|
-
return original.apply(target, args);
|
|
1620
|
-
};
|
|
1621
|
-
Reflect.set(target, name, wrapper);
|
|
1622
|
-
return { target, name, original, wrapper };
|
|
1623
|
-
});
|
|
1624
|
-
return () => {
|
|
1625
|
-
for (const { target, name, original, wrapper } of wrapped) {
|
|
1626
|
-
if (Reflect.get(target, name) === wrapper)
|
|
1627
|
-
Reflect.set(target, name, original);
|
|
1628
|
-
}
|
|
1629
|
-
};
|
|
1630
|
-
}
|
|
1631
|
-
|
|
1632
|
-
// ../kit/src/ci.ts
|
|
1633
|
-
init_style();
|
|
1634
|
-
|
|
1635
|
-
// ../kit/src/tool.ts
|
|
1636
|
-
init_format2();
|
|
1637
|
-
import process13 from "process";
|
|
1638
|
-
function cwdGone() {
|
|
1639
|
-
try {
|
|
1640
|
-
process13.cwd();
|
|
1641
|
-
return false;
|
|
1642
|
-
} catch {
|
|
1643
|
-
return true;
|
|
1644
|
-
}
|
|
1645
|
-
}
|
|
1646
|
-
|
|
1647
|
-
class SpawnError extends Error {
|
|
1648
|
-
missing;
|
|
1649
|
-
constructor(message, missing) {
|
|
1650
|
-
super(message);
|
|
1651
|
-
this.missing = missing;
|
|
1652
|
-
}
|
|
1653
|
-
}
|
|
1654
|
-
function spawnFailure(command, error) {
|
|
1655
|
-
const gone = cwdGone();
|
|
1656
|
-
const missing = !gone && error?.code === "ENOENT";
|
|
1657
|
-
return new SpawnError(`${command}: ${error instanceof Error ? error.message : String(error)}${gone ? " (the working directory was removed)" : ""}`, missing);
|
|
1658
|
-
}
|
|
1659
|
-
async function runTool(label, argv, { timeoutMs, cwd, onStart, env } = {}) {
|
|
1660
|
-
let ran;
|
|
1661
|
-
try {
|
|
1662
|
-
ran = await runCommand(argv, { env: { ...process13.env, ...env }, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
|
|
1663
|
-
} catch (error) {
|
|
1664
|
-
throw spawnFailure(label, error);
|
|
1665
|
-
}
|
|
1666
|
-
if (ran.timedOut)
|
|
1667
|
-
throw new Error(`${label}: no answer in ${formatDuration(timeoutMs ?? 0)}`);
|
|
1668
|
-
const decoders = { stdout: new TextDecoder, stderr: new TextDecoder };
|
|
1669
|
-
const streams = { stdout: "", stderr: "" };
|
|
1670
|
-
for (const { stream, data } of ran.chunks)
|
|
1671
|
-
streams[stream] += decoders[stream].decode(data, { stream: true });
|
|
1672
|
-
streams.stdout += decoders.stdout.decode();
|
|
1673
|
-
streams.stderr += decoders.stderr.decode();
|
|
1674
|
-
return { code: ran.code, ...streams };
|
|
1675
|
-
}
|
|
1676
|
-
// ../kit/src/cli.ts
|
|
1677
|
-
init_args();
|
|
1678
|
-
import { readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
|
|
1679
|
-
import { dirname as dirname3, join as join5 } from "path";
|
|
1680
|
-
import process17 from "process";
|
|
1681
|
-
|
|
1682
|
-
// ../kit/src/askpass.ts
|
|
1683
|
-
import process14 from "process";
|
|
1684
|
-
var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
|
|
1685
|
-
async function askpassClient(argv) {
|
|
1686
|
-
const socketPath = process14.env[SOCKET_VARIABLE];
|
|
1687
|
-
if (socketPath === undefined)
|
|
1688
|
-
return;
|
|
1689
|
-
const request = { prompt: argv[0] ?? "", ...process14.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
|
|
1690
|
-
const { promise, resolve } = Promise.withResolvers();
|
|
1691
|
-
let received = "";
|
|
1692
|
-
try {
|
|
1693
|
-
await Bun.connect({
|
|
1694
|
-
unix: socketPath,
|
|
1695
|
-
socket: {
|
|
1696
|
-
open: (socket) => void socket.write(`${JSON.stringify(request)}
|
|
1697
|
-
`),
|
|
1698
|
-
data: (_, chunk) => {
|
|
1699
|
-
received += chunk.toString();
|
|
1700
|
-
},
|
|
1701
|
-
close: () => resolve(received),
|
|
1702
|
-
error: () => resolve("")
|
|
1703
|
-
}
|
|
1704
|
-
});
|
|
1705
|
-
} catch {
|
|
1706
|
-
return 1;
|
|
1707
|
-
}
|
|
1708
|
-
const reply = await promise;
|
|
1709
|
-
if (reply === "")
|
|
1710
|
-
return 1;
|
|
1711
|
-
const { answer } = JSON.parse(reply);
|
|
1712
|
-
if (request.notice === true)
|
|
1713
|
-
return 0;
|
|
1714
|
-
if (answer === undefined)
|
|
1715
|
-
return 1;
|
|
1716
|
-
process14.stdout.write(`${answer}
|
|
1717
|
-
`);
|
|
1718
|
-
return 0;
|
|
1719
|
-
}
|
|
1720
|
-
|
|
1721
|
-
// ../kit/src/completions.ts
|
|
1722
|
-
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
1723
|
-
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'
|
|
3
|
+
var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};function a(e,t,o){return JSON.stringify([e??null,t??null,o])}function y(e,t){let o=a(e,t),n=i.get(o);if(!n)n=new Intl.NumberFormat(e,t),i.set(o,n);return n}var i;var init_chunk_n6z2kk96=__esm(()=>{i=new Map});function Ao(t,e,r="..."){let{suffix:n="...",includeSuffix:s=!1,wordBoundary:o=!1}=typeof r==="string"?{suffix:r}:r;if(t.length<=e)return t;let l=Math.max(0,e),c=t.substring(0,Math.max(0,s?l-n.length:l));if(o&&!Y.test(t[c.length]??" "))c=c.replace(Nt,"")||c;if(o)c=c.trimEnd();return s?(c+n).slice(0,l):c+n}var Nt,Y,be;var init_chunk_rkhsft4a=__esm(()=>{Nt=/\s+\S*$/,Y=/\s/;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))});var init_text=__esm(()=>{init_chunk_rkhsft4a()});import process2 from"process";function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process2.stdout,env=process2.env){let chosen=env.KIT_MODE;if(chosen!==void 0&&MODES.has(chosen))return chosen;if(AGENT_VARIABLES.some((name)=>isSet(env[name])))return"agent";if(stream.isTTY===!0)return"terminal";return isSet(env.CI)?"ci":"pipe"}function isInteractive(streams=process2){return streams.stdin?.isTTY===!0&&streams.stderr?.isTTY===!0}var MODES,AGENT_VARIABLES;var init_mode=__esm(()=>{MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"]});function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G2.test(e))return[0,0,0];if(e.length===3||e.length===4)return[Number.parseInt(e[0]+e[0],16),Number.parseInt(e[1]+e[1],16),Number.parseInt(e[2]+e[2],16)];if(e.length!==6&&e.length!==8)throw Error(`Invalid hex color length: ${e.length}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}function C(r,e=globalThis.process?.env??{}){if(e.FORCE_COLOR!==void 0)return h.has(e.FORCE_COLOR);if(e.NO_COLOR!==void 0||e.NODE_DISABLE_COLORS!==void 0||e.TERM==="dumb")return!1;return r?.isTTY===!0}function f(r,e=[]){let l="",n="";for(let t=0,i=e.length;t<i;t++)l+=`\x1B[${e[t][0]}m`,n=`\x1B[${e[t][1]}m${n}`;let c=(t)=>C(r.stream??globalThis.process?.stdout,r.env)?l+t+n:t,g=new Map;return new Proxy(c,{get(t,i){let a=B[i];if(Array.isArray(a)){let s=g.get(i);if(s===void 0)s=f(r,[...e,a]),g.set(i,s);return s}if(typeof a==="function")return(...s)=>{let y=`${i}:${s.join(",")}`,u=g.get(y);if(u===void 0){if(g.size>=64)g.clear();u=f(r,[...e,a(...s)]),g.set(y,u)}return u};throw Error(`Unknown style: ${String(i)}`)}})}function Fe(r={}){return f(r)}var G2,B,h,o;var init_chunk_x450vn3m=__esm(()=>{G2=/^[a-f0-9]+$/i;B={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")=>{let[l,n,c]=b(r);return[`${e==="fg"?38:48};2;${l};${n};${c}`,e==="fg"?39:49]},ansi256:(r,e="fg")=>[`${e==="fg"?38:48};5;${r}`,e==="fg"?39:49]},h=new Set(["","1","2","3","true"]);o=Fe()});var init_colors=__esm(()=>{init_chunk_x450vn3m()});import{existsSync}from"fs";import{dirname,join,resolve}from"path";import process3 from"process";function findUp(names,from=process3.cwd(),stop=()=>!1){let wanted=typeof names==="string"?[names]:names;for(let dir=resolve(from);;dir=dirname(dir)){let found=wanted.map((name)=>join(dir,name)).find((path)=>existsSync(path));if(found!==void 0)return found;if(stop(dir)||dirname(dir)===dir)return}}var init_config=__esm(()=>{init_args()});import{existsSync as existsSync2,readFileSync}from"fs";import{homedir}from"os";import{isAbsolute,join as join2}from"path";import process4 from"process";function xdgFolder(value,fallback){return value!==void 0&&isAbsolute(value)?value:fallback}function configBase(where={}){let xdg=where.xdg??(where.home===void 0?process4.env.XDG_CONFIG_HOME:void 0);return xdgFolder(xdg,join2(where.home??homedir(),".config"))}function userConfigPath(bin,where={}){return join2(configBase(where),"kaynooo-cli",`${bin}.json`)}function userConfigReadPath(bin,legacy=[],where={}){let current=userConfigPath(bin,where);if(existsSync2(current))return current;let base=configBase(where);return legacy.map((parts)=>join2(base,...parts)).find((path)=>existsSync2(path))??current}function readUserConfig(bin,where={},legacy=[]){let path=userConfigReadPath(bin,legacy,where);if(!existsSync2(path))return{};try{let parsed=Bun.JSONC.parse(readFileSync(path,"utf8"));return typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:{}}catch{return{}}}function configuredNumber(bin,key,fallback,where={},legacy=[]){let value=readUserConfig(bin,where,legacy)[key];return typeof value==="number"&&Number.isInteger(value)&&value>0?value:fallback}var init_user_config=()=>{};import{existsSync as existsSync3,readFileSync as readFileSync2,statSync}from"fs";import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process5 from"process";function toLinear(channel){let value=channel/255;return value<=0.04045?value/12.92:((value+0.055)/1.055)**2.4}function toOklab(hex){let[r,g,b]=[1,3,5].map((at)=>toLinear(Number.parseInt(hex.slice(at,at+2),16))),l=Math.cbrt(0.4122214708*r+0.5363325363*g+0.0514459929*b),m=Math.cbrt(0.2119034982*r+0.6806995451*g+0.1073969566*b),s=Math.cbrt(0.0883024619*r+0.2817188376*g+0.6299787005*b);return[0.2104542553*l+0.793617785*m-0.0040720468*s,1.9779984951*l-2.428592205*m+0.4505937099*s,0.0259040371*l+0.7827717662*m-0.808675766*s]}function fromOklab([lightness,a,b]){let l=(lightness+0.3963377774*a+0.2158037573*b)**3,m=(lightness-0.1055613458*a-0.0638541728*b)**3,s=(lightness-0.0894841775*a-1.291485548*b)**3;return`#${[4.0767416621*l-3.3077115913*m+0.2309699292*s,-1.2684380046*l+2.6097574011*m-0.3413193965*s,-0.0041960863*l-0.7034186147*m+1.707614701*s].map((channel)=>fromLinear(channel).toString(16).padStart(2,"0")).join("")}`}function gradientAt(theme,ratio){if(theme.gradient===void 0)return;let key=theme.gradient.join(),ends=ENDS.get(key);if(ends===void 0)ends=[toOklab(theme.gradient[0]),toOklab(theme.gradient[1])],ENDS.set(key,ends);let at=Math.min(1,Math.max(0,ratio)),[from,to]=ends;return fromOklab(from.map((start,index)=>start+(to[index]-start)*at))}function isColorSpec(spec){if(typeof spec==="number")return Number.isInteger(spec)&&spec>=0&&spec<=255;return typeof spec==="string"&&spec.trim()!==""&&spec.trim().split(SPACES).every((token)=>STYLES.has(token)||HEX.test(token))}function cubeLevel(channel){return CUBE.reduce((best,value,level)=>Math.abs(value-channel)<Math.abs(CUBE[best]-channel)?level:best,0)}function nearest256(hex){let rgb=[1,3,5].map((at)=>Number.parseInt(hex.slice(at,at+2),16)),levels=rgb.map(cubeLevel),cube=levels.map((level)=>CUBE[level]),grey=Math.min(23,Math.max(0,Math.round((rgb.reduce((sum,channel)=>sum+channel,0)/3-8)/10))),greyValue=8+grey*10,distance=(colour)=>colour.reduce((sum,channel,at)=>sum+(channel-rgb[at])**2,0);return distance([greyValue,greyValue,greyValue])<distance(cube)?232+grey:16+36*levels[0]+6*levels[1]+levels[2]}function hasTrueColor(env){return env.COLORTERM==="truecolor"||env.COLORTERM==="24bit"}function tinted(colors,spec,env=process5.env){if(typeof spec==="number")return colors.ansi256(spec);return spec.trim().split(SPACES).reduce((chain,token)=>{if(HEX.test(token))return hasTrueColor(env)?chain.hex(token):chain.ansi256(nearest256(token));return chain[token]??chain},colors)}function shaded(theme,colors,glyph,cells,width,env=process5.env){return Array.from({length:cells},(_,index)=>tinted(colors,gradientAt(theme,width<=1?0:index/(width-1))??theme.colors.accent,env)(glyph)).join("")}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function readThemeFile(path,warn){try{let stat=statSync(path,{throwIfNoEntry:!1});if(stat===void 0)return;if(!stat.isFile()||stat.size>MAX_FILE_BYTES){warn(`${path} is not a regular file under ${MAX_FILE_BYTES/1024} KiB, theme ignored`);return}let parsed=JSON.parse(readFileSync2(path,"utf8"));if(isRecord(parsed))return parsed;warn(`${path} is not a JSON object, theme ignored`)}catch(error){warn(`${path} does not parse (${error instanceof Error?error.message:String(error)}), theme ignored`)}return}function applyPreset(theme,name,warn,where){if(name===void 0)return;if(typeof name!=="string"||!Object.hasOwn(PRESETS,name)){warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);return}let preset=PRESETS[name];if(Object.assign(theme.colors,preset.colors),Object.assign(theme.glyphs,preset.glyphs),preset.accents!==void 0)theme.accents=[...preset.accents];if(Object.hasOwn(preset,"gradient"))theme.gradient=preset.gradient;return name}function applyFile(theme,file,where,warn){if(isRecord(file.colors))for(let[key,value]of Object.entries(file.colors))if(!Object.hasOwn(DEFAULT.colors,key))warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);else if(!isColorSpec(value))warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);else theme.colors[key]=value;if(isRecord(file.glyphs))for(let[key,value]of Object.entries(file.glyphs))if(!Object.hasOwn(DEFAULT.glyphs,key))warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);else if(typeof value!=="string"||CONTROL.test(value)||Bun.stringWidth(value)!==1)warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);else theme.glyphs[key]=value;if(Array.isArray(file.accents)&&file.accents.length>0&&file.accents.every(isColorSpec))theme.accents=[...file.accents];else if(file.accents!==void 0)warn(`${where}: accents must be a non-empty list of colours`);if(file.gradient===null)theme.gradient=void 0;else if(Array.isArray(file.gradient)&&file.gradient.length===2&&file.gradient.every((end)=>typeof end==="string"&&HEX.test(end)))theme.gradient=[file.gradient[0],file.gradient[1]];else if(file.gradient!==void 0)warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);if(isRecord(file.bins))for(let[bin,value]of Object.entries(file.bins))if(isColorSpec(value))theme.bins[bin]=value;else warn(`${where}: bin ${bin} has no valid colour`)}function endsWalk(home){return(dir)=>dir===resolve2(home)||existsSync3(join3(dir,".git"))}function warnOnce(message){if(warned.has(message))return;warned.add(message),console.error(`warning: theme ${message}`)}function isPath(chosen){return chosen.includes("/")||chosen.endsWith(".json")}function loadTheme({env=process5.env,from=process5.cwd(),home=homedir2(),warn=warnOnce}={}){let theme={colors:{...DEFAULT.colors},glyphs:{...DEFAULT.glyphs},accents:[...DEFAULT.accents],bins:Object.create(null),gradient:DEFAULT.gradient},sources=[],chosen=env.KIT_THEME??"",wanted=chosen===""?[userConfigPath("theme",{home,xdg:env.XDG_CONFIG_HOME}),findUp(join3(".kaynooo","theme.json"),from,endsWalk(home))]:[];if(isPath(chosen))wanted.push(resolve2(from,chosen));let files=[];for(let path of wanted){let file=path===void 0?void 0:readThemeFile(path,warn);if(path!==void 0&&file!==void 0)files.push({path,file})}let preset="default";if(chosen!==""&&!isPath(chosen))preset=applyPreset(theme,chosen,warn,"KIT_THEME")??preset;else{let named=files.findLast(({file})=>file.preset!==void 0);if(named!==void 0)preset=applyPreset(theme,named.file.preset,warn,named.path)??preset}for(let{path,file}of files)applyFile(theme,file,path,warn),sources.push(path);return{theme,sources,preset}}function activeTheme(){let key=`${process5.cwd()}\x00${process5.env.KIT_THEME??""}\x00${process5.env.XDG_CONFIG_HOME??""}`;if(current===void 0||key!==currentKey)current=loadTheme(),currentKey=key;return current}var fromLinear=(value)=>Math.round(255*Math.min(1,Math.max(0,value<=0.0031308?value*12.92:1.055*value**0.4166666666666667-0.055))),ENDS,DEFAULT,BRIGHT,LIGHT,MONO,ASCII,PRESETS,STYLES,HEX,CONTROL,MAX_FILE_BYTES=65536,SPACES,CUBE,warned,current,currentKey="";var init_theme=__esm(()=>{init_config();init_user_config();ENDS=new Map;DEFAULT={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"},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"},accents:["cyan","magenta","green","blue","yellow","redBright"],bins:{},gradient:["#c084fc","#67e8f9"]},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"},LIGHT={accent:"#0369a1",id:"#b45309",path:"#1d4ed8",label:"#52525b",value:"bold",ok:"#15803d",warn:"#b45309",problem:"#b91c1c",note:"#52525b",plan:"#7e22ce",passed:"#15803d",failed:"#b91c1c",running:"#0369a1",queued:"#b45309",skipped:"#52525b"},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"},ASCII={ok:"+",warn:"!",problem:"x",note:">",plan:"?",passed:"+",failed:"x",running:"*",queued:"o",skipped:"-",bar:"#",rule:"-",corner:"+",open:"*",leaf:"-",guide:"|"},PRESETS={default:{},"high-contrast":{colors:BRIGHT,accents:["cyanBright","magentaBright","greenBright","blueBright","yellowBright","redBright"],gradient:["#d8b4fe","#a5f3fc"]},light:{colors:LIGHT,accents:["#0369a1","#7e22ce","#15803d","#1d4ed8","#b45309","#b91c1c"],gradient:["#7c3aed","#0284c7"]},mono:{colors:MONO,accents:["bold"],gradient:void 0},ascii:{glyphs:ASCII}},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"]),HEX=/^#[0-9a-f]{6}$/i,CONTROL=/\p{Cc}/u,SPACES=/\s+/;CUBE=[0,95,135,175,215,255];warned=new Set});import process6 from"process";function takesControlCodes(stream,env=process6.env){return stream.isTTY===!0&&(env.NO_COLOR===void 0||env.NO_COLOR==="")&&env.NODE_DISABLE_COLORS===void 0&&env.TERM!=="dumb"&&outputMode(stream,env)==="terminal"}function paint(stream,env=process6.env){let effective=env.NO_COLOR===""?{...env,NO_COLOR:void 0}:env;return Fe({stream:{isTTY:takesControlCodes(stream,env)},env:effective})}function marked(mark,text,stream,detail,env=process6.env){let colors=paint(stream,env),head=MARK_WORDS[mark];if(takesControlCodes(stream,env)){let{theme}=activeTheme();head=tinted(colors.bold,theme.colors[mark],env)(theme.glyphs[mark])}return`${head} ${text}${detail===void 0?"":` ${colors.dim(detail)}`}`}function ok(text,detail){console.log(marked("ok",text,process6.stdout,detail))}function note(text,detail){console.log(marked("note",text,process6.stdout,detail))}function problem(text,detail){console.error(marked("problem",text,process6.stderr,detail))}function role(name,stream,env=process6.env){let colors=paint(stream,env);return takesControlCodes(stream,env)?tinted(colors,activeTheme().theme.colors[name],env):colors}function header(bin,context,stream,env=process6.env){if(!takesControlCodes(stream,env))return"";let colors=paint(stream,env),hash=[...bin].reduce((sum,char)=>sum+char.charCodeAt(0),0),{theme}=activeTheme(),spec=theme.bins[bin]??theme.accents[hash%theme.accents.length];return`${tinted(typeof spec==="string"&&spec.split(" ").includes("bold")?colors:colors.bold,spec,env)(bin)}${context===void 0?"":colors.dim(` \u203A ${context}`)}`}function printHeader(bin,context,stream=process6.stdout,env=process6.env){let line=header(bin,context,stream,env);if(line!=="")console.log(line)}var MARK_WORDS,STATUS_WORDS,STATUS_OF;var init_style=__esm(()=>{init_colors();init_mode();init_theme();MARK_WORDS={ok:"ok:",warn:"warning:",problem:"error:",note:"note:",plan:"would:"};STATUS_WORDS={passed:["passed","success","succeeded","ok"],failed:["failed","failure","error","errored"],running:["running","in_progress","started","holding"],queued:["queued","waiting","pending","created","blocked","scheduled"],skipped:["skipped","cancelled","canceled","manual"]},STATUS_OF=new Map(Object.entries(STATUS_WORDS).flatMap(([status,words])=>words.map((word)=>[word,status])))});function distance(a,b){let left=[...a],right=[...b],before=[],previous=Array.from({length:right.length+1},(_,index)=>index);for(let[i,x]of left.entries()){let current=[i+1];for(let[j,y]of right.entries()){let cost=Math.min((previous[j+1]??0)+1,(current[j]??0)+1,(previous[j]??0)+(x===y?0:1));if(i>0&&j>0&&x===right[j-1]&&left[i-1]===y)cost=Math.min(cost,(before[j-1]??0)+1);current.push(cost)}before=previous,previous=current}return previous[right.length]??0}function closest(name,names){let started=names.find((known)=>known.startsWith(name));if(started!==void 0)return started;let[best]=names.map((known)=>({known,far:distance(name,known)})).sort((a,b)=>a.far-b.far);return best!==void 0&&best.far<=(name.length<4?1:2)?best.known:void 0}function cutToWidth(line,width,suffix=""){if(Bun.stringWidth(line)<=width)return line;let suffixWidth=suffix===""?0:Bun.stringWidth(suffix),room=Math.max(0,width-suffixWidth),kept="",index=0,styled=!1,linked=!1;while(index<line.length){ESCAPE_CODE.lastIndex=index;let escape=ESCAPE_CODE.exec(line);if(escape!==null){if(kept+=escape[0],escape[0].startsWith(`${ESC}]`))linked=!0;else styled=!0;index=ESCAPE_CODE.lastIndex;continue}let char=String.fromCodePoint(line.codePointAt(index)),columns=Bun.stringWidth(char);if(columns>room)break;kept+=char,room-=columns,index+=char.length}return`${kept}${styled?RESET_STYLE:""}${linked?CLOSE_LINK:""}${suffix}`}var ESC,ESCAPE_CODE,RESET_STYLE,CLOSE_LINK;var init_text2=__esm(()=>{ESC=String.fromCharCode(27),ESCAPE_CODE=new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`,"y"),RESET_STYLE=`${ESC}[0m`,CLOSE_LINK=`${ESC}]8;;${ESC}\\`});function tt(i,{units:r="iec",dp:t=1,locale:n}={}){let e=r==="si"?1000:1024;if(Math.abs(i)<e)return`${i} B`;let s=r==="iec"?["KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"]:["kB","MB","GB","TB","PB","EB","ZB","YB"],o=-1,a=10**t;do i/=e,++o;while(Math.round(Math.abs(i)*a)/a>=e&&o<s.length-1);return`${n?y(n,{minimumFractionDigits:t,maximumFractionDigits:t}).format(i):i.toFixed(t)} ${s[o]}`}var init_chunk_knqbxp56=__esm(()=>{init_chunk_n6z2kk96()});var init_format=__esm(()=>{init_chunk_knqbxp56()});import process7 from"process";function formatSeconds(total){let rest=Math.max(0,Math.round(total)),amounts=UNITS.map(([unit,size])=>{let amount=Math.floor(rest/size);return rest-=amount*size,`${amount}${unit}`}),first=amounts.findIndex((amount)=>!amount.startsWith("0"));if(first===-1)return"0s";let next=amounts[first+1];return next===void 0||next.startsWith("0")?amounts[first]??"0s":`${amounts[first]} ${next}`}function formatDuration(ms){return ms<60000?`${(Math.max(0,ms)/1000).toFixed(1)}s`:formatSeconds(ms/1000)}function formatElapsed(ms){return formatSeconds(Math.floor(Math.max(0,ms)/1000))}function upTo(text,separator){let end=text.indexOf(separator);return end===-1?text:text.slice(0,end)}function formatAge(date,now=Date.now()){let at=typeof date==="number"?date:Date.parse(date);if(Number.isNaN(at))return"-";let seconds=(now-at)/1000;return seconds<60?"just now":`${upTo(formatSeconds(seconds)," ")} ago`}function truncate(text,width){return Ao(text,width,{suffix:"\u2026",includeSuffix:!0})}function textWidth(text){return Bun.stringWidth(text)}function table(rows,{cellWidth,header=!1,align=[],fit,stream=process7.stdout,env=process7.env}={}){let cells=cellWidth===void 0?rows:rows.map((row)=>row.map((cell)=>truncate(cell.replaceAll(LINE_BREAKS," "),cellWidth)));if(outputMode(stream,env)==="agent")return cells.map((row)=>row.map((cell)=>Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g," ")).join("\t")).join(`
|
|
4
|
+
`);let widths=[];for(let row of cells)for(let[index,cell]of row.entries())widths[index]=Math.max(widths[index]??0,textWidth(cell));let shown=fit===void 0?cells:narrow(cells,widths,fit),colors=paint(stream,env),lines=shown.map((row)=>row.map((cell,index)=>{let width=widths[index]??0,gap=" ".repeat(Math.max(0,width-textWidth(cell)));if(align[index]==="right")return`${gap}${cell}`;return index===row.length-1?cell:`${cell}${gap}`}).join(" ").trimEnd()),rule=header&&takesControlCodes(stream,env)&&lines.length>1?[colors.dim(activeTheme().theme.glyphs.rule.repeat(Math.max(...lines.map(textWidth))))]:[];return lines.flatMap((line,index)=>header&&index===0?[colors.bold(line),...rule]:[line]).join(`
|
|
5
|
+
`)}function narrow(rows,widths,limit){let used=()=>widths.reduce((sum,width)=>sum+width,0)+2*Math.max(0,widths.length-1),floor=8;while(used()>limit){let widest=-1;for(let[index,width]of widths.entries())if(width>8&&width>(widths[widest]??0))widest=index;if(widest===-1)break;widths[widest]=Math.max(8,(widths[widest]??0)-(used()-limit))}return rows.map((row)=>row.map((cell,index)=>textWidth(cell)>(widths[index]??0)?cutToWidth(cell,widths[index]??0,"\u2026"):cell))}function jsonText(value,replacer,{stream=process7.stdout,env=process7.env}={}){return JSON.stringify(value,replacer,outputMode(stream,env)==="agent"?void 0:2)}function printJson(value){console.log(jsonText(value))}var UNITS,LINE_BREAKS;var init_format2=__esm(()=>{init_text();init_mode();init_style();init_text2();init_theme();init_format();UNITS=[["d",86400],["h",3600],["m",60],["s",1]];LINE_BREAKS=/\s*\n\s*/g});import process8 from"process";function usageLine(usage,colors=paint(process8.stdout),{summary:withSummary=!0}={}){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
6
|
+
`),blank=lines.indexOf(""),synopses=blank===-1?lines:lines.slice(0,blank),details=blank===-1?[]:lines.slice(blank+1),colon=synopses[0].indexOf(": "),inline=synopses[0].slice(colon+2),summary=colon===-1?details.shift():`${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;if(colon!==-1)synopses[0]=synopses[0].slice(0,colon);let head=`${colors.bold("Usage:")} ${synopses.map((line)=>line.replaceAll(OPTIONAL,(part)=>colors.dim(part))).join(`
|
|
7
|
+
`)}`,lead=summary===void 0||!withSummary?[]:["",colors.bold(prose(summary,colors))],rest=details.length===0?[]:["",...details.map((line)=>prose(line,colors))];return[head,...lead,...rest].join(`
|
|
8
|
+
`)}function prose(line,colors){if(colors.cyan("x")==="x")return line;return line.replaceAll(PROSE_MARKS,(match,code,flag)=>code===void 0?colors.cyan(flag??match):colors.bold(code))}function helpText(usage,options,colors=paint(process8.stdout),{examples=[],exits=[],bin,columns}={}){let{summary}=description(usage);return[...bin===void 0?[usageLine(usage,colors)]:[`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary===""?"":` ${summary}`}`,"",usageLine(usage,colors,{summary:!1})],"",colors.bold("Options:"),...optionRows(options,colors,columns),...exitRows(exits,colors),...exampleRows(examples,colors)].join(`
|
|
9
|
+
`)}function exitRows(exits,colors=paint(process8.stdout)){if(exits.length===0)return[];return["",`${colors.bold("Exit codes:")} ${exits.map(([code,meaning])=>`${colors.cyan(String(code))} ${meaning}`).join(", ")}`]}function wantsHelpJson(env=process8.env){return env.KIT_HELP==="json"}function description(usage,{examples=[],replaces,exits}={},options){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
10
|
+
`),first=lines[0],colon=first.indexOf(": "),prose=lines[lines.indexOf("")+1]??"",fallback=lines.includes("")?`${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP,""):"";return{synopsis:colon===-1?first:first.slice(0,colon),summary:colon===-1?fallback:first.slice(colon+2),...replaces===void 0?{}:{replaces},examples:examples.map((example)=>typeof example==="string"?{line:example}:{line:example[0],note:example[1]}),...exits===void 0?{}:{exits:exits.map(([code,meaning])=>({code,meaning}))},...options===void 0?{}:{options:Object.entries(options).map(([name,{short,description}])=>({name,...short===void 0?{}:{short},...description===void 0?{}:{description}}))}}}function exampleRows(examples,colors=paint(process8.stdout)){if(examples.length===0||outputMode()==="agent")return[];return["",colors.bold("Examples:"),...examples.map((example)=>typeof example==="string"?` ${example}`:` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)]}function wrapText(text,limit){if(text.length<=limit)return[text];let lines=[],current="";for(let word of text.split(" "))if(current==="")current=word;else if(current.length+1+word.length<=limit)current=`${current} ${word}`;else lines.push(current),current=word;if(current!=="")lines.push(current);return lines}function optionRows(options,colors=paint(process8.stdout),columns){let rows=Object.entries(options).map(([name,option])=>{let short=option.short===void 0?" ":`${colors.cyan(`-${option.short}`)}, `,choices=option.choices?.join("|"),inline=choices!==void 0&&choices.length<=MAX_INLINE_CHOICES,named=inline?`<${choices}>`:"<value>",placeholder=option.optional===void 0?named:`[${named}]`,value=option.type==="string"?` ${colors.dim(placeholder)}`:"",described=choices===void 0||inline?option.description??"":[option.description,`one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");return{flag:`${short}${colors.cyan(`--${name}`)}${value}`,width:`-x, --${name}`.length+(option.type==="string"?placeholder.length+1:0),description:described}}),width=Math.max(0,...rows.map((row)=>row.width)),indent=2+width+2,room=columns!==void 0&&columns-indent>=20?columns-indent:void 0;return rows.flatMap((row)=>{if(row.description==="")return[` ${row.flag}`];let wrapped=room===void 0?[row.description]:wrapText(row.description,room),[first="",...rest]=wrapped;return[` ${row.flag}${" ".repeat(width-row.width)} ${colors.dim(first)}`,...rest.map((line)=>`${" ".repeat(indent)}${colors.dim(line)}`)]})}var OPTIONAL,USAGE_PREFIX,FULL_STOP,PROSE_MARKS,MAX_INLINE_CHOICES=24;var init_help=__esm(()=>{init_mode();init_style();OPTIONAL=/(?<!\x1B)\[[^\]]+\]/g,USAGE_PREFIX=/^usage:\s*/i,FULL_STOP=/\.$/,PROSE_MARKS=/`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi});function durationMs(text,unit){if(BARE_DURATION.test(text))return Number(text)*UNIT_MS[unit];if(!DURATION.test(text))return 0;let ms=0;for(let[,amount,part]of text.matchAll(DURATION_PART))ms+=Number(amount)*UNIT_MS[part];return ms}function duration(value,name,fallback,unit="s"){if(value===void 0)return fallback;let ms=durationMs(value.trim(),unit);if(ms<1)badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);return ms}var BARE_DURATION,DURATION,DURATION_PART,UNIT_MS;var init_input=__esm(()=>{init_args();BARE_DURATION=/^\d+(?:\.\d+)?$/,DURATION=/^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/,DURATION_PART=/(\d+(?:\.\d+)?)(ms|min|[smhd])/g,UNIT_MS={ms:1,s:1000,m:60000,min:60000,h:3600000,d:86400000}});import process9 from"process";import{parseArgs}from"util";function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}function badUsage(message){throw new UsageError(message)}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}function applyOutput(color,plain,env=process9.env){let when=plain===!0?"never":color??"auto";if(when==="auto")return;if(when!=="always"&&when!=="never")badUsage(`--color takes auto, always or never, not ${when}`);if(when==="always")env.FORCE_COLOR="1",delete env.NO_COLOR;else env.NO_COLOR="1",delete env.FORCE_COLOR}function parse(args,usage,options,settings={}){let output=Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name])=>!(name in options))),all={...options,...output,help:{type:"boolean",short:"h",description:"show this help"}},listing=listed(all,settings.allowNegative===!0);if(completion.active)throw new Completing(listing,settings.positionals,settings.candidates);let{own,rest}=settings.trailing===!0?splitTrailing(args,all,settings.positionals?.length??0):splitRest(args,settings.rest===!0),parsed;try{parsed=parseArgs({args:joinDashValues(withBare(withAliases(own,all),all),all),options:all,allowPositionals:!0,allowNegative:settings.allowNegative===!0,strict:!0})}catch(error){let message=parseError(error);throw new UsageError(message,nearestOption(message,all,settings.allowNegative===!0))}let values=parsed.values;if(applyOutput("color"in output?values.color:void 0,"plain"in output?values.plain:void 0),values.help===!0){let columns=takesControlCodes(process9.stdout)?process9.stdout.columns:void 0;throw console.log(wantsHelpJson()?JSON.stringify(description(usage,settings,listing)):helpText(usage,listing,void 0,{...settings,bin:heading.bin,columns})),new HelpShown}if(checkChoices(parsed.values,all),checkConflicts(parsed.values,all),settings.positionals!==void 0)checkPositionals(parsed.positionals,settings.positionals);return{...parsed,values:parsed.values,positionals:parsed.positionals,rest}}function splitRest(args,passes){let separator=passes?args.indexOf("--"):-1;return{own:separator===-1?args:args.slice(0,separator),rest:separator===-1?void 0:args.slice(separator+1)}}function splitTrailing(args,options,count){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),seen=0;if(count===0)return{own:args,rest:void 0};for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")break;if(word.startsWith("-")){if(takesValue(word))at++;continue}if(seen++,seen===count)return{own:args.slice(0,at+1),rest:args.slice(at+1)}}return{own:args,rest:void 0}}function listed(options,allowNegative){if(!allowNegative)return options;return Object.fromEntries(Object.entries(options).flatMap(([name,option])=>{if(option.type!=="boolean"||option.negative===void 0)return[[name,option]];return[...option.description===void 0?[]:[[name,option]],[`no-${name}`,{type:"boolean",description:option.negative}]]}))}function withAliases(args,options){let named=new Map(Object.entries(options).flatMap(([name,{aliases=[]}])=>aliases.map((alias)=>[`--${alias}`,`--${name}`])));if(named.size===0)return args;let separator=args.indexOf("--");return[...(separator===-1?args:args.slice(0,separator)).map((arg)=>{let at=arg.indexOf("="),current=named.get(at===-1?arg:arg.slice(0,at));return current===void 0?arg:`${current}${at===-1?"":arg.slice(at)}`}),...separator===-1?[]:args.slice(separator)]}function withBare(args,options){let bare=new Map(Object.entries(options).flatMap(([name,{short,optional}])=>optional===void 0?[]:[[`--${name}`,optional],...short===void 0?[]:[[`-${short}`,optional]]]));if(bare.size===0)return args;let separator=args.indexOf("--"),own=separator===-1?args:args.slice(0,separator);return[...own.flatMap((arg,index)=>{let optional=bare.get(arg),next=own[index+1],value=next!==void 0&&(optional?.accepts===void 0?!next.startsWith("-"):optional.accepts.test(next));return optional===void 0||value?[arg]:[arg,optional.bare]}),...separator===-1?[]:args.slice(separator)]}function checkConflicts(values,options){let given=(name)=>values[name]!==void 0&&values[name]!==!1;for(let[name,{conflicts=[]}]of Object.entries(options)){let other=given(name)?conflicts.find(given):void 0;if(other!==void 0)badUsage(`--${name} cannot be used with --${other}`)}}function checkChoices(values,options){for(let[name,option]of Object.entries(options)){if(option.choices===void 0)continue;let given=values[name];for(let value of Array.isArray(given)?given:[given])if(typeof value==="string")oneOf(value,name,option.choices)}}function oneOf(value,name,choices){if(!choices.includes(value))badUsage(`${name.startsWith("<")?name:`--${name}`} takes one of ${choices.join(", ")}, not ${value}`);return value}function checkPositionals(given,names){let variadic=names.at(-1)?.replace("]","").endsWith("...")===!0,required=names.filter((name)=>!name.startsWith("[")).length;if(given.length<required)badUsage(`missing ${names[given.length]}`);if(!variadic&&given.length>names.length)badUsage(`unexpected argument ${given[names.length]}`)}function joinDashValues(args,options){let longOf=new Map(Object.entries(options).flatMap(([name,option])=>option.short===void 0?[[`--${name}`,name]]:[[`--${name}`,name],[`-${option.short}`,name]])),isOption=(arg)=>arg==="--"||longOf.has(arg.includes("=")?arg.slice(0,arg.indexOf("=")):arg),joined=[];for(let i=0;i<args.length;i++){let arg=args[i]??"";if(arg==="--")return[...joined,...args.slice(i)];let name=longOf.get(arg),next=args[i+1];if(name!==void 0&&options[name]?.type==="string"&&next!==void 0&&next.startsWith("-")&&next!=="-"&&!isOption(next))joined.push(`--${name}=${next}`),i++;else joined.push(arg)}return joined}function parseError(error){let message=upTo(error instanceof Error?error.message:String(error),". ");return`${message.charAt(0).toLowerCase()}${message.slice(1)}`}function nearestOption(message,options,allowNegative){let typed=UNKNOWN_OPTION.exec(message)?.[1];if(typed===void 0)return;let word=typed.replace(DASHES,"");if(word.length<2&&!typed.startsWith("--"))return;let known=Object.entries(options).flatMap(([name,option])=>[...option.short===void 0?[]:[`-${option.short}`],`--${name}`,...allowNegative&&option.type==="boolean"?[`--no-${name}`]:[]]),meant=closest(word,known.map((flag)=>flag.replace(DASHES,"")));return meant===void 0?void 0:`did you mean ${known.find((flag)=>flag.replace(DASHES,"")===meant)}?`}var DASHES,EXIT,Exit,UsageError,HelpShown,completion,heading,OUTPUT_OPTIONS,UNKNOWN_OPTION;var init_args=__esm(()=>{init_format2();init_help();init_style();init_text2();init_help();init_input();DASHES=/^-+/;EXIT=Symbol.for("@kaynooo/cli-kit/Exit");Exit=class Exit extends Error{code;hint;[EXIT]=!0;constructor(message,code,hint){super(message);this.code=code;this.hint=hint}static[Symbol.hasInstance](value){if(this!==Exit)return Function.prototype[Symbol.hasInstance].call(this,value);return typeof value==="object"&&value!==null&&value[EXIT]===!0}};UsageError=class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}};HelpShown=class HelpShown extends Exit{constructor(){super("help shown",0)}};completion={active:!1},heading={bin:void 0},OUTPUT_OPTIONS={color:{type:"string",choices:["auto","always","never"],description:"auto (the default) colours on a terminal alone"},plain:{type:"boolean",description:"plain text, no colour or spinner: --color never"}};UNKNOWN_OPTION=/^unknown option '(-[^']+)'/});var init_folders=__esm(()=>{init_user_config()});var init_answers=__esm(()=>{init_folders()});import process24 from"process";function stopJob(){process24.kill(0,"SIGTSTP")}var init_job=()=>{};function isEditKey(key){return EDIT_KEYS.has(key)}var EDIT_KEYS;var init_line=__esm(()=>{EDIT_KEYS=new Set(["left","right","wordleft","wordright","linestart","lineend","erase","delete","word","killword","killnext","clear","killend","yank"])});var NONE;var init_score=__esm(()=>{NONE=Number.NEGATIVE_INFINITY});function repeat(value,count){return Array.from({length:count}).fill(value)}function parseKeys(input,paste={active:!1},ctrls=[]){let codes=new Map(ctrls.map((name)=>[String.fromCharCode(name.codePointAt(name.length-1)-96),name]));return(input.match(KEY_SEQUENCES)??[]).flatMap((sequence)=>{let wheel=MOUSE.exec(sequence)?.[1];if(wheel!==void 0)return repeat(wheel==="64"?"up":"down",wheel==="64"||wheel==="65"?WHEEL_LINES:0);let named=codes.get(sequence),key=named===void 0?KEYS[sequence]:{ctrl:named};if(sequence===PASTE_START||sequence===PASTE_END)return paste.active=sequence===PASTE_START,[];if(paste.active&&(sequence==="\r"||sequence===`
|
|
11
|
+
`))return[];if(key!==void 0)return[key];return IS_CONTROL.test(sequence)||sequence.startsWith("\x1B")?[]:[{text:sequence}]})}var IS_CONTROL,PASTE_START="\x1B[200~",PASTE_END="\x1B[201~",KEY_SEQUENCES,MOUSE,WHEEL_LINES=3,KEYS;var init_state=__esm(()=>{init_text2();init_line();init_score();IS_CONTROL=/[\x00-\x1F\x7F-\x9F]/,KEY_SEQUENCES=/\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu,MOUSE=/^\x1B\[<(\d+);\d+;\d+[a-z]$/i,KEYS={"\x1B[A":"up","\x1BOA":"up","\x10":"up","\x1B[B":"down","\x1BOB":"down","\x0E":"down","\x1B[5~":"pageup","\x1B[6~":"pagedown","\x1B[H":"home","\x1B[1~":"home","\x1BOH":"home","\x1B[F":"end","\x1B[4~":"end","\x1BOF":"end","\r":"enter","\n":"enter","\x03":"cancel","\x1B":"cancel","\x1B[D":"left","\x1BOD":"left","\x1B[C":"right","\x1BOC":"right","\x1B[1;5D":"wordleft","\x1B[1;3D":"wordleft","\x1Bb":"wordleft","\x1B[1;5C":"wordright","\x1B[1;3C":"wordright","\x1Bf":"wordright","\x01":"linestart","\x05":"lineend","\x7F":"erase","\x1B[3~":"delete","\b":"killword","\x1B\x7F":"killword","\x1B[3;5~":"killnext","\x1Bd":"killnext","\x15":"clear","\v":"killend","\x17":"word","\x19":"yank","\x1A":"suspend","\t":"tab","\x1F":"help","\x1BOP":"help","\x1B[11~":"help"}});function overwrite(lines,columns){return lines.map((line)=>textWidth(line)%columns===0?`\x1B[2K${line}`:`${line}\x1B[K`).join(`
|
|
12
|
+
`)}function rowsTaken(lines,columns){return lines.reduce((rows,line)=>rows+Math.max(1,Math.ceil(textWidth(line)/columns)),0)}var SYNC_START="\x1B[?2026h",SYNC_END="\x1B[?2026l";var init_redraw=__esm(()=>{init_format2()});import process25 from"process";function readKeys(input,paste={active:!1}){return parseKeys(input,paste).filter((key)=>typeof key==="object"?"text"in key:PROMPT_KEYS.has(key)||isEditKey(key))}async function confirm(question,{default:fallback,...settings}={}){let answered=fallback,choices={true:"Y/n",false:"y/N",undefined:"y/n"}[String(fallback)];return await ask(question,settings,(colors,state)=>[state==="asking"?asking(colors,question,"",choices):answer(colors,question,state,answered?"yes":"no")],(key)=>{if(key==="cancel")return"cancel";if(key==="enter")return answered===void 0?void 0:"enter";let letter=typeof key==="object"?key.text.toLowerCase():"";if(letter!=="y"&&letter!=="n")return;return answered=letter==="y","enter"})?answered:void 0}function asking(colors,question,typed,keys){return`${colors.cyan("?")} ${question} ${typed===""?colors.dim(`(${keys})`):typed}`}function answer(colors,question,state,picked){return state==="enter"?`${colors.green("\u2713")} ${question} ${colors.cyan(picked)}`:`${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`}async function ask(question,{hint,terminal=process25},render,press){let{stdin,stderr}=terminal;if(!isInteractive(terminal))fail(`cannot ask "${question}" off a terminal`,2,hint);let colors=paint(stderr),current="asking",outcome,columns=()=>stderr.columns||80,draw=(state,last=!1)=>{let frame=render(colors,state,{columns:columns(),rows:stderr.rows||24}),rows=rowsTaken(frame,columns());stderr.write(`${SYNC_START}\r${overwrite(frame,columns())}\x1B[0J${last||rows<2?"":`\x1B[${rows-1}A`}${last?"":"\r"}${SYNC_END}`),current=state},redraw=()=>draw(current),paste={active:!1},stop=terminal.stop??(terminal===process25?stopJob:void 0),suspend=()=>{if(stop===void 0)return;stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l"),stdin.setRawMode(!1),stop(),stdin.setRawMode(!0),stderr.write("\x1B[?25l\x1B[?2004h")};try{return stderr.on?.("resize",redraw),stdin.setRawMode(!0),stdin.resume(),stderr.write("\x1B[?25l\x1B[?2004h"),draw("asking"),await new Promise((resolve)=>{function onData(data){for(let key of readKeys(data.toString(),paste)){if(key==="suspend"){suspend();continue}let pressed=press(key);if(pressed!==void 0){settle(pressed);return}}draw("asking")}function onEnd(){settle("cancel")}function settle(settled){outcome=settled,stdin.off("data",onData),stdin.off("end",onEnd),resolve(settled==="enter")}stdin.on("data",onData),stdin.on("end",onEnd)})}finally{stderr.off?.("resize",redraw),draw(outcome??"cancel",!0),stderr.write(`
|
|
13
|
+
\x1B[?25h\x1B[?2004l`),stdin.setRawMode(!1),stdin.pause()}}var PROMPT_KEYS;var init_prompt=__esm(()=>{init_answers();init_args();init_format2();init_job();init_mode();init_line();init_state();init_redraw();init_style();PROMPT_KEYS=new Set(["up","down","pageup","pagedown","home","end","enter","cancel","suspend","tab"])});import process26 from"process";var SEVERITIES=["low","moderate","high","critical"];function severityRank(severity){return SEVERITIES.indexOf(severity)}function isIgnored(advisory,ignore){return ignore.includes(advisory.ghsa??"")||ignore.includes(String(advisory.id))}init_args();import{readFileSync as readFileSync3,realpathSync}from"fs";import{resolve as resolve3}from"path";import process10 from"process";function commandLine(){try{return readFileSync3("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve3(word))}catch{return}}function scriptArgs(argv=process10.argv.slice(2),cmdline=commandLine(),script=process10.argv[1]){let target=script===void 0?void 0:realPath(script)??script,at=cmdline===void 0||target===void 0?-1:cmdline.findIndex((word,index)=>index>0&&(resolve3(word)===script||realPath(word)===target)),after=at===-1?[]:cmdline.slice(at+1);return after[0]==="--"&&after.length===argv.length+1&&argv.every((word,index)=>word===after[index+1])?after:argv}init_format2();init_mode();init_style();init_theme();init_args();init_format2();init_format2();import process12 from"process";import{readFileSync as readFileSync4}from"fs";import{constants}from"os";import process11 from"process";var KILL_GRACE_MS=2000,SIGNALS=["SIGINT","SIGTERM","SIGHUP"],GROUP_SIGNALS=new Set(["SIGINT","SIGHUP"]);function exitCodeOf(code,signal){if(code!==null)return code;if(typeof signal==="number")return 128+signal;return signal===null?129:128+constants.signals[signal]}function groupsOf(pid){try{let stat=readFileSync4(`/proc/${pid}/stat`,"utf8"),fields=stat.slice(stat.lastIndexOf(")")+2).split(" ");return{group:Number(fields[2]),foreground:Number(fields[5])}}catch{return}}function heardTheTerminal(child){if(child.pid===void 0)return!1;let own=groupsOf("self");return own!==void 0&&own.group===own.foreground&&groupsOf(child.pid)?.group===own.group}function holdSignals(cleanup){let received,child,held={get signal(){return received},forward:(to)=>{child=to},release:()=>{for(let signal of SIGNALS)process11.off(signal,onSignal)}};function onSignal(signal){if(received=signal,child!==void 0){if(!GROUP_SIGNALS.has(signal)||!heardTheTerminal(child))child.kill(signal);return}if(cleanup===void 0)return;held.release(),cleanup(signal),process11.kill(process11.pid,signal)}for(let signal of SIGNALS)process11.on(signal,onSignal);return held}async function runCommand(argv,{cwd,env,stdin="ignore",input,timeoutMs,signal,maxBytes=1/0,onChunk,onStart}={}){let chunks=[],grouped=timeoutMs!==void 0||signal!==void 0||onStart!==void 0||onChunk!==void 0,proc=Bun.spawn(argv,{...cwd===void 0?{}:{cwd},...env===void 0?{}:{env},stdin:input===void 0?stdin:new TextEncoder().encode(input),stdout:"pipe",stderr:"pipe",...grouped?{detached:!0}:{}}),state={kept:0,truncated:!1,timedOut:!1,failure:void 0,done:!1},timers=[],killGroup=(killing)=>{if(state.done)return;try{if(grouped)process11.kill(-proc.pid,killing);else proc.kill(killing)}catch{}},stop=()=>{killGroup("SIGTERM"),timers.push(setTimeout(killGroup,KILL_GRACE_MS,"SIGKILL"))},onAbort=()=>stop();if(timeoutMs!==void 0)timers.push(setTimeout(()=>{state.timedOut=!0,stop()},timeoutMs));if(signal?.aborted===!0)onAbort();else signal?.addEventListener("abort",onAbort,{once:!0});onStart?.({kill:(killing)=>killGroup(killing)});let drain=async(stream,name)=>{for await(let data of stream){if(state.failure!==void 0)continue;try{onChunk?.({stream:name,data})}catch(error){state.failure=error,stop();continue}if(state.truncated)continue;let kept=data;if(state.kept+data.length>maxBytes){let cut=maxBytes-state.kept;while(cut>0&&((data[cut]??0)&192)===128)cut--;kept=data.subarray(0,cut),state.truncated=!0}if(state.kept+=kept.length,kept.length>0)chunks.push({stream:name,data:kept})}};try{await Promise.all([drain(proc.stdout,"stdout"),drain(proc.stderr,"stderr")]),await proc.exited}finally{state.done=!0;for(let timer of timers)clearTimeout(timer);signal?.removeEventListener("abort",onAbort)}if(state.failure!==void 0)throw state.failure;let joined=()=>Buffer.concat(chunks.map(({data})=>data)),output,text,stdout;return{code:exitCodeOf(proc.exitCode,proc.signalCode),chunks,timedOut:state.timedOut,truncated:state.truncated,get output(){return output??=joined()},get text(){return text??=(output??=joined()).toString()},get stdout(){return stdout??=Buffer.concat(chunks.filter((chunk)=>chunk.stream==="stdout").map((chunk)=>chunk.data)).toString()}}}init_style();init_text2();init_theme();var FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],FRAME_MS=200,BAR_WIDTH=20,CLEAR_BELOW="\r\x1B[J",CTRL_C=3,CONSOLE_METHODS=["log","info","warn","error","debug","dir","dirxml","table","trace","group","groupCollapsed","count","timeEnd","timeLog","assert"];function liveRegion(render,stream=process12.stderr,env=process12.env){if(!takesControlCodes(stream,env))return{redraw:()=>{return},print:(text)=>void stream.write(`${text}
|
|
14
|
+
`),stop:()=>{return},pause:()=>()=>{return}};let write=stream.write.bind(stream),frame=0,drawn=!1,paused=!1,stopped=!1,columns=()=>{let now=stream.getWindowSize?.()[0]??stream.columns;return now===void 0||now===0?80:now},clear=()=>{if(drawn)write(CLEAR_BELOW);drawn=!1},draw=()=>{if(paused)return;let width=columns()-1,height=stream.rows===void 0||stream.rows===0?24:stream.rows,lines=render(FRAMES[frame++%FRAMES.length]).slice(0,Math.max(1,height-1)).map((line)=>cutToWidth(line,width));if(lines.length===0){clear();return}write(`${CLEAR_BELOW}${lines.join(`
|
|
15
|
+
`)}${lines.length>1?`\x1B[${lines.length-1}A`:""}\r`),drawn=!0},timer=setInterval(draw,FRAME_MS);stream.on?.("resize",draw);let restore=interceptOutput(clear),release=swallowInput(),onExit=()=>{clear(),release()},signals=holdSignals(stop);function stop(){stopped=!0,clearInterval(timer),stream.off?.("resize",draw),clear(),restore(),release(),process12.off("exit",onExit),signals.release()}function pause(){if(paused||stopped)return()=>{return};return paused=!0,clearInterval(timer),stream.off?.("resize",draw),clear(),restore(),release(),()=>{if(!paused||stopped)return;paused=!1,timer=setInterval(draw,FRAME_MS),timer.unref(),stream.on?.("resize",draw),restore=interceptOutput(clear),release=swallowInput(),draw()}}return timer.unref(),process12.on("exit",onExit),{redraw:draw,print:(text)=>{clear(),write(`${text}
|
|
16
|
+
`),draw()},stop,pause}}function progressLine(stream=process12.stderr,env=process12.env){let colors=paint(stream,env),write=stream.write.bind(stream),begun=performance.now(),started=begun,current,region=liveRegion((spinner)=>current===void 0?[]:[tintedParts(progressParts(current,spinner,performance.now()-started),colors)],stream,env),end=(line)=>{region.stop(),write(`${line}
|
|
17
|
+
`)};return{update:(progress)=>{let step=current?.step;if(current=progress,progress.step!==step)started=performance.now(),region.redraw()},stop:region.stop,pause:region.pause,done:(text)=>end(marked("ok",text,stream,formatDuration(performance.now()-begun),env)),failed:(text)=>end(marked("problem",text,stream,void 0,env))}}function progressParts({step,done,total,unit},spinner,ms){let{theme}=activeTheme(),parts=[{text:spinner,tint:(colors)=>tinted(colors,theme.colors.accent)},{text:` ${step}`,tint:()=>plain}];if(total!==void 0&&total>0){let counted=Math.min(done??0,total),filled=Math.round(counted/total*BAR_WIDTH);parts.push({text:" ",tint:()=>plain},{text:theme.glyphs.bar.repeat(filled),tint:(colors)=>()=>shaded(theme,colors,theme.glyphs.bar,filled,BAR_WIDTH)},{text:theme.glyphs.bar.repeat(BAR_WIDTH-filled),tint:(colors)=>colors.dim},{text:` ${counted}/${total}${unit===void 0?"":` ${unit}`}`,tint:(colors)=>colors.dim})}return parts.push({text:` ${formatElapsed(ms)}`,tint:(colors)=>colors.dim}),parts}function plain(text){return text}function tintedParts(parts,colors){return parts.map(({text,tint})=>tint(colors)(text)).join("")}function swallowInput(){let input=process12.stdin;if(!input.isTTY)return()=>{return};let onData=(data)=>{if(data.includes(CTRL_C))process12.kill(process12.pid,"SIGINT")};input.setRawMode(!0),input.on("data",onData),input.resume();let released=!1;return()=>{if(released)return;released=!0,input.off("data",onData),input.pause(),input.setRawMode(!1)}}function interceptOutput(clear){let wrapped=[...CONSOLE_METHODS.map((name)=>[console,name]),[process12.stdout,"write"],[process12.stderr,"write"]].map(([target,name])=>{let original=Reflect.get(target,name),wrapper=(...args)=>(clear(),original.apply(target,args));return Reflect.set(target,name,wrapper),{target,name,original,wrapper}});return()=>{for(let{target,name,original,wrapper}of wrapped)if(Reflect.get(target,name)===wrapper)Reflect.set(target,name,original)}}init_style();init_format2();import process13 from"process";function cwdGone(){try{return process13.cwd(),!1}catch{return!0}}class SpawnError extends Error{missing;constructor(message,missing){super(message);this.missing=missing}}function spawnFailure(command,error){let gone=cwdGone(),missing=!gone&&error?.code==="ENOENT";return new SpawnError(`${command}: ${error instanceof Error?error.message:String(error)}${gone?" (the working directory was removed)":""}`,missing)}async function runTool(label,argv,{timeoutMs,cwd,onStart,env}={}){let ran;try{ran=await runCommand(argv,{env:{...process13.env,...env},...timeoutMs===void 0?{}:{timeoutMs},...cwd===void 0?{}:{cwd},...onStart===void 0?{}:{onStart}})}catch(error){throw spawnFailure(label,error)}if(ran.timedOut)throw Error(`${label}: no answer in ${formatDuration(timeoutMs??0)}`);let decoders={stdout:new TextDecoder,stderr:new TextDecoder},streams={stdout:"",stderr:""};for(let{stream,data}of ran.chunks)streams[stream]+=decoders[stream].decode(data,{stream:!0});return streams.stdout+=decoders.stdout.decode(),streams.stderr+=decoders.stderr.decode(),{code:ran.code,...streams}}init_args();import{readFileSync as readFileSync6,realpathSync as realpathSync2}from"fs";import{dirname as dirname3,join as join5}from"path";import process17 from"process";import process14 from"process";var SOCKET_VARIABLE="KAYNOOO_ASKPASS_SOCKET";async function askpassClient(argv){let socketPath=process14.env[SOCKET_VARIABLE];if(socketPath===void 0)return;let request={prompt:argv[0]??"",...process14.env.SSH_ASKPASS_PROMPT==="none"?{notice:!0}:{}},{promise,resolve}=Promise.withResolvers(),received="";try{await Bun.connect({unix:socketPath,socket:{open:(socket)=>void socket.write(`${JSON.stringify(request)}
|
|
18
|
+
`),data:(_,chunk)=>{received+=chunk.toString()},close:()=>resolve(received),error:()=>resolve("")}})}catch{return 1}let reply=await promise;if(reply==="")return 1;let{answer}=JSON.parse(reply);if(request.notice===!0)return 0;if(answer===void 0)return 1;return process14.stdout.write(`${answer}
|
|
19
|
+
`),0}init_args();var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
|
|
20
|
+
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'
|
|
1724
21
|
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
1725
22
|
set -l current (commandline -ct)
|
|
1726
23
|
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
@@ -1730,8 +27,10 @@ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_
|
|
|
1730
27
|
echo $line
|
|
1731
28
|
end
|
|
1732
29
|
end
|
|
1733
|
-
end
|
|
1734
|
-
|
|
30
|
+
end
|
|
31
|
+
${bins.map((bin)=>`complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
32
|
+
`).join("")}`;if(shell==="bash")return`${header}
|
|
33
|
+
__kaynooo_cli_complete() {
|
|
1735
34
|
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
1736
35
|
local -a lines
|
|
1737
36
|
COMPREPLY=()
|
|
@@ -1744,8 +43,10 @@ var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
|
1744
43
|
fi
|
|
1745
44
|
done
|
|
1746
45
|
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
1747
|
-
}
|
|
1748
|
-
|
|
46
|
+
}
|
|
47
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
48
|
+
`;return`${header}
|
|
49
|
+
__kaynooo_cli_complete() {
|
|
1749
50
|
local line
|
|
1750
51
|
local -a described plain
|
|
1751
52
|
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
@@ -1760,1771 +61,42 @@ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
|
1760
61
|
(( \${#described} )) && _describe -V value described
|
|
1761
62
|
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
1762
63
|
return 0
|
|
1763
|
-
}`;
|
|
1764
|
-
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
1765
|
-
if (shell === "fish")
|
|
1766
|
-
return `${header}
|
|
1767
|
-
${FISH_FUNCTION}
|
|
1768
|
-
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
1769
|
-
`).join("")}`;
|
|
1770
|
-
if (shell === "bash")
|
|
1771
|
-
return `${header}
|
|
1772
|
-
${BASH_FUNCTION}
|
|
1773
|
-
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
1774
|
-
`;
|
|
1775
|
-
return `${header}
|
|
1776
|
-
${ZSH_FUNCTION}
|
|
1777
|
-
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
1778
|
-
`;
|
|
1779
|
-
}
|
|
1780
|
-
|
|
1781
|
-
// ../kit/src/notify.ts
|
|
1782
|
-
init_format2();
|
|
1783
|
-
init_mode();
|
|
1784
|
-
import process15 from "process";
|
|
1785
|
-
var NOTIFY_AFTER_MS = 1e4;
|
|
1786
|
-
var CANCELLED = 130;
|
|
1787
|
-
function base64(text) {
|
|
1788
|
-
return Buffer.from(text).toString("base64");
|
|
1789
|
-
}
|
|
1790
|
-
function notification(title, body, env = process15.env) {
|
|
1791
|
-
const id = `kit${process15.pid}`;
|
|
1792
|
-
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\\`];
|
|
1793
|
-
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
1794
|
-
}
|
|
1795
|
-
function notifyEnd(command, code, ms, { stream = process15.stderr, env = process15.env } = {}) {
|
|
1796
|
-
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
1797
|
-
return;
|
|
1798
|
-
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
1799
|
-
}
|
|
1800
|
-
|
|
1801
|
-
// ../kit/src/cli.ts
|
|
1802
|
-
init_style();
|
|
1803
|
-
init_text2();
|
|
1804
|
-
|
|
1805
|
-
// ../kit/src/usage.ts
|
|
1806
|
-
import { appendFileSync, mkdirSync } from "fs";
|
|
1807
|
-
import { homedir as homedir3 } from "os";
|
|
1808
|
-
import { dirname as dirname2, join as join4 } from "path";
|
|
1809
|
-
import process16 from "process";
|
|
1810
|
-
|
|
1811
|
-
// ../kit/src/logs.ts
|
|
1812
|
-
init_user_config();
|
|
1813
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
1814
|
-
var CLI_FOLDER = "kaynooo-cli";
|
|
1815
|
-
|
|
1816
|
-
// ../kit/src/usage.ts
|
|
1817
|
-
init_user_config();
|
|
1818
|
-
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
1819
|
-
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
1820
|
-
var LONGEST_NAME = 40;
|
|
1821
|
-
var usageError;
|
|
1822
|
-
function noteUsageError(message) {
|
|
1823
|
-
usageError = message;
|
|
1824
|
-
}
|
|
1825
|
-
function stateHome(env = process16.env) {
|
|
1826
|
-
return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
|
|
1827
|
-
}
|
|
1828
|
-
function usagePath(env = process16.env) {
|
|
1829
|
-
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1830
|
-
}
|
|
1831
|
-
function usageRecorded(env = process16.env) {
|
|
1832
|
-
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1833
|
-
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1834
|
-
}
|
|
1835
|
-
function flagNames(argv) {
|
|
1836
|
-
const end = argv.indexOf("--");
|
|
1837
|
-
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
1838
|
-
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
1839
|
-
}
|
|
1840
|
-
function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
|
|
1841
|
-
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
1842
|
-
usageError = undefined;
|
|
1843
|
-
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
|
|
1844
|
-
}
|
|
1845
|
-
function recordUsage(entry, env = process16.env) {
|
|
1846
|
-
if (!usageRecorded(env))
|
|
1847
|
-
return;
|
|
1848
|
-
try {
|
|
1849
|
-
const path = usagePath(env);
|
|
1850
|
-
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
1851
|
-
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1852
|
-
`, { mode: 384 });
|
|
1853
|
-
} catch {}
|
|
1854
64
|
}
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
1878
|
-
}
|
|
1879
|
-
function shown(commands) {
|
|
1880
|
-
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
1881
|
-
}
|
|
1882
|
-
function takeOutputFlags(argv) {
|
|
1883
|
-
let index = 0;
|
|
1884
|
-
for (;index < argv.length; index++) {
|
|
1885
|
-
const word = argv[index];
|
|
1886
|
-
if (word === "--plain")
|
|
1887
|
-
applyOutput(undefined, true);
|
|
1888
|
-
else if (word.startsWith("--color="))
|
|
1889
|
-
applyOutput(word.slice("--color=".length), undefined);
|
|
1890
|
-
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
1891
|
-
applyOutput(argv[++index], undefined);
|
|
1892
|
-
else
|
|
1893
|
-
break;
|
|
1894
|
-
}
|
|
1895
|
-
return argv.slice(index);
|
|
1896
|
-
}
|
|
1897
|
-
async function resolveSummary(summary) {
|
|
1898
|
-
return typeof summary === "string" ? summary : summary();
|
|
1899
|
-
}
|
|
1900
|
-
function lookup({ commands, aliases }, word) {
|
|
1901
|
-
const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
|
|
1902
|
-
return Object.hasOwn(commands, name) ? commands[name] : undefined;
|
|
1903
|
-
}
|
|
1904
|
-
function scopeOf(commands, extra, aliases) {
|
|
1905
|
-
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
1906
|
-
}
|
|
1907
|
-
async function expand(scope, words) {
|
|
1908
|
-
if (scope.lazy.length === 0)
|
|
1909
|
-
return scope;
|
|
1910
|
-
const commands = { ...scope.commands };
|
|
1911
|
-
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
1912
|
-
for (const [name, command] of Object.entries(added))
|
|
1913
|
-
commands[name] ??= command;
|
|
1914
|
-
}
|
|
1915
|
-
return { ...scope, commands, lazy: [] };
|
|
1916
|
-
}
|
|
1917
|
-
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
1918
|
-
const colors = paint(stream);
|
|
1919
|
-
const prefix = path.join(" ");
|
|
1920
|
-
const summary = await resolveSummary(lazySummary);
|
|
1921
|
-
if (wantsHelpJson())
|
|
1922
|
-
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
1923
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1924
|
-
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
1925
|
-
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
1926
|
-
return [
|
|
1927
|
-
header(colors, summary),
|
|
1928
|
-
"",
|
|
1929
|
-
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
1930
|
-
"",
|
|
1931
|
-
...await commandRows(commands, colors),
|
|
1932
|
-
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
1933
|
-
"",
|
|
1934
|
-
colors.bold("Options:"),
|
|
1935
|
-
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
1936
|
-
...exampleRows(examples ?? [], colors),
|
|
1937
|
-
"",
|
|
1938
|
-
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
1939
|
-
].join(`
|
|
1940
|
-
`);
|
|
1941
|
-
}
|
|
1942
|
-
function printError(prefix, message, hint, cause) {
|
|
1943
|
-
const colors = paint(process17.stderr);
|
|
1944
|
-
const styled = takesControlCodes(process17.stderr);
|
|
1945
|
-
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1946
|
-
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1947
|
-
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1948
|
-
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1949
|
-
}
|
|
1950
|
-
function printJsonError(message, hint, cause) {
|
|
1951
|
-
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1952
|
-
}
|
|
1953
|
-
function wantsJson(argv) {
|
|
1954
|
-
const end = argv.indexOf("--");
|
|
1955
|
-
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1956
|
-
}
|
|
1957
|
-
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1958
|
-
if (error instanceof HelpShown)
|
|
1959
|
-
return 0;
|
|
1960
|
-
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1961
|
-
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1962
|
-
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1963
|
-
if (error instanceof Exit && error.code === 2)
|
|
1964
|
-
noteUsageError(error.message);
|
|
1965
|
-
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1966
|
-
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
1967
|
-
return error instanceof Exit ? error.code : 1;
|
|
1968
|
-
}
|
|
1969
|
-
async function dispatch(level, typed, { version, redact }) {
|
|
1970
|
-
const prefix = level.path.join(" ");
|
|
1971
|
-
let argv;
|
|
1972
|
-
try {
|
|
1973
|
-
argv = takeOutputFlags(typed);
|
|
1974
|
-
} catch (error) {
|
|
1975
|
-
return reportThrown(prefix, error);
|
|
1976
|
-
}
|
|
1977
|
-
const [name, ...args] = argv;
|
|
1978
|
-
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
1979
|
-
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
1980
|
-
try {
|
|
1981
|
-
return await fallback.run([]);
|
|
1982
|
-
} catch (error) {
|
|
1983
|
-
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
1984
|
-
}
|
|
1985
|
-
}
|
|
1986
|
-
if (name === undefined && level.path.length > 1) {
|
|
1987
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process17.stderr));
|
|
1988
|
-
return 2;
|
|
1989
|
-
}
|
|
1990
|
-
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1991
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process17.stdout));
|
|
1992
|
-
return 0;
|
|
1993
|
-
}
|
|
1994
|
-
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
1995
|
-
console.log(version);
|
|
1996
|
-
return 0;
|
|
1997
|
-
}
|
|
1998
|
-
let command = lookup(level, name);
|
|
1999
|
-
let rest = args;
|
|
2000
|
-
let ran = name;
|
|
2001
|
-
if (command === undefined && level.lazy.length > 0) {
|
|
2002
|
-
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
2003
|
-
command = lookup(level, name);
|
|
2004
|
-
}
|
|
2005
|
-
if (command === undefined && level.defaultCommand !== undefined) {
|
|
2006
|
-
command = level.commands[level.defaultCommand];
|
|
2007
|
-
rest = argv;
|
|
2008
|
-
ran = level.defaultCommand;
|
|
2009
|
-
}
|
|
2010
|
-
if (command === undefined) {
|
|
2011
|
-
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
2012
|
-
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
2013
|
-
return 2;
|
|
2014
|
-
}
|
|
2015
|
-
if ("commands" in command) {
|
|
2016
|
-
const { summary } = command;
|
|
2017
|
-
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 });
|
|
2018
|
-
}
|
|
2019
|
-
try {
|
|
2020
|
-
return await command.run(rest);
|
|
2021
|
-
} catch (error) {
|
|
2022
|
-
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
2023
|
-
}
|
|
2024
|
-
}
|
|
2025
|
-
var COMPLETE = "__complete";
|
|
2026
|
-
var FILES = "__files__";
|
|
2027
|
-
async function completingOf(run) {
|
|
2028
|
-
completion.active = true;
|
|
2029
|
-
try {
|
|
2030
|
-
await run([]);
|
|
2031
|
-
} catch (error) {
|
|
2032
|
-
if (error instanceof Completing)
|
|
2033
|
-
return error;
|
|
2034
|
-
} finally {
|
|
2035
|
-
completion.active = false;
|
|
2036
|
-
}
|
|
2037
|
-
return new Completing({});
|
|
2038
|
-
}
|
|
2039
|
-
async function optionsOf(run) {
|
|
2040
|
-
return (await completingOf(run)).options;
|
|
2041
|
-
}
|
|
2042
|
-
function candidateLine(candidate) {
|
|
2043
|
-
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
2044
|
-
}
|
|
2045
|
-
function positionalBeingTyped(before, { options, positionals }) {
|
|
2046
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
2047
|
-
const typed = [];
|
|
2048
|
-
let at = 0;
|
|
2049
|
-
while (at < before.length) {
|
|
2050
|
-
const word = before[at];
|
|
2051
|
-
if (word === "--") {
|
|
2052
|
-
typed.push(...before.slice(at + 1));
|
|
2053
|
-
break;
|
|
2054
|
-
}
|
|
2055
|
-
if (!word.startsWith("-"))
|
|
2056
|
-
typed.push(word);
|
|
2057
|
-
else if (takesValue(word))
|
|
2058
|
-
at++;
|
|
2059
|
-
at++;
|
|
2060
|
-
}
|
|
2061
|
-
const last = positionals.at(-1);
|
|
2062
|
-
if (typed.length < positionals.length)
|
|
2063
|
-
return { name: positionals[typed.length], typed };
|
|
2064
|
-
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
2065
|
-
}
|
|
2066
|
-
async function leafCandidates(run, words) {
|
|
2067
|
-
const completing = await completingOf(run);
|
|
2068
|
-
if ((words.at(-1) ?? "").startsWith("-"))
|
|
2069
|
-
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
2070
|
-
const flag = words.at(-2);
|
|
2071
|
-
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
2072
|
-
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
2073
|
-
if (option?.type === "string") {
|
|
2074
|
-
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
2075
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
2076
|
-
}
|
|
2077
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
2078
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
2079
|
-
}
|
|
2080
|
-
async function candidates(scope, defaultCommand, words, before = []) {
|
|
2081
|
-
const [word = "", ...rest] = words;
|
|
2082
|
-
const listing = rest.length === 0 && !word.startsWith("-");
|
|
2083
|
-
let { commands } = scope;
|
|
2084
|
-
let command = lookup(scope, word);
|
|
2085
|
-
if (listing || command === undefined) {
|
|
2086
|
-
const expanded = await expand(scope, [...before, ...words]);
|
|
2087
|
-
commands = expanded.commands;
|
|
2088
|
-
command = lookup(expanded, word);
|
|
2089
|
-
}
|
|
2090
|
-
if (listing) {
|
|
2091
|
-
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
2092
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
2093
|
-
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
2094
|
-
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
2095
|
-
return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
|
|
2096
|
-
}
|
|
2097
|
-
if (command === undefined) {
|
|
2098
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
2099
|
-
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
2100
|
-
}
|
|
2101
|
-
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
2102
|
-
}
|
|
2103
|
-
var COMPLETIONS = "--completions";
|
|
2104
|
-
function flagValue([flag = "", ...rest]) {
|
|
2105
|
-
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
2106
|
-
}
|
|
2107
|
-
function printCompletionScript(name, args) {
|
|
2108
|
-
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
2109
|
-
if (shell === undefined || args.length !== 1) {
|
|
2110
|
-
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
2111
|
-
return 2;
|
|
2112
|
-
}
|
|
2113
|
-
console.log(completionScript(shell, [name]).trimEnd());
|
|
2114
|
-
return 0;
|
|
2115
|
-
}
|
|
2116
|
-
async function printCandidates(found) {
|
|
2117
|
-
for (const line of await found)
|
|
2118
|
-
console.log(line);
|
|
2119
|
-
return 0;
|
|
2120
|
-
}
|
|
2121
|
-
function packageVersion(entry = Bun.main) {
|
|
2122
|
-
let resolved = entry;
|
|
2123
|
-
try {
|
|
2124
|
-
resolved = realpathSync2(entry);
|
|
2125
|
-
} catch {}
|
|
2126
|
-
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
2127
|
-
try {
|
|
2128
|
-
const { version } = JSON.parse(readFileSync5(join5(dir, "package.json"), "utf8"));
|
|
2129
|
-
if (typeof version === "string")
|
|
2130
|
-
return version;
|
|
2131
|
-
} catch {}
|
|
2132
|
-
if (dirname3(dir) === dir)
|
|
2133
|
-
return "0.0.0";
|
|
2134
|
-
}
|
|
2135
|
-
}
|
|
2136
|
-
async function runCli(cli, argv = scriptArgs()) {
|
|
2137
|
-
const version = cli.version ?? packageVersion();
|
|
2138
|
-
const answered = await askpassClient(argv);
|
|
2139
|
-
if (answered !== undefined)
|
|
2140
|
-
return answered;
|
|
2141
|
-
if (argv[0] === COMPLETE)
|
|
2142
|
-
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
2143
|
-
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
2144
|
-
return printCompletionScript(cli.name, flagValue(argv));
|
|
2145
|
-
const started = performance.now();
|
|
2146
|
-
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 });
|
|
2147
|
-
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
2148
|
-
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
2149
|
-
if (cli.usage !== false) {
|
|
2150
|
-
try {
|
|
2151
|
-
recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
|
|
2152
|
-
} catch {}
|
|
2153
|
-
}
|
|
2154
|
-
return code;
|
|
2155
|
-
}
|
|
2156
|
-
function commandPath(scope, argv) {
|
|
2157
|
-
const path = [];
|
|
2158
|
-
let level = scope;
|
|
2159
|
-
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
2160
|
-
const command = lookup(level, word);
|
|
2161
|
-
if (command === undefined)
|
|
2162
|
-
break;
|
|
2163
|
-
path.push(word);
|
|
2164
|
-
if (!("commands" in command))
|
|
2165
|
-
break;
|
|
2166
|
-
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
2167
|
-
}
|
|
2168
|
-
return path.length === 0 ? undefined : path.join(" ");
|
|
2169
|
-
}
|
|
2170
|
-
|
|
2171
|
-
// ../kit/src/index.ts
|
|
2172
|
-
init_config();
|
|
2173
|
-
|
|
2174
|
-
// ../kit/src/excerpt.ts
|
|
2175
|
-
init_text2();
|
|
2176
|
-
|
|
2177
|
-
// ../kit/src/index.ts
|
|
2178
|
-
init_folders();
|
|
2179
|
-
init_format2();
|
|
2180
|
-
|
|
2181
|
-
// ../kit/src/git.ts
|
|
2182
|
-
init_args();
|
|
2183
|
-
// ../kit/src/limit.ts
|
|
2184
|
-
init_args();
|
|
2185
|
-
|
|
2186
|
-
// ../kit/src/index.ts
|
|
2187
|
-
init_mode();
|
|
2188
|
-
|
|
2189
|
-
// ../kit/src/pool.ts
|
|
2190
|
-
async function pool(items, limit, task, onDone) {
|
|
2191
|
-
const results = Array.from({ length: items.length });
|
|
2192
|
-
let next = 0;
|
|
2193
|
-
let done = 0;
|
|
2194
|
-
async function worker() {
|
|
2195
|
-
while (next < items.length) {
|
|
2196
|
-
const index = next++;
|
|
2197
|
-
results[index] = await task(items[index]);
|
|
2198
|
-
onDone?.(++done, items.length);
|
|
2199
|
-
}
|
|
2200
|
-
}
|
|
2201
|
-
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
2202
|
-
return results;
|
|
2203
|
-
}
|
|
2204
|
-
// ../kit/src/report.ts
|
|
2205
|
-
init_style();
|
|
2206
|
-
init_text2();
|
|
2207
|
-
// ../kit/src/secrets.ts
|
|
2208
|
-
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
2209
|
-
var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
|
|
2210
|
-
// ../kit/src/sessions.ts
|
|
2211
|
-
var {Glob } = globalThis.Bun;
|
|
2212
|
-
var SESSION_FILES = new Glob("*.json");
|
|
2213
|
-
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
2214
|
-
// ../kit/src/size.ts
|
|
2215
|
-
var SIZE = /^(\d+(?:\.\d+)?)\s*(?:([kmgt])i?b?|(b))?$/i;
|
|
2216
|
-
var POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
|
|
2217
|
-
function parseSize(text, bareUnit = 1) {
|
|
2218
|
-
const match = SIZE.exec(text.trim());
|
|
2219
|
-
if (match === null)
|
|
2220
|
-
return;
|
|
2221
|
-
const suffix = match[2]?.toLowerCase();
|
|
2222
|
-
let unit = bareUnit;
|
|
2223
|
-
if (match[3] !== undefined)
|
|
2224
|
-
unit = 1;
|
|
2225
|
-
else if (suffix !== undefined)
|
|
2226
|
-
unit = 1024 ** POWERS[suffix];
|
|
2227
|
-
return Math.round(Number(match[1]) * unit);
|
|
2228
|
-
}
|
|
2229
|
-
|
|
2230
|
-
// ../kit/src/index.ts
|
|
2231
|
-
init_style();
|
|
2232
|
-
init_text2();
|
|
2233
|
-
init_theme();
|
|
2234
|
-
init_user_config();
|
|
2235
|
-
|
|
2236
|
-
// ../kit/src/watch.ts
|
|
2237
|
-
init_args();
|
|
2238
|
-
init_input();
|
|
2239
|
-
init_style();
|
|
2240
|
-
import process18 from "process";
|
|
2241
|
-
import { format } from "util";
|
|
2242
|
-
var CLEAR_SCREEN = "\x1B[H\x1B[2J";
|
|
2243
|
-
var DEFAULT_SECONDS = 2;
|
|
2244
|
-
var ATTACHED_SHORT = /^-w./;
|
|
2245
|
-
var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
|
|
2246
|
-
function watchOption(what) {
|
|
2247
|
-
return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
|
|
2248
|
-
}
|
|
2249
|
-
function withoutWatch(args) {
|
|
2250
|
-
const rest = [];
|
|
2251
|
-
for (let at = 0;at < args.length; at++) {
|
|
2252
|
-
const arg = args[at];
|
|
2253
|
-
if (arg === "--watch" || arg === "-w") {
|
|
2254
|
-
if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
|
|
2255
|
-
at++;
|
|
2256
|
-
} else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
|
|
2257
|
-
rest.push(arg);
|
|
2258
|
-
}
|
|
2259
|
-
}
|
|
2260
|
-
return rest;
|
|
2261
|
-
}
|
|
2262
|
-
async function watching(value, step, stream = process18.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
|
|
2263
|
-
const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
|
|
2264
|
-
if (!takesControlCodes(stream))
|
|
2265
|
-
badUsage("--watch redraws the screen, so it needs a terminal");
|
|
2266
|
-
let code = 0;
|
|
2267
|
-
for (let round = 0;round < rounds; round++) {
|
|
2268
|
-
const held = [];
|
|
2269
|
-
const { log, info } = console;
|
|
2270
|
-
const write = process18.stdout.write.bind(process18.stdout);
|
|
2271
|
-
const hold = (...parts) => void held.push(`${format(...parts)}
|
|
2272
|
-
`);
|
|
2273
|
-
console.log = hold;
|
|
2274
|
-
console.info = hold;
|
|
2275
|
-
process18.stdout.write = (text) => {
|
|
2276
|
-
held.push(typeof text === "string" ? text : Buffer.from(text).toString());
|
|
2277
|
-
return true;
|
|
2278
|
-
};
|
|
2279
|
-
try {
|
|
2280
|
-
code = await step();
|
|
2281
|
-
} finally {
|
|
2282
|
-
console.log = log;
|
|
2283
|
-
console.info = info;
|
|
2284
|
-
process18.stdout.write = write;
|
|
2285
|
-
}
|
|
2286
|
-
stream.write(`${CLEAR_SCREEN}${held.join("")}`);
|
|
2287
|
-
await sleep(interval);
|
|
2288
|
-
}
|
|
2289
|
-
return code;
|
|
2290
|
-
}
|
|
2291
|
-
// ../kit/src/workspace-root.ts
|
|
2292
|
-
init_user_config();
|
|
2293
|
-
import { homedir as homedir4 } from "os";
|
|
2294
|
-
import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
|
|
2295
|
-
import process19 from "process";
|
|
2296
|
-
function expandHome(path, home) {
|
|
2297
|
-
if (path === "~")
|
|
2298
|
-
return home;
|
|
2299
|
-
return path.startsWith("~/") ? join6(home, path.slice(2)) : path;
|
|
2300
|
-
}
|
|
2301
|
-
function configured(env, home) {
|
|
2302
|
-
const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
|
|
2303
|
-
return typeof folder === "string" && folder !== "" ? folder : undefined;
|
|
2304
|
-
}
|
|
2305
|
-
function workspaceRoot({ given, env = process19.env, home = homedir4() } = {}) {
|
|
2306
|
-
const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
|
|
2307
|
-
return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
|
|
2308
|
-
}
|
|
2309
|
-
// src/audit.ts
|
|
2310
|
-
import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync8, statSync as statSync2 } from "fs";
|
|
2311
|
-
import { readdir } from "fs/promises";
|
|
2312
|
-
import { join as join9, relative, resolve as resolve5 } from "path";
|
|
2313
|
-
import process21 from "process";
|
|
2314
|
-
|
|
2315
|
-
// src/osv.ts
|
|
2316
|
-
import { existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
|
|
2317
|
-
import { join as join8 } from "path";
|
|
2318
|
-
|
|
2319
|
-
// src/report.ts
|
|
2320
|
-
import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
|
|
2321
|
-
import { join as join7 } from "path";
|
|
2322
|
-
var UPPER_BOUND = /<\s*(\d[\w.+-]*)/;
|
|
2323
|
-
var DEPENDENCY_KINDS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
|
|
2324
|
-
var GHSA = /GHSA-[\w-]+$/;
|
|
2325
|
-
function parseAudit(text) {
|
|
2326
|
-
try {
|
|
2327
|
-
const parsed = JSON.parse(text);
|
|
2328
|
-
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : undefined;
|
|
2329
|
-
} catch {
|
|
2330
|
-
return;
|
|
2331
|
-
}
|
|
2332
|
-
}
|
|
2333
|
-
function fixedAt(range) {
|
|
2334
|
-
const bounds = range.split("||").map((part) => UPPER_BOUND.exec(part)?.[1]);
|
|
2335
|
-
if (bounds.length === 0 || bounds.includes(undefined))
|
|
2336
|
-
return;
|
|
2337
|
-
return bounds.reduce((highest, bound) => Bun.semver.order(bound, highest) > 0 ? bound : highest);
|
|
2338
|
-
}
|
|
2339
|
-
function fixFor(advisories) {
|
|
2340
|
-
const fixes = advisories.map((advisory) => fixedAt(advisory.vulnerable_versions));
|
|
2341
|
-
if (fixes.length === 0 || fixes.includes(undefined))
|
|
2342
|
-
return;
|
|
2343
|
-
return fixes.reduce((highest, fix) => Bun.semver.order(fix, highest) > 0 ? fix : highest);
|
|
2344
|
-
}
|
|
2345
|
-
function findingsOf(audit, reaching, direct, level, ignore = [], via = new Map) {
|
|
2346
|
-
const found = [];
|
|
2347
|
-
for (const [name, all] of Object.entries(audit)) {
|
|
2348
|
-
const kept = all.filter((advisory) => severityRank(advisory.severity) >= severityRank(level) && !isIgnored({ id: advisory.id, ghsa: GHSA.exec(advisory.url)?.[0] }, ignore));
|
|
2349
|
-
if (kept.length === 0)
|
|
2350
|
-
continue;
|
|
2351
|
-
const advisories = kept.map((advisory) => ({ id: advisory.id, ghsa: GHSA.exec(advisory.url)?.[0], url: advisory.url, title: advisory.title, severity: advisory.severity, fixed: fixedAt(advisory.vulnerable_versions) }));
|
|
2352
|
-
found.push({
|
|
2353
|
-
package: name,
|
|
2354
|
-
severity: advisories.reduce((worst, advisory) => severityRank(advisory.severity) > severityRank(worst) ? advisory.severity : worst, advisories[0].severity),
|
|
2355
|
-
advisories,
|
|
2356
|
-
scope: reaching.has(name) ? "prod" : "dev",
|
|
2357
|
-
direct: direct.has(name),
|
|
2358
|
-
via: direct.has(name) ? [] : via.get(name) ?? [],
|
|
2359
|
-
fix: fixFor(kept)
|
|
2360
|
-
});
|
|
2361
|
-
}
|
|
2362
|
-
return found.toSorted((a, b) => severityRank(b.severity) - severityRank(a.severity) || Number(b.scope === "prod") - Number(a.scope === "prod") || a.package.localeCompare(b.package));
|
|
2363
|
-
}
|
|
2364
|
-
function lockGraph(lockText) {
|
|
2365
|
-
const graph = new Map;
|
|
2366
|
-
let lock;
|
|
2367
|
-
try {
|
|
2368
|
-
lock = Bun.JSONC.parse(lockText);
|
|
2369
|
-
} catch {
|
|
2370
|
-
return graph;
|
|
2371
|
-
}
|
|
2372
|
-
for (const entry of Object.values(lock?.packages ?? {})) {
|
|
2373
|
-
const resolution = entry[0];
|
|
2374
|
-
const info = entry[2];
|
|
2375
|
-
if (typeof resolution !== "string" || typeof info !== "object" || info === null)
|
|
2376
|
-
continue;
|
|
2377
|
-
const at = resolution.indexOf("@", 1);
|
|
2378
|
-
const name = at === -1 ? resolution : resolution.slice(0, at);
|
|
2379
|
-
const wanted = DEPENDENCY_KINDS.flatMap((kind) => Object.keys(info[kind] ?? {}));
|
|
2380
|
-
graph.set(name, [...new Set([...graph.get(name) ?? [], ...wanted])]);
|
|
2381
|
-
}
|
|
2382
|
-
return graph;
|
|
2383
|
-
}
|
|
2384
|
-
function reachedFrom(graph, direct, targets) {
|
|
2385
|
-
const from = new Map;
|
|
2386
|
-
for (const start of direct) {
|
|
2387
|
-
const seen = new Set([start]);
|
|
2388
|
-
const queue = [start];
|
|
2389
|
-
for (let name = queue.shift();name !== undefined; name = queue.shift()) {
|
|
2390
|
-
if (name !== start && targets.has(name))
|
|
2391
|
-
from.set(name, [...from.get(name) ?? [], start]);
|
|
2392
|
-
for (const next of graph.get(name) ?? []) {
|
|
2393
|
-
if (!seen.has(next)) {
|
|
2394
|
-
seen.add(next);
|
|
2395
|
-
queue.push(next);
|
|
2396
|
-
}
|
|
2397
|
-
}
|
|
2398
|
-
}
|
|
2399
|
-
}
|
|
2400
|
-
return new Map([...from].map(([name, starts]) => [name, starts.toSorted()]));
|
|
2401
|
-
}
|
|
2402
|
-
function readManifest(path) {
|
|
2403
|
-
try {
|
|
2404
|
-
return existsSync4(path) ? JSON.parse(readFileSync6(path, "utf8")) : {};
|
|
2405
|
-
} catch {
|
|
2406
|
-
return {};
|
|
2407
|
-
}
|
|
2408
|
-
}
|
|
2409
|
-
function namesIn(manifest) {
|
|
2410
|
-
return DEPENDENCY_KINDS.flatMap((kind) => {
|
|
2411
|
-
const section = manifest[kind];
|
|
2412
|
-
return typeof section === "object" && section !== null ? Object.keys(section) : [];
|
|
2413
|
-
});
|
|
2414
|
-
}
|
|
2415
|
-
function directDependencies(root, workspaces) {
|
|
2416
|
-
const names = new Set(namesIn(readManifest(join7(root, "package.json"))));
|
|
2417
|
-
for (const workspace of workspaces) {
|
|
2418
|
-
for (const name of namesIn(readManifest(join7(root, workspace, "package.json"))))
|
|
2419
|
-
names.add(name);
|
|
2420
|
-
}
|
|
2421
|
-
return names;
|
|
2422
|
-
}
|
|
2423
|
-
function workspacePatterns(field) {
|
|
2424
|
-
if (Array.isArray(field))
|
|
2425
|
-
return field;
|
|
2426
|
-
const packages = typeof field === "object" && field !== null ? field.packages : undefined;
|
|
2427
|
-
return Array.isArray(packages) ? packages : [];
|
|
2428
|
-
}
|
|
2429
|
-
function workspaceFolders(root, children) {
|
|
2430
|
-
const patterns = workspacePatterns(readManifest(join7(root, "package.json")).workspaces);
|
|
2431
|
-
return patterns.filter((pattern) => typeof pattern === "string").flatMap((pattern) => pattern.endsWith("/*") ? children(pattern.slice(0, -2)).map((name) => join7(pattern.slice(0, -2), name)) : [pattern]);
|
|
2432
|
-
}
|
|
2433
|
-
|
|
2434
|
-
// src/osv.ts
|
|
2435
|
-
var OSV = "https://api.osv.dev/v1";
|
|
2436
|
-
var BATCH = 1000;
|
|
2437
|
-
var DETAIL_CONCURRENCY = 8;
|
|
2438
|
-
var TIMEOUT_MS = 20000;
|
|
2439
|
-
var PACKAGE_BLOCK = /^\[\[package\]\]\s*$/m;
|
|
2440
|
-
var FIELD = /^(name|version|source) = (.+)$/gm;
|
|
2441
|
-
var QUOTED = /^"([^"]*)"$/;
|
|
2442
|
-
var LEADING_V = /^v/;
|
|
2443
|
-
function parseComposerLock(text) {
|
|
2444
|
-
const lock = JSON.parse(text);
|
|
2445
|
-
const entry = (prod) => (each) => ({ name: each.name, version: each.version.replace(LEADING_V, ""), prod });
|
|
2446
|
-
return [...(lock.packages ?? []).map(entry(true)), ...(lock["packages-dev"] ?? []).map(entry(false))];
|
|
2447
|
-
}
|
|
2448
|
-
function tomlPackages(text, fromRegistry) {
|
|
2449
|
-
const found = [];
|
|
2450
|
-
for (const block of text.split(PACKAGE_BLOCK).slice(1)) {
|
|
2451
|
-
const fields = new Map;
|
|
2452
|
-
for (const [, key, value] of block.matchAll(FIELD))
|
|
2453
|
-
fields.set(key, QUOTED.exec(value.trim())?.[1] ?? value.trim());
|
|
2454
|
-
const source = fields.get("source");
|
|
2455
|
-
const name = fields.get("name");
|
|
2456
|
-
const version = fields.get("version");
|
|
2457
|
-
if (name !== undefined && version !== undefined && source !== undefined && fromRegistry(source))
|
|
2458
|
-
found.push({ name, version, prod: true });
|
|
2459
|
-
}
|
|
2460
|
-
return found;
|
|
2461
|
-
}
|
|
2462
|
-
function parseCargoLock(text) {
|
|
2463
|
-
return tomlPackages(text, (source) => source.startsWith("registry+"));
|
|
2464
|
-
}
|
|
2465
|
-
function parseUvLock(text) {
|
|
2466
|
-
return tomlPackages(text, (source) => source.includes("registry"));
|
|
2467
|
-
}
|
|
2468
|
-
var ECOSYSTEMS = [
|
|
2469
|
-
{ lockfile: "composer.lock", osv: "Packagist", parse: parseComposerLock },
|
|
2470
|
-
{ lockfile: "Cargo.lock", osv: "crates.io", parse: parseCargoLock },
|
|
2471
|
-
{ lockfile: "uv.lock", osv: "PyPI", parse: parseUvLock }
|
|
2472
|
-
];
|
|
2473
|
-
function holdsOsvLock(dir) {
|
|
2474
|
-
return ECOSYSTEMS.some((each) => existsSync5(join8(dir, each.lockfile)));
|
|
2475
|
-
}
|
|
2476
|
-
var SEVERITY_NAMES = { LOW: "low", MODERATE: "moderate", MEDIUM: "moderate", HIGH: "high", CRITICAL: "critical" };
|
|
2477
|
-
async function ok2(response) {
|
|
2478
|
-
if (!response.ok)
|
|
2479
|
-
throw new Error(`osv.dev answered ${response.status}`);
|
|
2480
|
-
return response.json();
|
|
2481
|
-
}
|
|
2482
|
-
function rowOf(vuln, name) {
|
|
2483
|
-
const fixes = (vuln.affected ?? []).filter((each) => each.package?.name === name).flatMap((each) => each.ranges ?? []).flatMap((range) => range.events ?? []).map((event) => event.fixed).filter((fixed) => fixed !== undefined);
|
|
2484
|
-
return { id: 0, ghsa: vuln.id, url: `https://osv.dev/vulnerability/${vuln.id}`, title: vuln.summary ?? vuln.id, severity: SEVERITY_NAMES[vuln.database_specific?.severity?.toUpperCase() ?? ""] ?? "moderate", fixed: fixes.length === 0 ? undefined : fixedAt(fixes.map((fix) => `<${fix}`).join(" || ")) };
|
|
2485
|
-
}
|
|
2486
|
-
async function osvFindings(locked, ecosystem, direct, level, ignore, fetcher = fetch) {
|
|
2487
|
-
const hits = new Map;
|
|
2488
|
-
for (let start = 0;start < locked.length; start += BATCH) {
|
|
2489
|
-
const chunk = locked.slice(start, start + BATCH);
|
|
2490
|
-
const queries = chunk.map((each) => ({ package: { name: each.name, ecosystem }, version: each.version }));
|
|
2491
|
-
const answer = await ok2(await fetcher(`${OSV}/querybatch`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ queries }), signal: AbortSignal.timeout(TIMEOUT_MS) }));
|
|
2492
|
-
for (const [index, each] of chunk.entries()) {
|
|
2493
|
-
const ids = (answer.results[index]?.vulns ?? []).map((vuln) => vuln.id).filter((id) => !ignore.includes(id));
|
|
2494
|
-
if (ids.length > 0)
|
|
2495
|
-
hits.set(each, ids);
|
|
2496
|
-
}
|
|
2497
|
-
}
|
|
2498
|
-
const details = new Map;
|
|
2499
|
-
await pool([...new Set([...hits.values()].flat())], DETAIL_CONCURRENCY, async (id) => {
|
|
2500
|
-
details.set(id, await ok2(await fetcher(`${OSV}/vulns/${encodeURIComponent(id)}`, { signal: AbortSignal.timeout(TIMEOUT_MS) })));
|
|
2501
|
-
});
|
|
2502
|
-
const findings = [];
|
|
2503
|
-
let below = 0;
|
|
2504
|
-
for (const [each, ids] of hits) {
|
|
2505
|
-
const rows = ids.map((id) => rowOf(details.get(id), each.name));
|
|
2506
|
-
const advisories = rows.filter((row) => severityRank(row.severity) >= severityRank(level));
|
|
2507
|
-
below += rows.length - advisories.length;
|
|
2508
|
-
if (advisories.length === 0)
|
|
2509
|
-
continue;
|
|
2510
|
-
const fixes = advisories.map((row) => row.fixed);
|
|
2511
|
-
findings.push({
|
|
2512
|
-
package: each.name,
|
|
2513
|
-
severity: advisories.reduce((worst, row) => severityRank(row.severity) > severityRank(worst) ? row.severity : worst, advisories[0].severity),
|
|
2514
|
-
advisories,
|
|
2515
|
-
scope: each.prod ? "prod" : "dev",
|
|
2516
|
-
direct: direct.has(each.name),
|
|
2517
|
-
via: [],
|
|
2518
|
-
fix: fixes.includes(undefined) ? undefined : fixes.reduce((highest, fix) => Bun.semver.order(fix, highest) > 0 ? fix : highest)
|
|
2519
|
-
});
|
|
2520
|
-
}
|
|
2521
|
-
return { findings: findings.toSorted((a, b) => severityRank(b.severity) - severityRank(a.severity) || Number(b.scope === "prod") - Number(a.scope === "prod") || a.package.localeCompare(b.package)), below };
|
|
2522
|
-
}
|
|
2523
|
-
function manifestNames(dir) {
|
|
2524
|
-
try {
|
|
2525
|
-
const manifest = JSON.parse(readFileSync7(join8(dir, "composer.json"), "utf8"));
|
|
2526
|
-
return new Set([...Object.keys(manifest.require ?? {}), ...Object.keys(manifest["require-dev"] ?? {})]);
|
|
2527
|
-
} catch {
|
|
2528
|
-
return new Set;
|
|
2529
|
-
}
|
|
2530
|
-
}
|
|
2531
|
-
async function osvAudit(dir, level, ignore, fetcher = fetch) {
|
|
2532
|
-
const all = { findings: [], below: 0 };
|
|
2533
|
-
for (const each of ECOSYSTEMS.filter((each) => existsSync5(join8(dir, each.lockfile)))) {
|
|
2534
|
-
const done = await osvFindings(each.parse(readFileSync7(join8(dir, each.lockfile), "utf8")), each.osv, each.lockfile === "composer.lock" ? manifestNames(dir) : new Set, level, ignore, fetcher);
|
|
2535
|
-
all.findings.push(...done.findings);
|
|
2536
|
-
all.below += done.below;
|
|
2537
|
-
}
|
|
2538
|
-
return all;
|
|
2539
|
-
}
|
|
2540
|
-
|
|
2541
|
-
// src/audit.ts
|
|
2542
|
-
var USAGE = `ws audit [options] [root]: the known vulnerabilities of the Bun, Composer, Cargo and uv repositories under root (the current folder by default), one table per repository
|
|
2543
|
-
|
|
2544
|
-
Each package with an advisory is one row: its worst severity, advisory count, prod or dev, direct or via the direct dependencies leading to it, and the version that fixes every advisory at once.
|
|
2545
|
-
It reaches the network: \`bun audit --json\` for a bun.lock, osv.dev for a composer.lock, Cargo.lock or uv.lock; the walk goes three levels deep and stops at a lockfile.
|
|
2546
|
-
To sweep many repositories at once; \`pkg audit\` vets the one repository in depth.`;
|
|
2547
|
-
var EXITS = [[0, "no repository has an advisory at the level asked"], [1, "one has"], [2, "a repository's audit failed, no lockfile sits under root, a usage error or a root that is no folder"]];
|
|
2548
|
-
var OPTIONS = {
|
|
2549
|
-
level: { type: "string", choices: SEVERITIES, default: "moderate", description: "only the advisories at least this severe: low, moderate, high or critical" },
|
|
2550
|
-
prod: { type: "boolean", description: "only the packages a production dependency needs" },
|
|
2551
|
-
ignore: { type: "string", multiple: true, description: "an advisory skipped by GHSA or numeric id, repeatable" },
|
|
2552
|
-
json: jsonOption("[{repo, path, findings: [{package, severity, scope, direct, via, fix, advisories: [{id, ghsa, url, title, severity, fixed}]}], below: advisories under --level, warnings: what bun audit could not audit, error}]")
|
|
2553
|
-
};
|
|
2554
|
-
var MAX_DEPTH = 3;
|
|
2555
|
-
var CONCURRENCY = 4;
|
|
2556
|
-
var AUDIT_MS = 60000;
|
|
2557
|
-
var WARNING = /^warn: .+$/gm;
|
|
2558
|
-
var VIA_SHOWN = 2;
|
|
2559
|
-
function countAdvisories(findings) {
|
|
2560
|
-
return findings.reduce((sum, found) => sum + found.advisories.length, 0);
|
|
2561
|
-
}
|
|
2562
|
-
function holdsBunLock(dir) {
|
|
2563
|
-
return existsSync6(join9(dir, "bun.lock")) || existsSync6(join9(dir, "bun.lockb"));
|
|
2564
|
-
}
|
|
2565
|
-
function holdsLock(dir) {
|
|
2566
|
-
return holdsBunLock(dir) || holdsOsvLock(dir);
|
|
2567
|
-
}
|
|
2568
|
-
async function findRepos(root) {
|
|
2569
|
-
if (holdsLock(root))
|
|
2570
|
-
return [root];
|
|
2571
|
-
const found = [];
|
|
2572
|
-
async function walk(dir, depth) {
|
|
2573
|
-
let entries;
|
|
2574
|
-
try {
|
|
2575
|
-
entries = await readdir(dir, { withFileTypes: true });
|
|
2576
|
-
} catch {
|
|
2577
|
-
return;
|
|
2578
|
-
}
|
|
2579
|
-
for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
|
|
2580
|
-
if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith("."))
|
|
2581
|
-
continue;
|
|
2582
|
-
const path = join9(dir, entry.name);
|
|
2583
|
-
if (holdsLock(path))
|
|
2584
|
-
found.push(path);
|
|
2585
|
-
else if (depth < MAX_DEPTH)
|
|
2586
|
-
await walk(path, depth + 1);
|
|
2587
|
-
}
|
|
2588
|
-
}
|
|
2589
|
-
await walk(root, 1);
|
|
2590
|
-
return found;
|
|
2591
|
-
}
|
|
2592
|
-
function children(root) {
|
|
2593
|
-
return (folder) => {
|
|
2594
|
-
try {
|
|
2595
|
-
return readdirSync(join9(root, folder), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
|
|
2596
|
-
} catch {
|
|
2597
|
-
return [];
|
|
2598
|
-
}
|
|
2599
|
-
};
|
|
2600
|
-
}
|
|
2601
|
-
async function audited(path, shown, level, ignore) {
|
|
2602
|
-
const bun = holdsBunLock(path) ? await bunAudited(path, shown, level, ignore) : { repo: shown, path, findings: [], below: 0, warnings: [], error: undefined };
|
|
2603
|
-
if (bun.error !== undefined || !holdsOsvLock(path))
|
|
2604
|
-
return bun;
|
|
2605
|
-
try {
|
|
2606
|
-
const osv = await osvAudit(path, level, ignore);
|
|
2607
|
-
return { ...bun, findings: [...bun.findings, ...osv.findings], below: bun.below + osv.below };
|
|
2608
|
-
} catch (error) {
|
|
2609
|
-
return { ...bun, error: `osv.dev: ${error instanceof Error ? error.message : String(error)}` };
|
|
2610
|
-
}
|
|
2611
|
-
}
|
|
2612
|
-
async function bunAudited(path, shown, level, ignore) {
|
|
2613
|
-
const [all, production] = await Promise.all([
|
|
2614
|
-
runCommand(["bun", "audit", "--json"], { cwd: path, timeoutMs: AUDIT_MS }),
|
|
2615
|
-
runCommand(["bun", "audit", "--json", "--prod"], { cwd: path, timeoutMs: AUDIT_MS })
|
|
2616
|
-
]);
|
|
2617
|
-
const audit = parseAudit(all.stdout);
|
|
2618
|
-
const reached = parseAudit(production.stdout);
|
|
2619
|
-
if (audit === undefined || reached === undefined)
|
|
2620
|
-
return { repo: shown, path, findings: [], below: 0, warnings: [], error: failure(audit === undefined ? all : production) };
|
|
2621
|
-
const reaching = new Set(Object.keys(reached));
|
|
2622
|
-
const direct = directDependencies(path, workspaceFolders(path, children(path)));
|
|
2623
|
-
const via = reachedFrom(lockGraph(lockText(path)), direct, new Set(Object.keys(audit)));
|
|
2624
|
-
const findings = findingsOf(audit, reaching, direct, level, ignore, via);
|
|
2625
|
-
return { repo: shown, path, findings, below: countAdvisories(findingsOf(audit, reaching, direct, "low", ignore)) - countAdvisories(findings), warnings: [...new Set(all.text.match(WARNING) ?? [])], error: undefined };
|
|
2626
|
-
}
|
|
2627
|
-
function lockText(path) {
|
|
2628
|
-
try {
|
|
2629
|
-
return readFileSync8(join9(path, "bun.lock"), "utf8");
|
|
2630
|
-
} catch {
|
|
2631
|
-
return "";
|
|
2632
|
-
}
|
|
2633
|
-
}
|
|
2634
|
-
function originOf(found) {
|
|
2635
|
-
if (found.direct)
|
|
2636
|
-
return "direct";
|
|
2637
|
-
if (found.via.length === 0)
|
|
2638
|
-
return "via";
|
|
2639
|
-
return `via ${found.via.slice(0, VIA_SHOWN).join(", ")}${found.via.length > VIA_SHOWN ? ` +${found.via.length - VIA_SHOWN}` : ""}`;
|
|
2640
|
-
}
|
|
2641
|
-
function failure(ran) {
|
|
2642
|
-
return ran.timedOut ? `timed out after ${AUDIT_MS / 1000}s` : ran.text.trim().split(`
|
|
2643
|
-
`).at(-1) ?? `exit ${ran.code}`;
|
|
2644
|
-
}
|
|
2645
|
-
function tint(severity) {
|
|
2646
|
-
const colors = paint(process21.stdout);
|
|
2647
|
-
if (severity === "critical" || severity === "high")
|
|
2648
|
-
return colors.red;
|
|
2649
|
-
return severity === "moderate" ? colors.yellow : colors.dim;
|
|
2650
|
-
}
|
|
2651
|
-
function rows(findings) {
|
|
2652
|
-
return findings.map((found) => [
|
|
2653
|
-
found.package,
|
|
2654
|
-
tint(found.severity)(found.severity),
|
|
2655
|
-
String(found.advisories.length),
|
|
2656
|
-
found.scope,
|
|
2657
|
-
originOf(found),
|
|
2658
|
-
found.fix ?? "-"
|
|
2659
|
-
]);
|
|
2660
|
-
}
|
|
2661
|
-
async function audit(args) {
|
|
2662
|
-
const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["[root]"], exits: EXITS, replaces: "a bun audit run in each repository and a read of every advisory to find what is worth fixing", examples: ["ws audit", "ws audit ~/Workspace --level high --prod"] });
|
|
2663
|
-
const root = resolve5(positionals[0] ?? ".");
|
|
2664
|
-
if (!existsSync6(root) || !statSync2(root).isDirectory())
|
|
2665
|
-
fail(`no folder ${root}`);
|
|
2666
|
-
const level = oneOf(values.level, "level", SEVERITIES);
|
|
2667
|
-
const progress = progressLine();
|
|
2668
|
-
let audits;
|
|
2669
|
-
try {
|
|
2670
|
-
progress.update({ step: "finding the repositories" });
|
|
2671
|
-
const paths = await findRepos(root);
|
|
2672
|
-
if (paths.length === 0)
|
|
2673
|
-
fail(`no bun.lock, composer.lock, Cargo.lock or uv.lock under ${root}`);
|
|
2674
|
-
progress.update({ step: "auditing", done: 0, total: paths.length, unit: "repositories" });
|
|
2675
|
-
audits = await pool(paths, configuredNumber("audit", "concurrency", CONCURRENCY), async (path) => audited(path, relative(root, path) || ".", level, values.ignore ?? []), (done, total) => progress.update({ step: "auditing", done, total, unit: "repositories" }));
|
|
2676
|
-
} finally {
|
|
2677
|
-
progress.stop();
|
|
2678
|
-
}
|
|
2679
|
-
const kept = audits.map((each) => ({ ...each, findings: values.prod === true ? each.findings.filter((found) => found.scope === "prod") : each.findings }));
|
|
2680
|
-
if (values.json === true)
|
|
2681
|
-
printJson(kept);
|
|
2682
|
-
else
|
|
2683
|
-
show(kept, audits.length);
|
|
2684
|
-
if (kept.some((each) => each.error !== undefined))
|
|
2685
|
-
return 2;
|
|
2686
|
-
return kept.some((each) => each.findings.length > 0) ? 1 : 0;
|
|
2687
|
-
}
|
|
2688
|
-
function show(audits, total) {
|
|
2689
|
-
const label = role("label", process21.stdout);
|
|
2690
|
-
const path = role("path", process21.stdout);
|
|
2691
|
-
const flagged = audits.filter((each) => each.error !== undefined || each.findings.length > 0);
|
|
2692
|
-
if (flagged.length === 0) {
|
|
2693
|
-
console.log(label(`no advisory in ${total} ${total === 1 ? "repository" : "repositories"}`));
|
|
2694
|
-
return;
|
|
2695
|
-
}
|
|
2696
|
-
for (const each of flagged) {
|
|
2697
|
-
console.log(`${path(each.repo)} ${label(each.error === undefined ? `${each.findings.length} ${each.findings.length === 1 ? "package" : "packages"}` : `audit failed: ${each.error}`)}`);
|
|
2698
|
-
if (each.findings.length > 0)
|
|
2699
|
-
console.log(table([["package", "severity", "advisories", "scope", "origin", "fix"], ...rows(each.findings)], { header: true, align: ["left", "left", "right", "left", "left", "left"] }));
|
|
2700
|
-
if (each.findings.some((found) => !found.direct))
|
|
2701
|
-
console.log(label("via: a dependency of the ones named, fixed by upgrading one of them to a release that depends on the fixed version"));
|
|
2702
|
-
if (each.below > 0)
|
|
2703
|
-
console.log(label(`${each.below} ${each.below === 1 ? "advisory" : "advisories"} below the level left out, --level low lists them`));
|
|
2704
|
-
for (const warning of each.warnings)
|
|
2705
|
-
console.log(label(warning));
|
|
2706
|
-
}
|
|
2707
|
-
}
|
|
2708
|
-
|
|
2709
|
-
// src/repos.ts
|
|
2710
|
-
import { existsSync as existsSync8, statSync as statSync3 } from "fs";
|
|
2711
|
-
import { basename as basename2, relative as relative2 } from "path";
|
|
2712
|
-
import process23 from "process";
|
|
2713
|
-
|
|
2714
|
-
// src/repos-scan.ts
|
|
2715
|
-
import { existsSync as existsSync7 } from "fs";
|
|
2716
|
-
import { readdir as readdir2 } from "fs/promises";
|
|
2717
|
-
import { basename, join as join10 } from "path";
|
|
2718
|
-
import process22 from "process";
|
|
2719
|
-
var MAX_DEPTH2 = 3;
|
|
2720
|
-
var CONCURRENCY2 = 8;
|
|
2721
|
-
var PACKAGE_CONCURRENCY = 4;
|
|
2722
|
-
var GIT_MS = 1e4;
|
|
2723
|
-
var FETCH_MS = 30000;
|
|
2724
|
-
var AHEAD_BEHIND = /\+(\d+) -(\d+)/;
|
|
2725
|
-
var PACKAGE_TAG = /^(.+)-v\d/;
|
|
2726
|
-
var REASONS = ["dirty", "unpushed", "unreleased", "behind"];
|
|
2727
|
-
function reasonsOf(repo) {
|
|
2728
|
-
const reasons = [];
|
|
2729
|
-
if (repo.dirty > 0)
|
|
2730
|
-
reasons.push("dirty");
|
|
2731
|
-
if ((repo.ahead ?? 0) > 0)
|
|
2732
|
-
reasons.push("unpushed");
|
|
2733
|
-
if ((repo.behind ?? 0) > 0)
|
|
2734
|
-
reasons.push("behind");
|
|
2735
|
-
if ((repo.unreleased ?? 0) > 0)
|
|
2736
|
-
reasons.push("unreleased");
|
|
2737
|
-
return reasons;
|
|
2738
|
-
}
|
|
2739
|
-
async function findRepos2(root, skip) {
|
|
2740
|
-
if (existsSync7(join10(root, ".git")))
|
|
2741
|
-
return [root];
|
|
2742
|
-
const found = [];
|
|
2743
|
-
async function walk(dir, depth) {
|
|
2744
|
-
let entries;
|
|
2745
|
-
try {
|
|
2746
|
-
entries = await readdir2(dir, { withFileTypes: true });
|
|
2747
|
-
} catch {
|
|
2748
|
-
return;
|
|
2749
|
-
}
|
|
2750
|
-
for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
|
|
2751
|
-
if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith(".") || skip.has(entry.name))
|
|
2752
|
-
continue;
|
|
2753
|
-
const path = join10(dir, entry.name);
|
|
2754
|
-
if (existsSync7(join10(path, ".git")))
|
|
2755
|
-
found.push(path);
|
|
2756
|
-
else if (depth < MAX_DEPTH2)
|
|
2757
|
-
await walk(path, depth + 1);
|
|
2758
|
-
}
|
|
2759
|
-
}
|
|
2760
|
-
await walk(root, 1);
|
|
2761
|
-
return found;
|
|
2762
|
-
}
|
|
2763
|
-
async function read(path, args, timeoutMs = GIT_MS) {
|
|
2764
|
-
try {
|
|
2765
|
-
const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...process22.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs });
|
|
2766
|
-
return ran.code === 0 && !ran.timedOut ? ran.stdout.trim() : undefined;
|
|
2767
|
-
} catch {
|
|
2768
|
-
return;
|
|
2769
|
-
}
|
|
2770
|
-
}
|
|
2771
|
-
async function commitsSince(path, tag, folder) {
|
|
2772
|
-
const count = await read(path, ["rev-list", "--count", `${tag}..HEAD`, ...folder === undefined ? [] : ["--", folder]]);
|
|
2773
|
-
return Number(count ?? 0);
|
|
2774
|
-
}
|
|
2775
|
-
async function packageReleases(path) {
|
|
2776
|
-
const names = new Set;
|
|
2777
|
-
for (const tag of (await read(path, ["tag", "--list"]) ?? "").split(`
|
|
2778
|
-
`)) {
|
|
2779
|
-
const name = PACKAGE_TAG.exec(tag)?.[1];
|
|
2780
|
-
if (name !== undefined)
|
|
2781
|
-
names.add(name);
|
|
2782
|
-
}
|
|
2783
|
-
const releases = await pool([...names].toSorted(), PACKAGE_CONCURRENCY, async (name) => {
|
|
2784
|
-
const folder = [join10("packages", name), name].find((candidate) => existsSync7(join10(path, candidate)));
|
|
2785
|
-
const tag = folder === undefined ? undefined : await read(path, ["describe", "--tags", "--abbrev=0", "--match", `${name}-v*`]);
|
|
2786
|
-
return folder !== undefined && tag !== undefined && tag !== "" ? { name, tag, unreleased: await commitsSince(path, tag, folder) } : undefined;
|
|
2787
|
-
});
|
|
2788
|
-
return releases.filter((release) => release !== undefined);
|
|
2789
|
-
}
|
|
2790
|
-
async function inspect(path, fetch2) {
|
|
2791
|
-
const fetched = fetch2 ? await read(path, ["fetch", "--quiet"], FETCH_MS) : "";
|
|
2792
|
-
const [status, worktrees, packages] = await Promise.all([
|
|
2793
|
-
read(path, ["status", "--porcelain=v2", "--branch"]),
|
|
2794
|
-
read(path, ["worktree", "list", "--porcelain"]),
|
|
2795
|
-
packageReleases(path)
|
|
2796
|
-
]);
|
|
2797
|
-
const state = { name: basename(path), path, branch: "?", upstream: null, dirty: 0, ahead: null, behind: null, worktrees: 0, tag: null, unreleased: null, packages, fetchFailed: fetched === undefined, unreadable: status === undefined };
|
|
2798
|
-
for (const line of (status ?? "").split(`
|
|
2799
|
-
`)) {
|
|
2800
|
-
if (line.startsWith("# branch.head "))
|
|
2801
|
-
state.branch = line.slice("# branch.head ".length);
|
|
2802
|
-
else if (line.startsWith("# branch.upstream "))
|
|
2803
|
-
state.upstream = line.slice("# branch.upstream ".length);
|
|
2804
|
-
else if (line.startsWith("# branch.ab "))
|
|
2805
|
-
[state.ahead, state.behind] = AHEAD_BEHIND.exec(line)?.slice(1).map(Number);
|
|
2806
|
-
else if (line !== "" && !line.startsWith("#"))
|
|
2807
|
-
state.dirty++;
|
|
2808
|
-
}
|
|
2809
|
-
state.worktrees = Math.max(0, (worktrees ?? "").split(`
|
|
2810
|
-
`).filter((line) => line.startsWith("worktree ")).length - 1);
|
|
2811
|
-
if (packages.length > 0) {
|
|
2812
|
-
state.unreleased = packages.reduce((sum, release) => sum + release.unreleased, 0);
|
|
2813
|
-
} else {
|
|
2814
|
-
const tag = await read(path, ["describe", "--tags", "--abbrev=0"]);
|
|
2815
|
-
if (tag !== undefined && tag !== "") {
|
|
2816
|
-
state.tag = tag;
|
|
2817
|
-
state.unreleased = await commitsSince(path, tag);
|
|
2818
|
-
}
|
|
2819
|
-
}
|
|
2820
|
-
return state;
|
|
2821
|
-
}
|
|
2822
|
-
function pullBlocker(repo) {
|
|
2823
|
-
if (repo.unreadable)
|
|
2824
|
-
return "unreadable";
|
|
2825
|
-
if (repo.fetchFailed)
|
|
2826
|
-
return "fetch failed";
|
|
2827
|
-
if (repo.branch === "(detached)")
|
|
2828
|
-
return "detached HEAD";
|
|
2829
|
-
if (repo.upstream === null)
|
|
2830
|
-
return "no upstream";
|
|
2831
|
-
if (repo.dirty > 0)
|
|
2832
|
-
return `${repo.dirty} dirty ${repo.dirty === 1 ? "file" : "files"}`;
|
|
2833
|
-
return (repo.ahead ?? 0) > 0 ? `diverged, ${repo.ahead} ahead` : undefined;
|
|
2834
|
-
}
|
|
2835
|
-
function firstLine(text) {
|
|
2836
|
-
const end = text.indexOf(`
|
|
2837
|
-
`);
|
|
2838
|
-
return end === -1 ? text : text.slice(0, end);
|
|
2839
|
-
}
|
|
2840
|
-
async function fastForward(path) {
|
|
2841
|
-
try {
|
|
2842
|
-
const ran = await runCommand(["git", "--no-optional-locks", "merge", "--ff-only", "--quiet", "@{upstream}"], { cwd: path, env: { ...process22.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs: GIT_MS });
|
|
2843
|
-
if (ran.timedOut)
|
|
2844
|
-
return "timed out";
|
|
2845
|
-
return ran.code === 0 ? undefined : firstLine(ran.text.trim()) || `exit ${ran.code}`;
|
|
2846
|
-
} catch (error) {
|
|
2847
|
-
return error instanceof Error ? error.message : String(error);
|
|
2848
|
-
}
|
|
2849
|
-
}
|
|
2850
|
-
|
|
2851
|
-
// src/repos.ts
|
|
2852
|
-
var USAGE2 = `ws repos [options] [root]: the git repositories under root (the configured workspace by default) that need attention: dirty files, commits not pushed, an upstream ahead, commits since the latest tag
|
|
65
|
+
__kaynooo_cli_register() {
|
|
66
|
+
add-zsh-hook -d precmd __kaynooo_cli_register
|
|
67
|
+
(( $+functions[compdef] )) || { autoload -Uz compinit && compinit }
|
|
68
|
+
compdef __kaynooo_cli_complete $__kaynooo_cli_bins
|
|
69
|
+
}
|
|
70
|
+
autoload -Uz add-zsh-hook
|
|
71
|
+
add-zsh-hook precmd __kaynooo_cli_register
|
|
72
|
+
typeset -gaU __kaynooo_cli_bins
|
|
73
|
+
__kaynooo_cli_bins+=(${bins.join(" ")})
|
|
74
|
+
`}var COMPLETE="__complete",FILES="__files__",COMPLETIONS="--completions";function shown(commands){return Object.fromEntries(Object.entries(commands).filter(([,{hidden}])=>hidden!==!0))}async function resolveSummary(summary){return typeof summary==="string"?summary:summary()}function lookup({commands,aliases},word){let name=aliases!==void 0&&Object.hasOwn(aliases,word)?aliases[word]??word:word;return Object.hasOwn(commands,name)?commands[name]:void 0}function scopeOf(commands,extra,aliases){return{commands:typeof commands==="function"?{}:commands,lazy:[...typeof commands==="function"?[commands]:[],...extra===void 0?[]:[extra]],aliases}}async function expand(scope,words){if(scope.lazy.length===0)return scope;let commands={...scope.commands};for(let added of await Promise.all(scope.lazy.map(async(lazy)=>lazy(words))))for(let[name,command]of Object.entries(added))commands[name]??=command;return{...scope,commands,lazy:[]}}async function completingOf(run){completion.active=!0;try{await run([])}catch(error){if(error instanceof Completing)return error}finally{completion.active=!1}return new Completing({})}async function optionsOf(run){return(await completingOf(run)).options}function candidateLine(candidate){return typeof candidate==="string"?candidate:candidate.join("\t")}function positionalBeingTyped(before,{options,positionals}){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),typed=[],at=0;while(at<before.length){let word=before[at];if(word==="--"){typed.push(...before.slice(at+1));break}if(!word.startsWith("-"))typed.push(word);else if(takesValue(word))at++;at++}let last=positionals.at(-1);if(typed.length<positionals.length)return{name:positionals[typed.length],typed};return{name:last?.replace("]","").endsWith("...")===!0?last:void 0,typed}}async function leafCandidates(run,words){let completing=await completingOf(run);if((words.at(-1)??"").startsWith("-"))return Object.entries(completing.options).map(([name,option])=>option.description===void 0?`--${name}`:`--${name} ${option.description}`);let flag=words.at(-2),option=flag?.startsWith("-")===!0?Object.entries(completing.options).find(([name,{short}])=>flag===`--${name}`||flag===`-${short}`)?.[1]:void 0,{name,typed}=positionalBeingTyped(words.slice(0,-1),completing);if(option?.type==="string"){let values=option.choices===void 0?await option.candidates?.(typed):option.choices;return values===void 0?[FILES]:values.map(candidateLine)}let values=name===void 0?void 0:await completing.candidates[name]?.(typed);return values===void 0?[FILES]:values.map(candidateLine)}async function candidates(scope,defaultCommand,words,before=[]){let[word="",...rest]=words,listing=rest.length===0&&!word.startsWith("-"),{commands}=scope,command=lookup(scope,word);if(listing||command===void 0){let expanded=await expand(scope,[...before,...words]);commands=expanded.commands,command=lookup(expanded,word)}if(listing){let own=await Promise.all(Object.entries(shown(commands)).map(async([name,{summary}])=>`${name} ${await resolveSummary(summary)}`)),fallback=defaultCommand===void 0?void 0:commands[defaultCommand],values=fallback!==void 0&&"run"in fallback?await leafCandidates(fallback.run,[word]):[],valueOf=(line)=>line.slice(0,line.includes("\t")?line.indexOf("\t"):void 0);return[...own,...values.filter((line)=>line!==FILES&&!Object.hasOwn(commands,valueOf(line)))]}if(command===void 0){let fallback=defaultCommand===void 0?void 0:commands[defaultCommand];return fallback!==void 0&&"run"in fallback?leafCandidates(fallback.run,words):[]}return"commands"in command?candidates(scopeOf(command.commands,command.extraCommands,command.aliases),void 0,rest,[...before,word]):leafCandidates(command.run,rest)}function flagValue([flag="",...rest]){return flag.includes("=")?[flag.slice(flag.indexOf("=")+1),...rest]:rest}function printCompletionScript(name,args,reportError){let shell=COMPLETION_SHELLS.find((each)=>each===args[0]);if(shell===void 0||args.length!==1)return reportError(name,`${COMPLETIONS} takes one of ${COMPLETIONS_SHELLS_LIST()}`,`${name} ${COMPLETIONS} fish`),2;return console.log(completionScript(shell,[name]).trimEnd()),0}function COMPLETIONS_SHELLS_LIST(){return COMPLETION_SHELLS.join(", ")}async function printCandidates(found){for(let line of await found)console.log(line);return 0}init_format2();init_mode();import process15 from"process";var NOTIFY_AFTER_MS=1e4,CANCELLED=130;function base64(text){return Buffer.from(text).toString("base64")}function sanitizeOsc(text){return text.replaceAll(/[\x00-\x1F\x7F;]/g," ")}function wrapTmux(codes,env){return codes.map((code)=>env.TMUX===void 0||env.TMUX===""?code:`\x1BPtmux;${code.replaceAll("\x1B","\x1B\x1B")}\x1B\\`).join("")}function notification(title,body,env=process15.env){let program=env.TERM_PROGRAM??"",term=env.TERM??"";if(program==="WezTerm"||term.startsWith("foot")||term.startsWith("rxvt"))return wrapTmux([`\x1B]777;notify;${sanitizeOsc(title)};${sanitizeOsc(body)}\x1B\\`],env);if(program==="iTerm.app"||env.WT_SESSION!==void 0&&env.WT_SESSION!=="")return wrapTmux([`\x1B]9;${sanitizeOsc(title)}: ${sanitizeOsc(body)}\x1B\\`],env);let id=`kit${process15.pid}`,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\\`];return wrapTmux(codes,env)}function notifyEnd(command,code,ms,{stream=process15.stderr,env=process15.env}={}){if(ms<NOTIFY_AFTER_MS||code===CANCELLED||outputMode(stream,env)!=="terminal")return;stream.write(notification(command,code===0?`done in ${formatDuration(ms)}`:`failed with exit ${code} after ${formatDuration(ms)}`,env))}init_style();init_text2();import{appendFileSync,mkdirSync,readFileSync as readFileSync5,renameSync,statSync as statSync2,writeFileSync}from"fs";import{homedir as homedir3}from"os";import{dirname as dirname2,join as join4}from"path";import process16 from"process";init_user_config();var CLI_FOLDER="kaynooo-cli";init_user_config();var MAX_USAGE_BYTES=2097152,UNKNOWN_OPTION2=/unknown option '(--[a-z][a-z0-9-]*)[=']/,FLAG_NAME=/^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/,LONGEST_NAME=40,usageError;function noteUsageError(message){usageError=message}function stateHome(env=process16.env){return xdgFolder(env.XDG_STATE_HOME,join4(homedir3(),".local","state"))}function usagePath(env=process16.env){return join4(stateHome(env),CLI_FOLDER,"usage.jsonl")}function usageRecorded(env=process16.env){let off=env.KAYNOOO_CLI_NO_USAGE;return env.NODE_ENV!=="test"&&(off===void 0||off===""||off==="0")}function flagNames(argv){let end=argv.indexOf("--"),names=(end===-1?argv:argv.slice(0,end)).filter((word)=>word.startsWith("-")&&word!=="-").map((word)=>word.includes("=")?word.slice(0,word.indexOf("=")):word);return[...new Set(names)].filter((name)=>name.length<=LONGEST_NAME&&FLAG_NAME.test(name))}function usageEntry(bin,command,argv,code,{ms,now=new Date}={}){let unknown=code===2&&usageError!==void 0?UNKNOWN_OPTION2.exec(usageError)?.[1]:void 0;return usageError=void 0,{at:now.toISOString(),bin,...command===void 0?{}:{command},flags:flagNames(argv),code,...unknown===void 0?{}:{unknown},...ms===void 0?{}:{ms:Math.round(ms)}}}function trimUsage(path,maxBytes){let info=statSync2(path,{throwIfNoEntry:!1});if(info===void 0||info.size<=maxBytes)return;let lines=readFileSync5(path,"utf8").split(`
|
|
75
|
+
`).filter(Boolean),kept=`${lines.slice(Math.floor(lines.length/2)).join(`
|
|
76
|
+
`)}
|
|
77
|
+
`,temp=`${path}.${process16.pid}.tmp`;writeFileSync(temp,kept,{mode:384}),renameSync(temp,path)}function recordUsage(entry,env=process16.env,maxBytes=MAX_USAGE_BYTES){if(!usageRecorded(env))return;try{let path=usagePath(env);mkdirSync(dirname2(path),{recursive:!0,mode:448}),appendFileSync(path,`${JSON.stringify(entry)}
|
|
78
|
+
`,{mode:384}),trimUsage(path,maxBytes)}catch{}}var LEVEL_OPTIONS={...OUTPUT_OPTIONS,help:{type:"boolean",short:"h",description:"show this help"}},TOP_OPTIONS={...LEVEL_OPTIONS,version:{type:"boolean",short:"v",description:"print the version"},completions:{type:"string",choices:COMPLETION_SHELLS,description:"print the shell completion script"}};async function commandRows(all,colors){let commands=shown(all),width=Math.max(0,...Object.keys(commands).map((name)=>name.length)),groups=new Map([["Commands:",[]]]),summaries=await Promise.all(Object.values(commands).map(async({summary})=>resolveSummary(summary)));for(let[index,[name,{group}]]of Object.entries(commands).entries()){let label=group===void 0?"Commands:":`${group}:`,rows=groups.get(label)??[];rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`),groups.set(label,rows)}return[...groups].filter(([,rows])=>rows.length>0).flatMap(([label,rows],index)=>[...index===0?[]:[""],colors.bold(label),...rows])}function takeOutputFlags(argv){let index=0;for(;index<argv.length;index++){let word=argv[index];if(word==="--plain")applyOutput(void 0,!0);else if(word.startsWith("--color="))applyOutput(word.slice(8),void 0);else if(word==="--color"&&argv[index+1]!==void 0)applyOutput(argv[++index],void 0);else break}return argv.slice(index)}async function help2({path,header,summary:lazySummary,commands,defaultCommand,examples,replaces},stream){let colors=paint(stream),prefix=path.join(" "),summary=await resolveSummary(lazySummary);if(wantsHelpJson())return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`,{examples,replaces}));let columns=takesControlCodes(stream)?stream.columns:void 0,fallback=defaultCommand===void 0?void 0:commands[defaultCommand],options=fallback!==void 0&&"run"in fallback?await optionsOf(fallback.run):void 0,own=Object.entries(options??{}).filter(([name])=>!(name in TOP_OPTIONS));return[header(colors,summary),"",usageLine(`${prefix} ${defaultCommand===void 0?colors.cyan("<command>"):`[${colors.cyan("<command>")}]`} [options]`,colors),"",...await commandRows(commands,colors),...own.length===0?[]:["",`${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`,...optionRows(Object.fromEntries(own),colors,columns)],"",colors.bold("Options:"),...optionRows(path.length===1?TOP_OPTIONS:LEVEL_OPTIONS,colors,columns),...exampleRows(examples??[],colors),"",`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`].join(`
|
|
79
|
+
`)}function printError(prefix,message,hint,cause){let colors=paint(process17.stderr),styled=takesControlCodes(process17.stderr),head=styled?`${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}`:`error: ${prefix}:`,under=(label,text,tint)=>text===void 0?"":`
|
|
80
|
+
${styled?tint(label):`${label}:`} ${text}`;console.error(`${head} ${message}${under("cause",cause,colors.dim)}${under("hint",hint,colors.yellow)}`)}function printJsonError(message,hint,cause){console.error(JSON.stringify({error:message,...hint===void 0?{}:{hint},...cause===void 0?{}:{cause}}))}function wantsJson(argv){let end=argv.indexOf("--");return(end===-1?argv:argv.slice(0,end)).includes("--json")}function reportThrown(prefix,error,redact=(text)=>text,json=!1){if(error instanceof HelpShown)return 0;let helpHint=error instanceof UsageError?`run ${prefix} --help for its options`:void 0,named=error instanceof Error&&!(error instanceof Exit)&&error.name!=="Error"?`${error.name}: ${error.message}`:void 0,cause=error instanceof Error&&error.cause instanceof Error?redact(error.cause.message):void 0;if(error instanceof Exit&&error.code===2)noteUsageError(error.message);return(json?printJsonError:(message,hint,causeText)=>printError(prefix,message,hint,causeText))(redact(named??(error instanceof Error?error.message:String(error))),error instanceof Exit?error.hint??helpHint:void 0,cause),error instanceof Exit?error.code:1}async function dispatch(level,typed,{version,redact}){let prefix=level.path.join(" "),argv;try{argv=takeOutputFlags(typed)}catch(error){return{code:reportThrown(prefix,error),meta:!1}}let[name,...args]=argv,fallback=level.defaultCommand===void 0?void 0:level.commands[level.defaultCommand];if(name===void 0&&level.runBare&&fallback!==void 0&&"run"in fallback)try{return{code:await fallback.run([]),meta:!1}}catch(error){return{code:reportThrown(`${prefix} ${level.defaultCommand}`,error,redact,!1),meta:error instanceof HelpShown}}if(name===void 0&&level.path.length>1)return console.error(await help2(await expand(level,[...level.path.slice(1),...argv]),process17.stderr)),{code:2,meta:!0};if(name==="help"&&args.length>0)return dispatch(level,[...args,"--help"],{version,redact});if(name===void 0||name==="help"||name==="--help"||name==="-h")return console.log(await help2(await expand(level,[...level.path.slice(1),...argv]),process17.stdout)),{code:0,meta:!0};if(level.path.length===1&&(name==="--version"||name==="-v"))return console.log(version()),{code:0,meta:!0};let command=lookup(level,name),rest=args,ran=name;if(command===void 0&&level.lazy.length>0)level=await expand(level,[...level.path.slice(1),...argv]),command=lookup(level,name);if(command===void 0&&level.defaultCommand!==void 0)command=level.commands[level.defaultCommand],rest=argv,ran=level.defaultCommand;if(command===void 0){let meant=closest(name,Object.keys(shown(level.commands)));return printError(prefix,`no command ${name}`,meant===void 0?`run ${prefix} --help for its commands`:`did you mean ${meant}?`),{code:2,meta:!1}}if("commands"in command){let{summary}=command;return dispatch({path:[...level.path,name],header:(colors,text)=>`${colors.bold(`${prefix} ${name}`)} ${text}`,summary,...scopeOf(command.commands,command.extraCommands,command.aliases),defaultCommand:void 0,runBare:!1,examples:command.examples,replaces:void 0},rest,{version,redact})}try{return{code:await command.run(rest),meta:!1}}catch(error){return{code:reportThrown(`${prefix} ${ran}`,error,redact,wantsJson(rest)),meta:error instanceof HelpShown}}}function packageVersion(entry=Bun.main){let resolved=entry;try{resolved=realpathSync2(entry)}catch{}for(let dir=dirname3(resolved);;dir=dirname3(dir)){try{let{version}=JSON.parse(readFileSync6(join5(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname3(dir)===dir)return"0.0.0"}}async function runCli(cli,argv=scriptArgs()){let answered=await askpassClient(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(candidates(scopeOf(cli.commands,cli.extraCommands,cli.aliases),cli.defaultCommand,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(cli.name,flagValue(argv),printError);let version=()=>cli.version??packageVersion(),started=performance.now(),{code,meta}=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===!0,examples:cli.examples,replaces:cli.replaces},argv,{version,redact:cli.redact}),command=commandPath(scopeOf(cli.commands,cli.extraCommands,cli.aliases),argv);if(notifyEnd(command===void 0?cli.name:`${cli.name} ${command}`,code,performance.now()-started),cli.usage!==!1&&!meta)try{recordUsage(usageEntry(cli.name,command,argv,code,{ms:performance.now()-started}))}catch{}return code}function commandPath(scope,argv){let path=[],level=scope;for(let word of argv.filter((each)=>!each.startsWith("-"))){let command=lookup(level,word);if(command===void 0)break;if(path.push(word),!("commands"in command))break;level=scopeOf(command.commands,command.extraCommands,command.aliases)}return path.length===0?void 0:path.join(" ")}init_config();init_text2();init_folders();init_format2();init_args();init_args();init_mode();async function pool(items,limit,task,onDone){let results=Array.from({length:items.length}),next=0,done=0;async function worker(){while(next<items.length){let index=next++;results[index]=await task(items[index]),onDone?.(++done,items.length)}}return await Promise.all(Array.from({length:Math.min(limit,items.length)},worker)),results}init_style();init_text2();var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");var SIZE=/^(\d+(?:\.\d+)?)\s*(?:([kmgt])i?b?|(b))?$/i,POWERS={"":0,k:1,m:2,g:3,t:4};function parseSize(text,bareUnit=1){let match=SIZE.exec(text.trim());if(match===null)return;let suffix=match[2]?.toLowerCase(),unit=bareUnit;if(match[3]!==void 0)unit=1;else if(suffix!==void 0)unit=1024**POWERS[suffix];return Math.round(Number(match[1])*unit)}init_style();init_text2();init_theme();init_user_config();init_args();init_input();init_style();import process18 from"process";import{format}from"util";var CLEAR_SCREEN="\x1B[H\x1B[2J",DEFAULT_SECONDS=2,ATTACHED_SHORT=/^-w./,INTERVAL=/^\d+(?:\.\d+)?(?:ms|[smh])?$/;function watchOption(what){return{type:"string",short:"w",optional:{bare:"",accepts:INTERVAL},description:`redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c`}}function withoutWatch(args){let rest=[];for(let at=0;at<args.length;at++){let arg=args[at];if(arg==="--watch"||arg==="-w"){if(args[at+1]!==void 0&&INTERVAL.test(args[at+1]))at++}else if(!arg.startsWith("--watch=")&&!ATTACHED_SHORT.test(arg))rest.push(arg)}return rest}async function watching(value,step,stream=process18.stdout,sleep=Bun.sleep,rounds=Number.POSITIVE_INFINITY){let interval=value===""?DEFAULT_SECONDS*1000:duration(value,"watch",DEFAULT_SECONDS*1000);if(!takesControlCodes(stream))badUsage("--watch redraws the screen, so it needs a terminal");let code=0;for(let round=0;round<rounds;round++){let held=[],{log,info}=console,write=process18.stdout.write.bind(process18.stdout),hold=(...parts)=>void held.push(`${format(...parts)}
|
|
81
|
+
`);console.log=hold,console.info=hold,process18.stdout.write=(text)=>(held.push(typeof text==="string"?text:Buffer.from(text).toString()),!0);try{code=await step()}finally{console.log=log,console.info=info,process18.stdout.write=write}stream.write(`${CLEAR_SCREEN}${held.join("")}`),await sleep(interval)}return code}init_user_config();import{homedir as homedir4}from"os";import{dirname as dirname4,join as join6,resolve as resolve4}from"path";import process19 from"process";function expandHome(path,home){if(path==="~")return home;return path.startsWith("~/")?join6(home,path.slice(2)):path}function configured(env,home){let folder=readUserConfig("config",{home,xdg:env.XDG_CONFIG_HOME}).workspace;return typeof folder==="string"&&folder!==""?folder:void 0}function workspaceRoot({given,env=process19.env,home=homedir4()}={}){let fromEnv=env.KAYNOOO_WORKSPACE===""?void 0:env.KAYNOOO_WORKSPACE;return resolve4(expandHome(given??fromEnv??configured(env,home)??join6(home,"Workspace"),home))}import{existsSync as existsSync6,readdirSync,readFileSync as readFileSync9,statSync as statSync3}from"fs";import{readdir}from"fs/promises";import{join as join9,relative,resolve as resolve5}from"path";import process21 from"process";import{existsSync as existsSync5,readFileSync as readFileSync8}from"fs";import{join as join8}from"path";import{existsSync as existsSync4,readFileSync as readFileSync7}from"fs";import{join as join7}from"path";var UPPER_BOUND=/<\s*(\d[\w.+-]*)/,DEPENDENCY_KINDS=["dependencies","devDependencies","optionalDependencies","peerDependencies"],GHSA=/GHSA-[\w-]+$/;function parseAudit(text){try{let parsed=JSON.parse(text);return typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:void 0}catch{return}}function fixedAt(range){let bounds=range.split("||").map((part)=>UPPER_BOUND.exec(part)?.[1]);if(bounds.length===0||bounds.includes(void 0))return;return bounds.reduce((highest,bound)=>Bun.semver.order(bound,highest)>0?bound:highest)}function fixFor(advisories){let fixes=advisories.map((advisory)=>fixedAt(advisory.vulnerable_versions));if(fixes.length===0||fixes.includes(void 0))return;return fixes.reduce((highest,fix)=>Bun.semver.order(fix,highest)>0?fix:highest)}function findingsOf(audit,reaching,direct,level,ignore=[],via=new Map){let found=[];for(let[name,all]of Object.entries(audit)){let kept=all.filter((advisory)=>severityRank(advisory.severity)>=severityRank(level)&&!isIgnored({id:advisory.id,ghsa:GHSA.exec(advisory.url)?.[0]},ignore));if(kept.length===0)continue;let advisories=kept.map((advisory)=>({id:advisory.id,ghsa:GHSA.exec(advisory.url)?.[0],url:advisory.url,title:advisory.title,severity:advisory.severity,fixed:fixedAt(advisory.vulnerable_versions)}));found.push({package:name,severity:advisories.reduce((worst,advisory)=>severityRank(advisory.severity)>severityRank(worst)?advisory.severity:worst,advisories[0].severity),advisories,scope:reaching.has(name)?"prod":"dev",direct:direct.has(name),via:direct.has(name)?[]:via.get(name)??[],fix:fixFor(kept)})}return found.toSorted((a,b)=>severityRank(b.severity)-severityRank(a.severity)||Number(b.scope==="prod")-Number(a.scope==="prod")||a.package.localeCompare(b.package))}function lockGraph(lockText){let graph=new Map,lock;try{lock=Bun.JSONC.parse(lockText)}catch{return graph}for(let entry of Object.values(lock?.packages??{})){let resolution=entry[0],info=entry[2];if(typeof resolution!=="string"||typeof info!=="object"||info===null)continue;let at=resolution.indexOf("@",1),name=at===-1?resolution:resolution.slice(0,at),wanted=DEPENDENCY_KINDS.flatMap((kind)=>Object.keys(info[kind]??{}));graph.set(name,[...new Set([...graph.get(name)??[],...wanted])])}return graph}function reachedFrom(graph,direct,targets){let from=new Map;for(let start of direct){let seen=new Set([start]),queue=[start];for(let name=queue.shift();name!==void 0;name=queue.shift()){if(name!==start&&targets.has(name))from.set(name,[...from.get(name)??[],start]);for(let next of graph.get(name)??[])if(!seen.has(next))seen.add(next),queue.push(next)}}return new Map([...from].map(([name,starts])=>[name,starts.toSorted()]))}function readManifest(path){try{return existsSync4(path)?JSON.parse(readFileSync7(path,"utf8")):{}}catch{return{}}}function namesIn(manifest){return DEPENDENCY_KINDS.flatMap((kind)=>{let section=manifest[kind];return typeof section==="object"&§ion!==null?Object.keys(section):[]})}function directDependencies(root,workspaces){let names=new Set(namesIn(readManifest(join7(root,"package.json"))));for(let workspace of workspaces)for(let name of namesIn(readManifest(join7(root,workspace,"package.json"))))names.add(name);return names}function workspacePatterns(field){if(Array.isArray(field))return field;let packages=typeof field==="object"&&field!==null?field.packages:void 0;return Array.isArray(packages)?packages:[]}function workspaceFolders(root,children){return workspacePatterns(readManifest(join7(root,"package.json")).workspaces).filter((pattern)=>typeof pattern==="string").flatMap((pattern)=>pattern.endsWith("/*")?children(pattern.slice(0,-2)).map((name)=>join7(pattern.slice(0,-2),name)):[pattern])}var OSV="https://api.osv.dev/v1",BATCH=1000,DETAIL_CONCURRENCY=8,TIMEOUT_MS=20000,PACKAGE_BLOCK=/^\[\[package\]\]\s*$/m,FIELD=/^(name|version|source) = (.+)$/gm,QUOTED=/^"([^"]*)"$/,LEADING_V=/^v/;function parseComposerLock(text){let lock=JSON.parse(text),entry=(prod)=>(each)=>({name:each.name,version:each.version.replace(LEADING_V,""),prod});return[...(lock.packages??[]).map(entry(!0)),...(lock["packages-dev"]??[]).map(entry(!1))]}function tomlPackages(text,fromRegistry){let found=[];for(let block of text.split(PACKAGE_BLOCK).slice(1)){let fields=new Map;for(let[,key,value]of block.matchAll(FIELD))fields.set(key,QUOTED.exec(value.trim())?.[1]??value.trim());let source=fields.get("source"),name=fields.get("name"),version=fields.get("version");if(name!==void 0&&version!==void 0&&source!==void 0&&fromRegistry(source))found.push({name,version,prod:!0})}return found}function parseCargoLock(text){return tomlPackages(text,(source)=>source.startsWith("registry+"))}function parseUvLock(text){return tomlPackages(text,(source)=>source.includes("registry"))}var ECOSYSTEMS=[{lockfile:"composer.lock",osv:"Packagist",parse:parseComposerLock},{lockfile:"Cargo.lock",osv:"crates.io",parse:parseCargoLock},{lockfile:"uv.lock",osv:"PyPI",parse:parseUvLock}];function holdsOsvLock(dir){return ECOSYSTEMS.some((each)=>existsSync5(join8(dir,each.lockfile)))}var SEVERITY_NAMES={LOW:"low",MODERATE:"moderate",MEDIUM:"moderate",HIGH:"high",CRITICAL:"critical"};async function ok2(response){if(!response.ok)throw Error(`osv.dev answered ${response.status}`);return response.json()}function rowOf(vuln,name){let fixes=(vuln.affected??[]).filter((each)=>each.package?.name===name).flatMap((each)=>each.ranges??[]).flatMap((range)=>range.events??[]).map((event)=>event.fixed).filter((fixed)=>fixed!==void 0);return{id:0,ghsa:vuln.id,url:`https://osv.dev/vulnerability/${vuln.id}`,title:vuln.summary??vuln.id,severity:SEVERITY_NAMES[vuln.database_specific?.severity?.toUpperCase()??""]??"moderate",fixed:fixes.length===0?void 0:fixedAt(fixes.map((fix)=>`<${fix}`).join(" || "))}}async function osvFindings(locked,ecosystem,direct,level,ignore,fetcher=fetch){let hits=new Map;for(let start=0;start<locked.length;start+=BATCH){let chunk=locked.slice(start,start+BATCH),queries=chunk.map((each)=>({package:{name:each.name,ecosystem},version:each.version})),answer=await ok2(await fetcher(`${OSV}/querybatch`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({queries}),signal:AbortSignal.timeout(TIMEOUT_MS)}));for(let[index,each]of chunk.entries()){let ids=(answer.results[index]?.vulns??[]).map((vuln)=>vuln.id).filter((id)=>!ignore.includes(id));if(ids.length>0)hits.set(each,ids)}}let details=new Map;await pool([...new Set([...hits.values()].flat())],DETAIL_CONCURRENCY,async(id)=>{details.set(id,await ok2(await fetcher(`${OSV}/vulns/${encodeURIComponent(id)}`,{signal:AbortSignal.timeout(TIMEOUT_MS)})))});let findings=[],below=0;for(let[each,ids]of hits){let rows=ids.map((id)=>rowOf(details.get(id),each.name)),advisories=rows.filter((row)=>severityRank(row.severity)>=severityRank(level));if(below+=rows.length-advisories.length,advisories.length===0)continue;let fixes=advisories.map((row)=>row.fixed);findings.push({package:each.name,severity:advisories.reduce((worst,row)=>severityRank(row.severity)>severityRank(worst)?row.severity:worst,advisories[0].severity),advisories,scope:each.prod?"prod":"dev",direct:direct.has(each.name),via:[],fix:fixes.includes(void 0)?void 0:fixes.reduce((highest,fix)=>Bun.semver.order(fix,highest)>0?fix:highest)})}return{findings:findings.toSorted((a,b)=>severityRank(b.severity)-severityRank(a.severity)||Number(b.scope==="prod")-Number(a.scope==="prod")||a.package.localeCompare(b.package)),below}}function manifestNames(dir){try{let manifest=JSON.parse(readFileSync8(join8(dir,"composer.json"),"utf8"));return new Set([...Object.keys(manifest.require??{}),...Object.keys(manifest["require-dev"]??{})])}catch{return new Set}}async function osvAudit(dir,level,ignore,fetcher=fetch){let all={findings:[],below:0};for(let each of ECOSYSTEMS.filter((each)=>existsSync5(join8(dir,each.lockfile)))){let done=await osvFindings(each.parse(readFileSync8(join8(dir,each.lockfile),"utf8")),each.osv,each.lockfile==="composer.lock"?manifestNames(dir):new Set,level,ignore,fetcher);all.findings.push(...done.findings),all.below+=done.below}return all}var USAGE="ws audit [options] [root]: the known vulnerabilities of the Bun, Composer, Cargo and uv repositories under root (the current folder by default), one table per repository\n\nEach package with an advisory is one row: its worst severity, advisory count, prod or dev, direct or via the direct dependencies leading to it, and the version that fixes every advisory at once.\nIt reaches the network: `bun audit --json` for a bun.lock, osv.dev for a composer.lock, Cargo.lock or uv.lock; the walk goes three levels deep and stops at a lockfile.\nTo sweep many repositories at once; `pkg audit` vets the one repository in depth.",EXITS=[[0,"no repository has an advisory at the level asked"],[1,"one has"],[2,"a repository's audit failed, no lockfile sits under root, a usage error or a root that is no folder"]],OPTIONS={level:{type:"string",choices:SEVERITIES,default:"moderate",description:"only the advisories at least this severe: low, moderate, high or critical"},prod:{type:"boolean",description:"only the packages a production dependency needs"},ignore:{type:"string",multiple:!0,description:"an advisory skipped by GHSA or numeric id, repeatable"},json:jsonOption("[{repo, path, findings: [{package, severity, scope, direct, via, fix, advisories: [{id, ghsa, url, title, severity, fixed}]}], below: advisories under --level, warnings: what bun audit could not audit, error}]")},MAX_DEPTH=3,CONCURRENCY=4,AUDIT_MS=60000,WARNING=/^warn: .+$/gm,VIA_SHOWN=2;function countAdvisories(findings){return findings.reduce((sum,found)=>sum+found.advisories.length,0)}function holdsBunLock(dir){return existsSync6(join9(dir,"bun.lock"))||existsSync6(join9(dir,"bun.lockb"))}function holdsLock(dir){return holdsBunLock(dir)||holdsOsvLock(dir)}async function findRepos(root){if(holdsLock(root))return[root];let found=[];async function walk(dir,depth){let entries;try{entries=await readdir(dir,{withFileTypes:!0})}catch{return}for(let entry of entries.toSorted((a,b)=>a.name.localeCompare(b.name))){if(!entry.isDirectory()||entry.name==="node_modules"||entry.name.startsWith("."))continue;let path=join9(dir,entry.name);if(holdsLock(path))found.push(path);else if(depth<MAX_DEPTH)await walk(path,depth+1)}}return await walk(root,1),found}function children(root){return(folder)=>{try{return readdirSync(join9(root,folder),{withFileTypes:!0}).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort()}catch{return[]}}}async function audited(path,shown,level,ignore){let bun=holdsBunLock(path)?await bunAudited(path,shown,level,ignore):{repo:shown,path,findings:[],below:0,warnings:[],error:void 0};if(bun.error!==void 0||!holdsOsvLock(path))return bun;try{let osv=await osvAudit(path,level,ignore);return{...bun,findings:[...bun.findings,...osv.findings],below:bun.below+osv.below}}catch(error){return{...bun,error:`osv.dev: ${error instanceof Error?error.message:String(error)}`}}}async function bunAudited(path,shown,level,ignore){let[all,production]=await Promise.all([runCommand(["bun","audit","--json"],{cwd:path,timeoutMs:AUDIT_MS}),runCommand(["bun","audit","--json","--prod"],{cwd:path,timeoutMs:AUDIT_MS})]),audit=parseAudit(all.stdout),reached=parseAudit(production.stdout);if(audit===void 0||reached===void 0)return{repo:shown,path,findings:[],below:0,warnings:[],error:failure(audit===void 0?all:production)};let reaching=new Set(Object.keys(reached)),direct=directDependencies(path,workspaceFolders(path,children(path))),via=reachedFrom(lockGraph(lockText(path)),direct,new Set(Object.keys(audit))),findings=findingsOf(audit,reaching,direct,level,ignore,via);return{repo:shown,path,findings,below:countAdvisories(findingsOf(audit,reaching,direct,"low",ignore))-countAdvisories(findings),warnings:[...new Set(all.text.match(WARNING)??[])],error:void 0}}function lockText(path){try{return readFileSync9(join9(path,"bun.lock"),"utf8")}catch{return""}}function originOf(found){if(found.direct)return"direct";if(found.via.length===0)return"via";return`via ${found.via.slice(0,VIA_SHOWN).join(", ")}${found.via.length>VIA_SHOWN?` +${found.via.length-VIA_SHOWN}`:""}`}function failure(ran){return ran.timedOut?`timed out after ${AUDIT_MS/1000}s`:ran.text.trim().split(`
|
|
82
|
+
`).at(-1)??`exit ${ran.code}`}function tint(severity){let colors=paint(process21.stdout);if(severity==="critical"||severity==="high")return colors.red;return severity==="moderate"?colors.yellow:colors.dim}function rows(findings){return findings.map((found)=>[found.package,tint(found.severity)(found.severity),String(found.advisories.length),found.scope,originOf(found),found.fix??"-"])}async function audit(args){let{values,positionals}=parse(args,USAGE,OPTIONS,{positionals:["[root]"],exits:EXITS,replaces:"a bun audit run in each repository and a read of every advisory to find what is worth fixing",examples:["ws audit","ws audit ~/Workspace --level high --prod"]}),root=resolve5(positionals[0]??".");if(!existsSync6(root)||!statSync3(root).isDirectory())fail(`no folder ${root}`);let level=oneOf(values.level,"level",SEVERITIES),progress=progressLine(),audits;try{progress.update({step:"finding the repositories"});let paths=await findRepos(root);if(paths.length===0)fail(`no bun.lock, composer.lock, Cargo.lock or uv.lock under ${root}`);progress.update({step:"auditing",done:0,total:paths.length,unit:"repositories"}),audits=await pool(paths,configuredNumber("audit","concurrency",CONCURRENCY),async(path)=>audited(path,relative(root,path)||".",level,values.ignore??[]),(done,total)=>progress.update({step:"auditing",done,total,unit:"repositories"}))}finally{progress.stop()}let kept=audits.map((each)=>({...each,findings:values.prod===!0?each.findings.filter((found)=>found.scope==="prod"):each.findings}));if(values.json===!0)printJson(kept);else show(kept,audits.length);if(kept.some((each)=>each.error!==void 0))return 2;return kept.some((each)=>each.findings.length>0)?1:0}function show(audits,total){printHeader("ws",`audit \xB7 ${total} ${total===1?"repository":"repositories"}`);let label=role("label",process21.stdout),path=role("path",process21.stdout),flagged=audits.filter((each)=>each.error!==void 0||each.findings.length>0);if(flagged.length===0){console.log(label(`no advisory in ${total} ${total===1?"repository":"repositories"}`));return}for(let each of flagged){if(console.log(`${path(each.repo)} ${label(each.error===void 0?`${each.findings.length} ${each.findings.length===1?"package":"packages"}`:`audit failed: ${each.error}`)}`),each.findings.length>0)console.log(table([["package","severity","advisories","scope","origin","fix"],...rows(each.findings)],{header:!0,align:["left","left","right","left","left","left"]}));if(each.findings.some((found)=>!found.direct))console.log(label("via: a dependency of the ones named, fixed by upgrading one of them to a release that depends on the fixed version"));if(each.below>0)console.log(label(`${each.below} ${each.below===1?"advisory":"advisories"} below the level left out, --level low lists them`));for(let warning of each.warnings)console.log(label(warning))}}import{existsSync as existsSync8,statSync as statSync4}from"fs";import{basename as basename2,relative as relative2}from"path";import process23 from"process";import{existsSync as existsSync7}from"fs";import{readdir as readdir2}from"fs/promises";import{basename,join as join10}from"path";import process22 from"process";var MAX_DEPTH2=3,CONCURRENCY2=8,PACKAGE_CONCURRENCY=4,GIT_MS=1e4,FETCH_MS=30000,AHEAD_BEHIND=/\+(\d+) -(\d+)/,PACKAGE_TAG=/^(.+)-v\d/,REASONS=["dirty","unpushed","unreleased","behind"];function reasonsOf(repo){let reasons=[];if(repo.dirty>0)reasons.push("dirty");if((repo.ahead??0)>0)reasons.push("unpushed");if((repo.behind??0)>0)reasons.push("behind");if((repo.unreleased??0)>0)reasons.push("unreleased");return reasons}async function findRepos2(root,skip){if(existsSync7(join10(root,".git")))return[root];let found=[];async function walk(dir,depth){let entries;try{entries=await readdir2(dir,{withFileTypes:!0})}catch{return}for(let entry of entries.toSorted((a,b)=>a.name.localeCompare(b.name))){if(!entry.isDirectory()||entry.name==="node_modules"||entry.name.startsWith(".")||skip.has(entry.name))continue;let path=join10(dir,entry.name);if(existsSync7(join10(path,".git")))found.push(path);else if(depth<MAX_DEPTH2)await walk(path,depth+1)}}return await walk(root,1),found}async function read(path,args,timeoutMs=GIT_MS){try{let ran=await runCommand(["git","--no-optional-locks",...args],{cwd:path,env:{...process22.env,GIT_TERMINAL_PROMPT:"0"},timeoutMs});return ran.code===0&&!ran.timedOut?ran.stdout.trim():void 0}catch{return}}async function commitsSince(path,tag,folder){let count=await read(path,["rev-list","--count",`${tag}..HEAD`,...folder===void 0?[]:["--",folder]]);return Number(count??0)}async function packageReleases(path){let names=new Set;for(let tag of(await read(path,["tag","--list"])??"").split(`
|
|
83
|
+
`)){let name=PACKAGE_TAG.exec(tag)?.[1];if(name!==void 0)names.add(name)}return(await pool([...names].toSorted(),PACKAGE_CONCURRENCY,async(name)=>{let folder=[join10("packages",name),name].find((candidate)=>existsSync7(join10(path,candidate))),tag=folder===void 0?void 0:await read(path,["describe","--tags","--abbrev=0","--match",`${name}-v*`]);return folder!==void 0&&tag!==void 0&&tag!==""?{name,tag,unreleased:await commitsSince(path,tag,folder)}:void 0})).filter((release)=>release!==void 0)}async function inspect(path,fetch2){let fetched=fetch2?await read(path,["fetch","--quiet"],FETCH_MS):"",[status,worktrees,packages]=await Promise.all([read(path,["status","--porcelain=v2","--branch"]),read(path,["worktree","list","--porcelain"]),packageReleases(path)]),state={name:basename(path),path,branch:"?",upstream:null,dirty:0,ahead:null,behind:null,worktrees:0,tag:null,unreleased:null,packages,fetchFailed:fetched===void 0,unreadable:status===void 0};for(let line of(status??"").split(`
|
|
84
|
+
`))if(line.startsWith("# branch.head "))state.branch=line.slice(14);else if(line.startsWith("# branch.upstream "))state.upstream=line.slice(18);else if(line.startsWith("# branch.ab "))[state.ahead,state.behind]=AHEAD_BEHIND.exec(line)?.slice(1).map(Number);else if(line!==""&&!line.startsWith("#"))state.dirty++;if(state.worktrees=Math.max(0,(worktrees??"").split(`
|
|
85
|
+
`).filter((line)=>line.startsWith("worktree ")).length-1),packages.length>0)state.unreleased=packages.reduce((sum,release)=>sum+release.unreleased,0);else{let tag=await read(path,["describe","--tags","--abbrev=0"]);if(tag!==void 0&&tag!=="")state.tag=tag,state.unreleased=await commitsSince(path,tag)}return state}function pullBlocker(repo){if(repo.unreadable)return"unreadable";if(repo.fetchFailed)return"fetch failed";if(repo.branch==="(detached)")return"detached HEAD";if(repo.upstream===null)return"no upstream";if(repo.dirty>0)return`${repo.dirty} dirty ${repo.dirty===1?"file":"files"}`;return(repo.ahead??0)>0?`diverged, ${repo.ahead} ahead`:void 0}function firstLine(text){let end=text.indexOf(`
|
|
86
|
+
`);return end===-1?text:text.slice(0,end)}async function fastForward(path){try{let ran=await runCommand(["git","--no-optional-locks","merge","--ff-only","--quiet","@{upstream}"],{cwd:path,env:{...process22.env,GIT_TERMINAL_PROMPT:"0"},timeoutMs:GIT_MS});if(ran.timedOut)return"timed out";return ran.code===0?void 0:firstLine(ran.text.trim())||`exit ${ran.code}`}catch(error){return error instanceof Error?error.message:String(error)}}var USAGE2=`ws repos [options] [root]: the git repositories under root (the configured workspace by default) that need attention: dirty files, commits not pushed, an upstream ahead, commits since the latest tag
|
|
2853
87
|
|
|
2854
88
|
A clean repository, or one with only unreleased commits, is left out unless --all or --only unreleased. The walk goes ${MAX_DEPTH2} levels deep and skips the names in "skip" of \`~/.config/kaynooo-cli/repos.json\`; ahead and behind are those of the last fetch unless --fetch reaches the remote.
|
|
2855
|
-
--pull fetches, then fast-forwards only the repositories listed that are clean, on a branch and only behind their upstream; the others are reported as skipped.`;
|
|
2856
|
-
var EXITS2 = [[0, "it listed the repositories, including when none needs attention"], [1, "a fast-forward --pull attempted failed"], [2, "a usage error, an unreadable config or a root that is no folder"]];
|
|
2857
|
-
var OPTIONS2 = {
|
|
2858
|
-
all: { type: "boolean", short: "a", description: "list the repositories with nothing to report too" },
|
|
2859
|
-
only: { type: "string", multiple: true, choices: REASONS, description: "only the repositories with this reason: dirty, unpushed, unreleased or behind, repeatable" },
|
|
2860
|
-
watch: watchOption("the repositories"),
|
|
2861
|
-
fetch: { type: "boolean", conflicts: ["watch"], description: "refresh the upstreams first (reaches the remote)" },
|
|
2862
|
-
pull: { type: "boolean", conflicts: ["watch"], description: "fetch, then fast-forward the clean repositories listed that are only behind their upstream (reaches the remote)" },
|
|
2863
|
-
path: { type: "boolean", conflicts: ["json"], description: "print only the paths of the repositories listed, one per line" },
|
|
2864
|
-
json: jsonOption("[{name, path, branch, upstream, dirty, ahead, behind, worktrees, tag, unreleased, packages, reasons, fetchFailed, unreadable}]")
|
|
2865
|
-
};
|
|
2866
|
-
async function skipped() {
|
|
2867
|
-
const file = userConfigReadPath("repos");
|
|
2868
|
-
if (!existsSync8(file))
|
|
2869
|
-
return new Set;
|
|
2870
|
-
try {
|
|
2871
|
-
const config = await Bun.file(file).json();
|
|
2872
|
-
return new Set(Array.isArray(config.skip) ? config.skip.filter((name) => typeof name === "string") : []);
|
|
2873
|
-
} catch (error) {
|
|
2874
|
-
fail(`${file} does not parse: ${error instanceof Error ? error.message : String(error)}`);
|
|
2875
|
-
}
|
|
2876
|
-
}
|
|
2877
|
-
function releasedCell(repo) {
|
|
2878
|
-
if (repo.packages.length > 0)
|
|
2879
|
-
return repo.packages.filter((release) => release.unreleased > 0).map((release) => `${release.name} ${release.unreleased}`).join(", ") || "-";
|
|
2880
|
-
return repo.tag === null || repo.unreleased === 0 ? "-" : `${repo.unreleased} since ${repo.tag}`;
|
|
2881
|
-
}
|
|
2882
|
-
function syncCell(repo, stream = process23.stdout) {
|
|
2883
|
-
const colors = paint(stream);
|
|
2884
|
-
const ahead = repo.ahead ?? 0;
|
|
2885
|
-
const behind = repo.behind ?? 0;
|
|
2886
|
-
if (repo.upstream === null)
|
|
2887
|
-
return colors.dim("no upstream");
|
|
2888
|
-
const parts = [ahead > 0 ? colors.green(`+${ahead}`) : "", behind > 0 ? colors.red(`-${behind}`) : ""].filter(Boolean);
|
|
2889
|
-
const diverged = takesControlCodes(stream) && ahead > 0 && behind > 0;
|
|
2890
|
-
return parts.length === 0 ? colors.dim("-") : `${parts.join(" ")}${diverged ? colors.yellow(" diverged") : ""}`;
|
|
2891
|
-
}
|
|
2892
|
-
var DEFAULT_BRANCHES = new Set(["main", "master"]);
|
|
2893
|
-
function branchCell(repo, stream = process23.stdout) {
|
|
2894
|
-
const colors = paint(stream);
|
|
2895
|
-
if (repo.unreadable)
|
|
2896
|
-
return colors.red("? (unreadable)");
|
|
2897
|
-
if (repo.branch === "(detached)")
|
|
2898
|
-
return colors.yellow(repo.branch);
|
|
2899
|
-
return DEFAULT_BRANCHES.has(repo.branch) ? repo.branch : role("accent", stream)(repo.branch);
|
|
2900
|
-
}
|
|
2901
|
-
function row(repo, shown) {
|
|
2902
|
-
const colors = paint(process23.stdout);
|
|
2903
|
-
const tint = role("path", process23.stdout);
|
|
2904
|
-
const unreleased = releasedCell(repo);
|
|
2905
|
-
return [
|
|
2906
|
-
tint(shown),
|
|
2907
|
-
branchCell(repo),
|
|
2908
|
-
repo.dirty === 0 ? colors.dim("-") : colors.yellow(String(repo.dirty)),
|
|
2909
|
-
syncCell(repo),
|
|
2910
|
-
repo.worktrees === 0 ? colors.dim("-") : String(repo.worktrees),
|
|
2911
|
-
unreleased === "-" ? colors.dim("-") : colors.cyan(unreleased)
|
|
2912
|
-
];
|
|
2913
|
-
}
|
|
2914
|
-
async function repos(args, watched = false) {
|
|
2915
|
-
const { values, positionals } = parse(args, USAGE2, OPTIONS2, { positionals: ["[root]"], exits: EXITS2, replaces: "a cd, git status, git log and git tag loop over each repository of the workspace", examples: ["ws repos", "ws repos ~/Workspace --only unreleased --fetch", ["ws repos --only behind --pull", "fast-forward what is behind and clean"], ["ws repos --only dirty --path", "the paths, for xargs"]] });
|
|
2916
|
-
if (values.watch !== undefined)
|
|
2917
|
-
return watching(values.watch, async () => repos(withoutWatch(args), true));
|
|
2918
|
-
const root = workspaceRoot({ given: positionals[0] });
|
|
2919
|
-
if (!existsSync8(root) || !statSync3(root).isDirectory())
|
|
2920
|
-
fail(`no folder ${root}`);
|
|
2921
|
-
const only = values.only ?? [];
|
|
2922
|
-
const progress = watched ? undefined : progressLine();
|
|
2923
|
-
const fetching = values.fetch === true || values.pull === true;
|
|
2924
|
-
const step = fetching ? "fetching" : "reading";
|
|
2925
|
-
let states;
|
|
2926
|
-
try {
|
|
2927
|
-
progress?.update({ step: "finding the repositories" });
|
|
2928
|
-
const paths = await findRepos2(root, await skipped());
|
|
2929
|
-
progress?.update({ step, done: 0, total: paths.length, unit: "repositories" });
|
|
2930
|
-
states = await pool(paths, configuredNumber("repos", "concurrency", CONCURRENCY2), async (path) => inspect(path, fetching), (done, total) => progress?.update({ step, done, total, unit: "repositories" }));
|
|
2931
|
-
} finally {
|
|
2932
|
-
progress?.stop();
|
|
2933
|
-
}
|
|
2934
|
-
const keeps = (repo) => {
|
|
2935
|
-
const reasons = reasonsOf(repo);
|
|
2936
|
-
if (only.length > 0)
|
|
2937
|
-
return reasons.some((reason) => only.includes(reason));
|
|
2938
|
-
return values.all === true || reasons.some((reason) => reason !== "unreleased") || repo.unreadable;
|
|
2939
|
-
};
|
|
2940
|
-
let failedPulls = 0;
|
|
2941
|
-
if (values.pull === true) {
|
|
2942
|
-
const log = values.json === true || values.path === true ? console.error : console.log;
|
|
2943
|
-
for (const [index, repo] of states.entries()) {
|
|
2944
|
-
if (!keeps(repo) || (repo.behind ?? 0) === 0)
|
|
2945
|
-
continue;
|
|
2946
|
-
const blocker = pullBlocker(repo);
|
|
2947
|
-
const refused = blocker === undefined ? await fastForward(repo.path) : undefined;
|
|
2948
|
-
if (blocker !== undefined) {
|
|
2949
|
-
log(marked("note", `${repo.name} skipped`, process23.stdout, blocker));
|
|
2950
|
-
} else if (refused !== undefined) {
|
|
2951
|
-
failedPulls++;
|
|
2952
|
-
log(marked("problem", `${repo.name} not pulled`, process23.stdout, refused));
|
|
2953
|
-
} else {
|
|
2954
|
-
log(marked("ok", `${repo.name} pulled`, process23.stdout, `${repo.behind} ${repo.behind === 1 ? "commit" : "commits"}`));
|
|
2955
|
-
states[index] = await inspect(repo.path, false);
|
|
2956
|
-
}
|
|
2957
|
-
}
|
|
2958
|
-
}
|
|
2959
|
-
const kept = states.filter(keeps);
|
|
2960
|
-
if (values.path === true) {
|
|
2961
|
-
for (const repo of kept)
|
|
2962
|
-
console.log(repo.path);
|
|
2963
|
-
return failedPulls > 0 ? 1 : 0;
|
|
2964
|
-
}
|
|
2965
|
-
if (values.json === true) {
|
|
2966
|
-
printJson(kept.map((repo) => ({ ...repo, reasons: reasonsOf(repo) })));
|
|
2967
|
-
return failedPulls > 0 ? 1 : 0;
|
|
2968
|
-
}
|
|
2969
|
-
const label = role("label", process23.stdout);
|
|
2970
|
-
printHeader("repos", `${basename2(root)} \xB7 ${states.length} ${states.length === 1 ? "repository" : "repositories"}`);
|
|
2971
|
-
if (kept.length === 0) {
|
|
2972
|
-
console.log(label(`nothing needs attention in ${states.length} repositories`));
|
|
2973
|
-
return failedPulls > 0 ? 1 : 0;
|
|
2974
|
-
}
|
|
2975
|
-
console.log(table([["repo", "branch", "dirty", "ahead/behind", "worktrees", "unreleased"], ...kept.map((repo) => row(repo, relative2(root, repo.path) || repo.name))], { header: true, align: ["left", "left", "right", "left", "right", "left"] }));
|
|
2976
|
-
const failed = kept.filter((repo) => repo.fetchFailed).map((repo) => repo.name);
|
|
2977
|
-
if (failed.length > 0)
|
|
2978
|
-
console.log(label(`fetch failed for ${failed.join(", ")}`));
|
|
2979
|
-
if (values.fetch !== true)
|
|
2980
|
-
console.log(label("ahead/behind as of the last fetch, --fetch refreshes them"));
|
|
2981
|
-
return failedPulls > 0 ? 1 : 0;
|
|
2982
|
-
}
|
|
2983
|
-
|
|
2984
|
-
// src/sweep.ts
|
|
2985
|
-
import { existsSync as existsSync11, statSync as statSync4 } from "fs";
|
|
2986
|
-
import { homedir as homedir6 } from "os";
|
|
2987
|
-
import { relative as relative3 } from "path";
|
|
2988
|
-
init_prompt();
|
|
2989
|
-
|
|
2990
|
-
// src/apply.ts
|
|
2991
|
-
import { existsSync as existsSync10 } from "fs";
|
|
2992
|
-
import { lstat as lstat3, rm } from "fs/promises";
|
|
2993
|
-
import { basename as basename4, join as join13 } from "path";
|
|
2994
|
-
|
|
2995
|
-
// src/sweep-scan.ts
|
|
2996
|
-
import { existsSync as existsSync9 } from "fs";
|
|
2997
|
-
import { lstat as lstat2, readdir as readdir4, realpath } from "fs/promises";
|
|
2998
|
-
import { homedir as homedir5 } from "os";
|
|
2999
|
-
import { basename as basename3, dirname as dirname5, join as join12 } from "path";
|
|
3000
|
-
|
|
3001
|
-
// src/size.ts
|
|
3002
|
-
import { lstat, readdir as readdir3 } from "fs/promises";
|
|
3003
|
-
import { join as join11 } from "path";
|
|
3004
|
-
var FS_LIMIT = 32;
|
|
3005
|
-
var FIND_MS = 60000;
|
|
3006
|
-
var FIND_LINE = /^(\w) (\d+) (\S+) (\d+) (\d+)$/gm;
|
|
3007
|
-
var OWN_UID = process.getuid?.() ?? -1;
|
|
3008
|
-
var waiting = [];
|
|
3009
|
-
var running = 0;
|
|
3010
|
-
async function gated(call) {
|
|
3011
|
-
if (running >= FS_LIMIT)
|
|
3012
|
-
await new Promise((resolve) => waiting.push(resolve));
|
|
3013
|
-
running++;
|
|
3014
|
-
try {
|
|
3015
|
-
return await call();
|
|
3016
|
-
} finally {
|
|
3017
|
-
running--;
|
|
3018
|
-
waiting.shift()?.();
|
|
3019
|
-
}
|
|
3020
|
-
}
|
|
3021
|
-
async function walk(folder, uid) {
|
|
3022
|
-
const seen = new Set;
|
|
3023
|
-
let total = 0;
|
|
3024
|
-
let foreign = 0;
|
|
3025
|
-
const visit = async (dir) => {
|
|
3026
|
-
let entries;
|
|
3027
|
-
try {
|
|
3028
|
-
entries = await gated(async () => readdir3(dir, { withFileTypes: true }));
|
|
3029
|
-
} catch {
|
|
3030
|
-
return;
|
|
3031
|
-
}
|
|
3032
|
-
await Promise.all(entries.map(async (entry) => {
|
|
3033
|
-
const path = join11(dir, entry.name);
|
|
3034
|
-
try {
|
|
3035
|
-
const stat = await gated(async () => lstat(path));
|
|
3036
|
-
if (stat.uid !== uid)
|
|
3037
|
-
foreign++;
|
|
3038
|
-
if (entry.isDirectory())
|
|
3039
|
-
return await visit(path);
|
|
3040
|
-
if (stat.nlink > 1) {
|
|
3041
|
-
const key = `${stat.dev}:${stat.ino}`;
|
|
3042
|
-
if (seen.has(key))
|
|
3043
|
-
return;
|
|
3044
|
-
seen.add(key);
|
|
3045
|
-
}
|
|
3046
|
-
total += stat.size;
|
|
3047
|
-
} catch {}
|
|
3048
|
-
}));
|
|
3049
|
-
};
|
|
3050
|
-
try {
|
|
3051
|
-
if ((await lstat(folder)).uid !== uid)
|
|
3052
|
-
foreign++;
|
|
3053
|
-
} catch {}
|
|
3054
|
-
await visit(folder);
|
|
3055
|
-
return { bytes: total, foreign };
|
|
3056
|
-
}
|
|
3057
|
-
async function findSize(folder, uid) {
|
|
3058
|
-
try {
|
|
3059
|
-
const ran = await runCommand(["find", "-P", folder, "-printf", "%y %n %D:%i %s %U\\n"], { timeoutMs: FIND_MS });
|
|
3060
|
-
const lines = [...ran.text.matchAll(FIND_LINE)];
|
|
3061
|
-
if (ran.timedOut || ran.code !== 0 && lines.length === 0)
|
|
3062
|
-
return;
|
|
3063
|
-
const seen = new Set;
|
|
3064
|
-
let total = 0;
|
|
3065
|
-
let foreign = 0;
|
|
3066
|
-
for (const [, type, links, id, bytes, owner] of lines) {
|
|
3067
|
-
if (Number(owner) !== uid)
|
|
3068
|
-
foreign++;
|
|
3069
|
-
if (type !== "f" && type !== "l")
|
|
3070
|
-
continue;
|
|
3071
|
-
if (Number(links) > 1) {
|
|
3072
|
-
if (seen.has(id))
|
|
3073
|
-
continue;
|
|
3074
|
-
seen.add(id);
|
|
3075
|
-
}
|
|
3076
|
-
total += Number(bytes);
|
|
3077
|
-
}
|
|
3078
|
-
return { bytes: total, foreign };
|
|
3079
|
-
} catch {
|
|
3080
|
-
return;
|
|
3081
|
-
}
|
|
3082
|
-
}
|
|
3083
|
-
async function measure(folder, uid = OWN_UID) {
|
|
3084
|
-
return await findSize(folder, uid) ?? await walk(folder, uid);
|
|
3085
|
-
}
|
|
89
|
+
--pull fetches, then fast-forwards only the repositories listed that are clean, on a branch and only behind their upstream; the others are reported as skipped.`,EXITS2=[[0,"it listed the repositories, including when none needs attention"],[1,"a fast-forward --pull attempted failed"],[2,"a usage error, an unreadable config or a root that is no folder"]],OPTIONS2={all:{type:"boolean",short:"a",description:"list the repositories with nothing to report too"},only:{type:"string",multiple:!0,choices:REASONS,description:"only the repositories with this reason: dirty, unpushed, unreleased or behind, repeatable"},watch:watchOption("the repositories"),fetch:{type:"boolean",conflicts:["watch"],description:"refresh the upstreams first (reaches the remote)"},pull:{type:"boolean",conflicts:["watch"],description:"fetch, then fast-forward the clean repositories listed that are only behind their upstream (reaches the remote)"},path:{type:"boolean",conflicts:["json"],description:"print only the paths of the repositories listed, one per line"},json:jsonOption("[{name, path, branch, upstream, dirty, ahead, behind, worktrees, tag, unreleased, packages, reasons, fetchFailed, unreadable}]")};async function skipped(){let file=userConfigReadPath("repos");if(!existsSync8(file))return new Set;try{let config=await Bun.file(file).json();return new Set(Array.isArray(config.skip)?config.skip.filter((name)=>typeof name==="string"):[])}catch(error){fail(`${file} does not parse: ${error instanceof Error?error.message:String(error)}`)}}function releasedCell(repo){if(repo.packages.length>0)return repo.packages.filter((release)=>release.unreleased>0).map((release)=>`${release.name} ${release.unreleased}`).join(", ")||"-";return repo.tag===null||repo.unreleased===0?"-":`${repo.unreleased} since ${repo.tag}`}function syncCell(repo,stream=process23.stdout){let colors=paint(stream),ahead=repo.ahead??0,behind=repo.behind??0;if(repo.upstream===null)return colors.dim("no upstream");let parts=[ahead>0?colors.green(`+${ahead}`):"",behind>0?colors.red(`-${behind}`):""].filter(Boolean),diverged=takesControlCodes(stream)&&ahead>0&&behind>0;return parts.length===0?colors.dim("-"):`${parts.join(" ")}${diverged?colors.yellow(" diverged"):""}`}var DEFAULT_BRANCHES=new Set(["main","master"]);function branchCell(repo,stream=process23.stdout){let colors=paint(stream);if(repo.unreadable)return colors.red("? (unreadable)");if(repo.branch==="(detached)")return colors.yellow(repo.branch);return DEFAULT_BRANCHES.has(repo.branch)?repo.branch:role("accent",stream)(repo.branch)}function row(repo,shown){let colors=paint(process23.stdout),tint=role("path",process23.stdout),unreleased=releasedCell(repo);return[tint(shown),branchCell(repo),repo.dirty===0?colors.dim("-"):colors.yellow(String(repo.dirty)),syncCell(repo),repo.worktrees===0?colors.dim("-"):String(repo.worktrees),unreleased==="-"?colors.dim("-"):colors.cyan(unreleased)]}async function repos(args,watched=!1){let{values,positionals}=parse(args,USAGE2,OPTIONS2,{positionals:["[root]"],exits:EXITS2,replaces:"a cd, git status, git log and git tag loop over each repository of the workspace",examples:["ws repos","ws repos ~/Workspace --only unreleased --fetch",["ws repos --only behind --pull","fast-forward what is behind and clean"],["ws repos --only dirty --path","the paths, for xargs"]]});if(values.watch!==void 0)return watching(values.watch,async()=>repos(withoutWatch(args),!0));let root=workspaceRoot({given:positionals[0]});if(!existsSync8(root)||!statSync4(root).isDirectory())fail(`no folder ${root}`);let only=values.only??[],progress=watched?void 0:progressLine(),fetching=values.fetch===!0||values.pull===!0,step=fetching?"fetching":"reading",states;try{progress?.update({step:"finding the repositories"});let paths=await findRepos2(root,await skipped());progress?.update({step,done:0,total:paths.length,unit:"repositories"}),states=await pool(paths,configuredNumber("repos","concurrency",CONCURRENCY2),async(path)=>inspect(path,fetching),(done,total)=>progress?.update({step,done,total,unit:"repositories"}))}finally{progress?.stop()}let keeps=(repo)=>{let reasons=reasonsOf(repo);if(only.length>0)return reasons.some((reason)=>only.includes(reason));return values.all===!0||reasons.some((reason)=>reason!=="unreleased")||repo.unreadable},failedPulls=0;if(values.pull===!0){let log=values.json===!0||values.path===!0?console.error:console.log;for(let[index,repo]of states.entries()){if(!keeps(repo)||(repo.behind??0)===0)continue;let blocker=pullBlocker(repo),refused=blocker===void 0?await fastForward(repo.path):void 0;if(blocker!==void 0)log(marked("note",`${repo.name} skipped`,process23.stdout,blocker));else if(refused!==void 0)failedPulls++,log(marked("problem",`${repo.name} not pulled`,process23.stdout,refused));else log(marked("ok",`${repo.name} pulled`,process23.stdout,`${repo.behind} ${repo.behind===1?"commit":"commits"}`)),states[index]=await inspect(repo.path,!1)}}let kept=states.filter(keeps);if(values.path===!0){for(let repo of kept)console.log(repo.path);return failedPulls>0?1:0}if(values.json===!0)return printJson(kept.map((repo)=>({...repo,reasons:reasonsOf(repo)}))),failedPulls>0?1:0;let label=role("label",process23.stdout);if(printHeader("repos",`${basename2(root)} \xB7 ${states.length} ${states.length===1?"repository":"repositories"}`),kept.length===0)return console.log(label(`nothing needs attention in ${states.length} repositories`)),failedPulls>0?1:0;console.log(table([["repo","branch","dirty","ahead/behind","worktrees","unreleased"],...kept.map((repo)=>row(repo,relative2(root,repo.path)||repo.name))],{header:!0,align:["left","left","right","left","right","left"]}));let failed=kept.filter((repo)=>repo.fetchFailed).map((repo)=>repo.name);if(failed.length>0)console.log(label(`fetch failed for ${failed.join(", ")}`));if(values.fetch!==!0)console.log(label("ahead/behind as of the last fetch, --fetch refreshes them"));return failedPulls>0?1:0}import{existsSync as existsSync11,statSync as statSync5}from"fs";import{homedir as homedir6}from"os";import{relative as relative3}from"path";init_prompt();import{existsSync as existsSync10}from"fs";import{lstat as lstat3,rm}from"fs/promises";import{basename as basename4,join as join13}from"path";import{existsSync as existsSync9}from"fs";import{lstat as lstat2,readdir as readdir4,realpath}from"fs/promises";import{homedir as homedir5}from"os";import{basename as basename3,dirname as dirname5,join as join12}from"path";import{lstat,readdir as readdir3}from"fs/promises";import{join as join11}from"path";var FS_LIMIT=32,FIND_MS=60000,FIND_LINE=/^(\w) (\d+) (\S+) (\d+) (\d+)$/gm,OWN_UID=process.getuid?.()??-1,waiting=[],running=0;async function gated(call){if(running>=FS_LIMIT)await new Promise((resolve)=>waiting.push(resolve));running++;try{return await call()}finally{running--,waiting.shift()?.()}}async function walk(folder,uid){let seen=new Set,total=0,foreign=0,visit=async(dir)=>{let entries;try{entries=await gated(async()=>readdir3(dir,{withFileTypes:!0}))}catch{return}await Promise.all(entries.map(async(entry)=>{let path=join11(dir,entry.name);try{let stat=await gated(async()=>lstat(path));if(stat.uid!==uid)foreign++;if(entry.isDirectory())return await visit(path);if(stat.nlink>1){let key=`${stat.dev}:${stat.ino}`;if(seen.has(key))return;seen.add(key)}total+=stat.size}catch{}}))};try{if((await lstat(folder)).uid!==uid)foreign++}catch{}return await visit(folder),{bytes:total,foreign}}async function findSize(folder,uid){try{let ran=await runCommand(["find","-P",folder,"-printf","%y %n %D:%i %s %U\\n"],{timeoutMs:FIND_MS}),lines=[...ran.text.matchAll(FIND_LINE)];if(ran.timedOut||ran.code!==0&&lines.length===0)return;let seen=new Set,total=0,foreign=0;for(let[,type,links,id,bytes,owner]of lines){if(Number(owner)!==uid)foreign++;if(type!=="f"&&type!=="l")continue;if(Number(links)>1){if(seen.has(id))continue;seen.add(id)}total+=Number(bytes)}return{bytes:total,foreign}}catch{return}}async function measure(folder,uid=OWN_UID){return await findSize(folder,uid)??await walk(folder,uid)}var FOLDER_NAMES=new Set(["node_modules",".nuxt",".next",".output","dist","build",".turbo",".svelte-kit","target","vendor",".venv","__pycache__",".gradle"]),NEEDS_BESIDE={target:["Cargo.toml"],vendor:["composer.json","composer.lock"]},MAX_DEPTH3=3,PROJECT_CACHE_NAMES=new Set([".turbo",".nuxt",".next",".svelte-kit","__pycache__",".gradle"]),GLOBAL_CACHES=[".bun/install/cache",".npm/_cacache",".cache/pip",".cache/uv",".cache/ms-playwright",".cache/puppeteer",".cache/go-build",".cache/typescript",".cargo/registry"];function isCachePath(path,home=homedir5()){return GLOBAL_CACHES.some((cache)=>join12(home,cache)===path)||basename3(path)===".cache"&&basename3(dirname5(path))==="node_modules"}async function listing(dir){try{return await readdir4(dir,{withFileTypes:!0})}catch{return[]}}async function addGlobalCaches(found,home){for(let cache of GLOBAL_CACHES){let path=join12(home,cache);try{let stat=await lstat2(path);if(stat.isSymbolicLink())found.skipped.push({path,reason:"symlink"});else if(stat.isDirectory())found.candidates.push({path,kind:"cache",global:!0})}catch{}}}async function findCandidates(root,home=homedir5(),withGlobal=!0){let found={candidates:[],skipped:[]},visit=async(dir,depth)=>{let entries=await listing(dir);for(let entry of entries){let path=join12(dir,entry.name);if(entry.name===".git")continue;if(entry.name===".worktrees"||entry.name==="worktrees"&&basename3(dir)===".claude"){if(!entry.isDirectory()){found.skipped.push({path,reason:"symlink"});continue}for(let worktree of await listing(path))if(worktree.isDirectory())found.candidates.push({path:join12(path,worktree.name),kind:"worktree"});else if(worktree.isSymbolicLink())found.skipped.push({path:join12(path,worktree.name),reason:"symlink"});continue}if(FOLDER_NAMES.has(entry.name)&&(NEEDS_BESIDE[entry.name]?.some((file)=>existsSync9(join12(dir,file)))??!0)){if(entry.isSymbolicLink())found.skipped.push({path,reason:"symlink"});else if(entry.isDirectory()){if(found.candidates.push({path,kind:PROJECT_CACHE_NAMES.has(entry.name)?"cache":"folder"}),entry.name==="node_modules"){let cache=(await listing(path)).find((inner)=>inner.name===".cache");if(cache?.isSymbolicLink())found.skipped.push({path:join12(path,".cache"),reason:"symlink"});else if(cache?.isDirectory())found.candidates.push({path:join12(path,".cache"),kind:"cache",inside:path})}}continue}if(entry.isDirectory()&&depth<MAX_DEPTH3)await visit(path,depth+1)}};if(await visit(root,0),withGlobal)await addGlobalCaches(found,home);return found}async function realOf(path){try{return await realpath(path)}catch{return}}var HEADS_PREFIX=/^refs\/heads\//,TRAILING_SLASH=/\/$/;async function gitIn(cwd,args){try{let{code,stdout,stderr}=await runTool(`git ${args.join(" ")}`,["git","-C",cwd,...args],{timeoutMs:30000});return{code,stdout:stdout.trim(),stderr}}catch(error){return{code:-1,stdout:"",stderr:String(error)}}}function memo(make){let cache=new Map;return async(key)=>{let value=cache.get(key);if(value===void 0)value=make(key),cache.set(key,value);return value}}var NOT_A_REPO=/not a git repository/i,toplevelOf=memo(async(dir)=>{let{code,stdout,stderr}=await gitIn(dir,["rev-parse","--show-toplevel"]);if(code===0&&stdout!=="")return{top:stdout};return NOT_A_REPO.test(stderr)?"none":"failed"}),lastCommitOf=memo(async(top)=>{let{code,stdout}=await gitIn(top,["log","-1","--format=%ct"]);return code===0&&stdout!==""?Number(stdout)*1000:void 0}),worktreesOf=memo(async(repo)=>{let{code,stdout}=await gitIn(repo,["worktree","list","--porcelain"]),branches=new Map;if(code!==0)return branches;for(let block of stdout.split(`
|
|
3086
90
|
|
|
3087
|
-
|
|
3088
|
-
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
|
|
3092
|
-
var GLOBAL_CACHES = [".bun/install/cache", ".npm/_cacache", ".cache/pip", ".cache/uv", ".cache/ms-playwright", ".cache/puppeteer", ".cache/go-build", ".cache/typescript", ".cargo/registry"];
|
|
3093
|
-
function isCachePath(path, home = homedir5()) {
|
|
3094
|
-
return GLOBAL_CACHES.some((cache) => join12(home, cache) === path) || basename3(path) === ".cache" && basename3(dirname5(path)) === "node_modules";
|
|
3095
|
-
}
|
|
3096
|
-
async function listing(dir) {
|
|
3097
|
-
try {
|
|
3098
|
-
return await readdir4(dir, { withFileTypes: true });
|
|
3099
|
-
} catch {
|
|
3100
|
-
return [];
|
|
3101
|
-
}
|
|
3102
|
-
}
|
|
3103
|
-
async function addGlobalCaches(found, home) {
|
|
3104
|
-
for (const cache of GLOBAL_CACHES) {
|
|
3105
|
-
const path = join12(home, cache);
|
|
3106
|
-
try {
|
|
3107
|
-
const stat = await lstat2(path);
|
|
3108
|
-
if (stat.isSymbolicLink())
|
|
3109
|
-
found.skipped.push({ path, reason: "symlink" });
|
|
3110
|
-
else if (stat.isDirectory())
|
|
3111
|
-
found.candidates.push({ path, kind: "cache", global: true });
|
|
3112
|
-
} catch {}
|
|
3113
|
-
}
|
|
3114
|
-
}
|
|
3115
|
-
async function findCandidates(root, home = homedir5(), withGlobal = true) {
|
|
3116
|
-
const found = { candidates: [], skipped: [] };
|
|
3117
|
-
const visit = async (dir, depth) => {
|
|
3118
|
-
const entries = await listing(dir);
|
|
3119
|
-
for (const entry of entries) {
|
|
3120
|
-
const path = join12(dir, entry.name);
|
|
3121
|
-
if (entry.name === ".git")
|
|
3122
|
-
continue;
|
|
3123
|
-
if (entry.name === ".worktrees" || entry.name === "worktrees" && basename3(dir) === ".claude") {
|
|
3124
|
-
if (!entry.isDirectory()) {
|
|
3125
|
-
found.skipped.push({ path, reason: "symlink" });
|
|
3126
|
-
continue;
|
|
3127
|
-
}
|
|
3128
|
-
for (const worktree of await listing(path)) {
|
|
3129
|
-
if (worktree.isDirectory())
|
|
3130
|
-
found.candidates.push({ path: join12(path, worktree.name), kind: "worktree" });
|
|
3131
|
-
else if (worktree.isSymbolicLink())
|
|
3132
|
-
found.skipped.push({ path: join12(path, worktree.name), reason: "symlink" });
|
|
3133
|
-
}
|
|
3134
|
-
continue;
|
|
3135
|
-
}
|
|
3136
|
-
if (FOLDER_NAMES.has(entry.name) && (NEEDS_BESIDE[entry.name]?.some((file) => existsSync9(join12(dir, file))) ?? true)) {
|
|
3137
|
-
if (entry.isSymbolicLink()) {
|
|
3138
|
-
found.skipped.push({ path, reason: "symlink" });
|
|
3139
|
-
} else if (entry.isDirectory()) {
|
|
3140
|
-
found.candidates.push({ path, kind: PROJECT_CACHE_NAMES.has(entry.name) ? "cache" : "folder" });
|
|
3141
|
-
if (entry.name === "node_modules") {
|
|
3142
|
-
const cache = (await listing(path)).find((inner) => inner.name === ".cache");
|
|
3143
|
-
if (cache?.isSymbolicLink())
|
|
3144
|
-
found.skipped.push({ path: join12(path, ".cache"), reason: "symlink" });
|
|
3145
|
-
else if (cache?.isDirectory())
|
|
3146
|
-
found.candidates.push({ path: join12(path, ".cache"), kind: "cache", inside: path });
|
|
3147
|
-
}
|
|
3148
|
-
}
|
|
3149
|
-
continue;
|
|
3150
|
-
}
|
|
3151
|
-
if (entry.isDirectory() && depth < MAX_DEPTH3)
|
|
3152
|
-
await visit(path, depth + 1);
|
|
3153
|
-
}
|
|
3154
|
-
};
|
|
3155
|
-
await visit(root, 0);
|
|
3156
|
-
if (withGlobal)
|
|
3157
|
-
await addGlobalCaches(found, home);
|
|
3158
|
-
return found;
|
|
3159
|
-
}
|
|
3160
|
-
async function realOf(path) {
|
|
3161
|
-
try {
|
|
3162
|
-
return await realpath(path);
|
|
3163
|
-
} catch {
|
|
3164
|
-
return;
|
|
3165
|
-
}
|
|
3166
|
-
}
|
|
3167
|
-
var HEADS_PREFIX = /^refs\/heads\//;
|
|
3168
|
-
var TRAILING_SLASH = /\/$/;
|
|
3169
|
-
async function gitIn(cwd, args) {
|
|
3170
|
-
try {
|
|
3171
|
-
const { code, stdout, stderr } = await runTool(`git ${args.join(" ")}`, ["git", "-C", cwd, ...args], { timeoutMs: 30000 });
|
|
3172
|
-
return { code, stdout: stdout.trim(), stderr };
|
|
3173
|
-
} catch (error) {
|
|
3174
|
-
return { code: -1, stdout: "", stderr: String(error) };
|
|
3175
|
-
}
|
|
3176
|
-
}
|
|
3177
|
-
function memo(make) {
|
|
3178
|
-
const cache = new Map;
|
|
3179
|
-
return async (key) => {
|
|
3180
|
-
let value = cache.get(key);
|
|
3181
|
-
if (value === undefined) {
|
|
3182
|
-
value = make(key);
|
|
3183
|
-
cache.set(key, value);
|
|
3184
|
-
}
|
|
3185
|
-
return value;
|
|
3186
|
-
};
|
|
3187
|
-
}
|
|
3188
|
-
var NOT_A_REPO = /not a git repository/i;
|
|
3189
|
-
var toplevelOf = memo(async (dir) => {
|
|
3190
|
-
const { code, stdout, stderr } = await gitIn(dir, ["rev-parse", "--show-toplevel"]);
|
|
3191
|
-
if (code === 0 && stdout !== "")
|
|
3192
|
-
return { top: stdout };
|
|
3193
|
-
return NOT_A_REPO.test(stderr) ? "none" : "failed";
|
|
3194
|
-
});
|
|
3195
|
-
var lastCommitOf = memo(async (top) => {
|
|
3196
|
-
const { code, stdout } = await gitIn(top, ["log", "-1", "--format=%ct"]);
|
|
3197
|
-
return code === 0 && stdout !== "" ? Number(stdout) * 1000 : undefined;
|
|
3198
|
-
});
|
|
3199
|
-
var worktreesOf = memo(async (repo) => {
|
|
3200
|
-
const { code, stdout } = await gitIn(repo, ["worktree", "list", "--porcelain"]);
|
|
3201
|
-
const branches = new Map;
|
|
3202
|
-
if (code !== 0)
|
|
3203
|
-
return branches;
|
|
3204
|
-
for (const block of stdout.split(`
|
|
3205
|
-
|
|
3206
|
-
`)) {
|
|
3207
|
-
const lines = block.split(`
|
|
3208
|
-
`);
|
|
3209
|
-
const path = lines.find((line) => line.startsWith("worktree "))?.slice("worktree ".length);
|
|
3210
|
-
const branch = lines.find((line) => line.startsWith("branch "))?.slice("branch ".length);
|
|
3211
|
-
if (path !== undefined)
|
|
3212
|
-
branches.set(await realOf(path) ?? path, branch);
|
|
3213
|
-
}
|
|
3214
|
-
return branches;
|
|
3215
|
-
});
|
|
3216
|
-
async function judgeFolder(path, kind, inside) {
|
|
3217
|
-
const parent = dirname5(path);
|
|
3218
|
-
const name = basename3(path);
|
|
3219
|
-
const located = await toplevelOf(parent);
|
|
3220
|
-
if (located === "failed")
|
|
3221
|
-
return { skip: "git failed" };
|
|
3222
|
-
if (existsSync9(join12(path, ".git")))
|
|
3223
|
-
return { skip: "holds a git repository" };
|
|
3224
|
-
if (located === "none")
|
|
3225
|
-
return name === "node_modules" || inside !== undefined ? { entry: { path, kind, committedAt: undefined, action: "remove", inside, project: dirname5(inside ?? path) } } : { skip: "not in a git repository" };
|
|
3226
|
-
const tracked = await gitIn(parent, ["ls-files", "--", name]);
|
|
3227
|
-
if (tracked.code !== 0 || tracked.stdout !== "")
|
|
3228
|
-
return { skip: "tracked by git" };
|
|
3229
|
-
if (name !== "node_modules" && inside === undefined && (await gitIn(parent, ["check-ignore", "-q", "--", name])).code !== 0)
|
|
3230
|
-
return { skip: "not ignored by git" };
|
|
3231
|
-
return { entry: { path, kind, committedAt: await lastCommitOf(located.top), action: "remove", inside, project: located.top } };
|
|
3232
|
-
}
|
|
3233
|
-
async function judgeWorktree(path) {
|
|
3234
|
-
const located = await toplevelOf(dirname5(path));
|
|
3235
|
-
if (located === "failed")
|
|
3236
|
-
return { skip: "git failed" };
|
|
3237
|
-
if (located === "none")
|
|
3238
|
-
return { skip: "not in a git repository" };
|
|
3239
|
-
const { top } = located;
|
|
3240
|
-
const real = await realOf(path);
|
|
3241
|
-
const branches = await worktreesOf(top);
|
|
3242
|
-
if (real === undefined || !branches.has(real))
|
|
3243
|
-
return { skip: "not a worktree of this repo" };
|
|
3244
|
-
const committedAt = await lastCommitOf(top);
|
|
3245
|
-
const keep = (reason) => ({ entry: { path, kind: "worktree", committedAt, action: "keep", reason, repo: top } });
|
|
3246
|
-
const branch = branches.get(real);
|
|
3247
|
-
if (branch === undefined)
|
|
3248
|
-
return keep("detached HEAD");
|
|
3249
|
-
const status = await gitIn(path, ["status", "--porcelain", "-z", "--ignored=matching"]);
|
|
3250
|
-
if (status.code !== 0)
|
|
3251
|
-
return keep("status failed");
|
|
3252
|
-
const changes = status.stdout.split("\x00").filter((line) => line !== "");
|
|
3253
|
-
if (changes.some((line) => !line.startsWith("!! ")))
|
|
3254
|
-
return keep("uncommitted changes");
|
|
3255
|
-
if (changes.some((line) => !line.endsWith("/") || !FOLDER_NAMES.has(basename3(line.slice(3).replace(TRAILING_SLASH, "")))))
|
|
3256
|
-
return keep("ignored files (.env, local data) that removing would delete");
|
|
3257
|
-
const unique = await gitIn(path, ["log", "--format=%h", branch, "--not", "--remotes", `--exclude=${branch.replace(HEADS_PREFIX, "")}`, "--branches"]);
|
|
3258
|
-
if (unique.code !== 0)
|
|
3259
|
-
return keep("log failed");
|
|
3260
|
-
if (unique.stdout !== "")
|
|
3261
|
-
return keep(`${unique.stdout.split(`
|
|
3262
|
-
`).length} commits on no other branch or remote`);
|
|
3263
|
-
return { entry: { path, kind: "worktree", committedAt, action: "remove", repo: top, project: path } };
|
|
3264
|
-
}
|
|
3265
|
-
async function judge(candidate) {
|
|
3266
|
-
if (candidate.global === true)
|
|
3267
|
-
return { entry: { path: candidate.path, kind: candidate.kind, committedAt: undefined, action: "remove" } };
|
|
3268
|
-
return candidate.kind === "worktree" ? judgeWorktree(candidate.path) : judgeFolder(candidate.path, candidate.kind, candidate.inside);
|
|
3269
|
-
}
|
|
3270
|
-
async function inspect2({ candidates, skipped }, onDone, uid) {
|
|
3271
|
-
const entries = [];
|
|
3272
|
-
const rejected = [...skipped];
|
|
3273
|
-
await pool(candidates, 8, async (candidate) => {
|
|
3274
|
-
const verdict = await judge(candidate);
|
|
3275
|
-
if ("skip" in verdict) {
|
|
3276
|
-
rejected.push({ path: candidate.path, reason: verdict.skip });
|
|
3277
|
-
return;
|
|
3278
|
-
}
|
|
3279
|
-
const { bytes, foreign } = await measure(candidate.path, uid);
|
|
3280
|
-
const owned = foreign > 0 && verdict.entry.action === "remove" ? { action: "keep", reason: `${foreign} ${foreign === 1 ? "entry" : "entries"} owned by another user (a container's?)` } : {};
|
|
3281
|
-
entries.push({ ...verdict.entry, ...owned, bytes });
|
|
3282
|
-
}, onDone);
|
|
3283
|
-
const listed = new Set(entries.filter((entry) => entry.action === "remove").map((entry) => entry.path));
|
|
3284
|
-
return { entries: entries.filter((entry) => entry.inside === undefined || !listed.has(entry.inside)), skipped: rejected };
|
|
3285
|
-
}
|
|
3286
|
-
|
|
3287
|
-
// src/apply.ts
|
|
3288
|
-
async function removeFolder(entry) {
|
|
3289
|
-
try {
|
|
3290
|
-
const stat = await lstat3(entry.path);
|
|
3291
|
-
if (stat.isSymbolicLink() || !stat.isDirectory() || !(FOLDER_NAMES.has(basename4(entry.path)) || entry.kind === "cache" && isCachePath(entry.path)))
|
|
3292
|
-
return { path: entry.path, removed: false, error: "no longer a plain folder" };
|
|
3293
|
-
if (existsSync10(join13(entry.path, ".git")))
|
|
3294
|
-
return { path: entry.path, removed: false, error: "holds a git repository" };
|
|
3295
|
-
await rm(entry.path, { recursive: true, force: true });
|
|
3296
|
-
return { path: entry.path, removed: true };
|
|
3297
|
-
} catch (error) {
|
|
3298
|
-
return { path: entry.path, removed: false, error: error instanceof Error ? error.message : String(error) };
|
|
3299
|
-
}
|
|
3300
|
-
}
|
|
3301
|
-
async function removeWorktree(entry) {
|
|
3302
|
-
if (entry.repo === undefined)
|
|
3303
|
-
return { path: entry.path, removed: false, error: "no repository known" };
|
|
3304
|
-
try {
|
|
3305
|
-
const ran = await runTool("git worktree remove", ["git", "-C", entry.repo, "worktree", "remove", entry.path]);
|
|
3306
|
-
return ran.code === 0 ? { path: entry.path, removed: true } : { path: entry.path, removed: false, error: ran.stderr.trim() };
|
|
3307
|
-
} catch (error) {
|
|
3308
|
-
return { path: entry.path, removed: false, error: String(error) };
|
|
3309
|
-
}
|
|
3310
|
-
}
|
|
3311
|
-
async function applyAll(entries, done) {
|
|
3312
|
-
const outcomes = [];
|
|
3313
|
-
for (const entry of entries) {
|
|
3314
|
-
if (entry.action !== "remove")
|
|
3315
|
-
continue;
|
|
3316
|
-
const outcome = await (entry.kind === "worktree" ? removeWorktree(entry) : removeFolder(entry));
|
|
3317
|
-
outcomes.push(outcome);
|
|
3318
|
-
done(outcome);
|
|
3319
|
-
}
|
|
3320
|
-
return outcomes;
|
|
3321
|
-
}
|
|
3322
|
-
|
|
3323
|
-
// src/busy.ts
|
|
3324
|
-
import { readdir as readdir5, readFile, readlink } from "fs/promises";
|
|
3325
|
-
import { basename as basename5, join as join14 } from "path";
|
|
3326
|
-
var DEV_PROGRAMS = new Set(["node", "bun", "deno", "npm", "npx", "pnpm", "yarn", "bunx", "vite", "esbuild", "ruby", "java", "cargo", "go", "php", "php-fpm"]);
|
|
3327
|
-
var DEV_PREFIXES = ["python", "php"];
|
|
3328
|
-
var DOCKER_MS = 5000;
|
|
3329
|
-
var PID = /^\d+$/;
|
|
3330
|
-
var PARENT = /^ \S+ (\d+)/;
|
|
3331
|
-
function isDevProgram(comm) {
|
|
3332
|
-
return DEV_PROGRAMS.has(comm) || DEV_PREFIXES.some((prefix) => comm.startsWith(prefix));
|
|
3333
|
-
}
|
|
3334
|
-
async function quietly(read) {
|
|
3335
|
-
try {
|
|
3336
|
-
return await read();
|
|
3337
|
-
} catch {
|
|
3338
|
-
return;
|
|
3339
|
-
}
|
|
3340
|
-
}
|
|
3341
|
-
async function lineage(pid, root) {
|
|
3342
|
-
const seen = new Set;
|
|
3343
|
-
for (let current = pid;current > 1 && !seen.has(current); ) {
|
|
3344
|
-
seen.add(current);
|
|
3345
|
-
const stat = await quietly(async () => readFile(join14(root, String(current), "stat"), "utf8"));
|
|
3346
|
-
const parent = Number(PARENT.exec(stat?.slice(stat.lastIndexOf(")") + 1) ?? "")?.[1]);
|
|
3347
|
-
if (!Number.isInteger(parent))
|
|
3348
|
-
break;
|
|
3349
|
-
current = parent;
|
|
3350
|
-
}
|
|
3351
|
-
return seen;
|
|
3352
|
-
}
|
|
3353
|
-
async function processPlaces(root = "/proc", self = process.pid) {
|
|
3354
|
-
const own = await lineage(self, root);
|
|
3355
|
-
const pids = (await quietly(async () => readdir5(root)) ?? []).filter((name) => PID.test(name)).map(Number).filter((pid) => !own.has(pid));
|
|
3356
|
-
const places = [];
|
|
3357
|
-
await Promise.all(pids.map(async (pid) => {
|
|
3358
|
-
const comm = (await quietly(async () => readFile(join14(root, String(pid), "comm"), "utf8")))?.trim();
|
|
3359
|
-
if (comm === undefined || !isDevProgram(comm))
|
|
3360
|
-
return;
|
|
3361
|
-
const cwd = await quietly(async () => readlink(join14(root, String(pid), "cwd")));
|
|
3362
|
-
const argv = (await quietly(async () => readFile(join14(root, String(pid), "cmdline"), "utf8")))?.split("\x00").filter((arg) => arg.startsWith("/")) ?? [];
|
|
3363
|
-
const who = `pid ${pid} ${comm}`;
|
|
3364
|
-
for (const path of [cwd, ...argv.slice(1)]) {
|
|
3365
|
-
if (path !== undefined)
|
|
3366
|
-
places.push({ path, who });
|
|
3367
|
-
}
|
|
3368
|
-
}));
|
|
3369
|
-
return places;
|
|
3370
|
-
}
|
|
3371
|
-
async function containerPlaces() {
|
|
3372
|
-
const ids = await quietly(async () => runCommand(["docker", "ps", "-q"], { timeoutMs: DOCKER_MS }));
|
|
3373
|
-
if (ids === undefined || ids.code !== 0 || ids.text.trim() === "")
|
|
3374
|
-
return [];
|
|
3375
|
-
const inspected = await quietly(async () => runCommand(["docker", "inspect", "--format", '{{.Name}}{{range .Mounts}}{{if eq .Type "bind"}}\t{{.Source}}{{end}}{{end}}', ...ids.text.trim().split(`
|
|
3376
|
-
`)], { timeoutMs: DOCKER_MS }));
|
|
3377
|
-
if (inspected === undefined || inspected.code !== 0)
|
|
3378
|
-
return [];
|
|
3379
|
-
return inspected.text.trim().split(`
|
|
3380
|
-
`).flatMap((line) => {
|
|
3381
|
-
const [name = "", ...sources] = line.split("\t");
|
|
3382
|
-
return sources.map((path) => ({ path, who: `container ${basename5(name)}` }));
|
|
3383
|
-
});
|
|
3384
|
-
}
|
|
3385
|
-
var within = (path, folder) => path === folder || path.startsWith(`${folder}/`);
|
|
3386
|
-
function userOf(folder, processes, containers) {
|
|
3387
|
-
return processes.find((place) => within(place.path, folder))?.who ?? containers.find((place) => within(place.path, folder) || within(folder, place.path))?.who;
|
|
3388
|
-
}
|
|
3389
|
-
|
|
3390
|
-
// src/sweep.ts
|
|
3391
|
-
var LARGE = 100 * 1024 ** 2;
|
|
3392
|
-
var BIG = 1024 ** 3;
|
|
3393
|
-
var USAGE3 = `ws sweep [options] [root]: lists the regenerable folders, caches and worktrees under root (the configured workspace by default, ${MAX_DEPTH3} levels down), largest first with the age of the repo's last commit
|
|
91
|
+
`)){let lines=block.split(`
|
|
92
|
+
`),path=lines.find((line)=>line.startsWith("worktree "))?.slice(9),branch=lines.find((line)=>line.startsWith("branch "))?.slice(7);if(path!==void 0)branches.set(await realOf(path)??path,branch)}return branches});async function judgeFolder(path,kind,inside){let parent=dirname5(path),name=basename3(path),located=await toplevelOf(parent);if(located==="failed")return{skip:"git failed"};if(existsSync9(join12(path,".git")))return{skip:"holds a git repository"};if(located==="none")return name==="node_modules"||inside!==void 0?{entry:{path,kind,committedAt:void 0,action:"remove",inside,project:dirname5(inside??path)}}:{skip:"not in a git repository"};let tracked=await gitIn(parent,["ls-files","--",name]);if(tracked.code!==0||tracked.stdout!=="")return{skip:"tracked by git"};if(name!=="node_modules"&&inside===void 0&&(await gitIn(parent,["check-ignore","-q","--",name])).code!==0)return{skip:"not ignored by git"};return{entry:{path,kind,committedAt:await lastCommitOf(located.top),action:"remove",inside,project:located.top}}}async function judgeWorktree(path){let located=await toplevelOf(dirname5(path));if(located==="failed")return{skip:"git failed"};if(located==="none")return{skip:"not in a git repository"};let{top}=located,real=await realOf(path),branches=await worktreesOf(top);if(real===void 0||!branches.has(real))return{skip:"not a worktree of this repo"};let committedAt=await lastCommitOf(top),keep=(reason)=>({entry:{path,kind:"worktree",committedAt,action:"keep",reason,repo:top}}),branch=branches.get(real);if(branch===void 0)return keep("detached HEAD");let status=await gitIn(path,["status","--porcelain","-z","--ignored=matching"]);if(status.code!==0)return keep("status failed");let changes=status.stdout.split("\x00").filter((line)=>line!=="");if(changes.some((line)=>!line.startsWith("!! ")))return keep("uncommitted changes");if(changes.some((line)=>!line.endsWith("/")||!FOLDER_NAMES.has(basename3(line.slice(3).replace(TRAILING_SLASH,"")))))return keep("ignored files (.env, local data) that removing would delete");let unique=await gitIn(path,["log","--format=%h",branch,"--not","--remotes",`--exclude=${branch.replace(HEADS_PREFIX,"")}`,"--branches"]);if(unique.code!==0)return keep("log failed");if(unique.stdout!=="")return keep(`${unique.stdout.split(`
|
|
93
|
+
`).length} commits on no other branch or remote`);return{entry:{path,kind:"worktree",committedAt,action:"remove",repo:top,project:path}}}async function judge(candidate){if(candidate.global===!0)return{entry:{path:candidate.path,kind:candidate.kind,committedAt:void 0,action:"remove"}};return candidate.kind==="worktree"?judgeWorktree(candidate.path):judgeFolder(candidate.path,candidate.kind,candidate.inside)}async function inspect2({candidates,skipped},onDone,uid){let entries=[],rejected=[...skipped];await pool(candidates,8,async(candidate)=>{let verdict=await judge(candidate);if("skip"in verdict){rejected.push({path:candidate.path,reason:verdict.skip});return}let{bytes,foreign}=await measure(candidate.path,uid),owned=foreign>0&&verdict.entry.action==="remove"?{action:"keep",reason:`${foreign} ${foreign===1?"entry":"entries"} owned by another user (a container's?)`}:{};entries.push({...verdict.entry,...owned,bytes})},onDone);let listed=new Set(entries.filter((entry)=>entry.action==="remove").map((entry)=>entry.path));return{entries:entries.filter((entry)=>entry.inside===void 0||!listed.has(entry.inside)),skipped:rejected}}async function removeFolder(entry){try{let stat=await lstat3(entry.path);if(stat.isSymbolicLink()||!stat.isDirectory()||!(FOLDER_NAMES.has(basename4(entry.path))||entry.kind==="cache"&&isCachePath(entry.path)))return{path:entry.path,removed:!1,error:"no longer a plain folder"};if(existsSync10(join13(entry.path,".git")))return{path:entry.path,removed:!1,error:"holds a git repository"};return await rm(entry.path,{recursive:!0,force:!0}),{path:entry.path,removed:!0}}catch(error){return{path:entry.path,removed:!1,error:error instanceof Error?error.message:String(error)}}}async function removeWorktree(entry){if(entry.repo===void 0)return{path:entry.path,removed:!1,error:"no repository known"};try{let ran=await runTool("git worktree remove",["git","-C",entry.repo,"worktree","remove",entry.path]);return ran.code===0?{path:entry.path,removed:!0}:{path:entry.path,removed:!1,error:ran.stderr.trim()}}catch(error){return{path:entry.path,removed:!1,error:String(error)}}}async function applyAll(entries,done){let outcomes=[];for(let entry of entries){if(entry.action!=="remove")continue;let outcome=await(entry.kind==="worktree"?removeWorktree(entry):removeFolder(entry));outcomes.push(outcome),done(outcome)}return outcomes}import{readdir as readdir5,readFile,readlink}from"fs/promises";import{basename as basename5,join as join14}from"path";var DEV_PROGRAMS=new Set(["node","bun","deno","npm","npx","pnpm","yarn","bunx","vite","esbuild","ruby","java","cargo","go","php","php-fpm"]),DEV_PREFIXES=["python","php"],DOCKER_MS=5000,PID=/^\d+$/,PARENT=/^ \S+ (\d+)/;function isDevProgram(comm){return DEV_PROGRAMS.has(comm)||DEV_PREFIXES.some((prefix)=>comm.startsWith(prefix))}async function quietly(read){try{return await read()}catch{return}}async function lineage(pid,root){let seen=new Set;for(let current=pid;current>1&&!seen.has(current);){seen.add(current);let stat=await quietly(async()=>readFile(join14(root,String(current),"stat"),"utf8")),parent=Number(PARENT.exec(stat?.slice(stat.lastIndexOf(")")+1)??"")?.[1]);if(!Number.isInteger(parent))break;current=parent}return seen}async function processPlaces(root="/proc",self=process.pid){let own=await lineage(self,root),pids=(await quietly(async()=>readdir5(root))??[]).filter((name)=>PID.test(name)).map(Number).filter((pid)=>!own.has(pid)),places=[];return await Promise.all(pids.map(async(pid)=>{let comm=(await quietly(async()=>readFile(join14(root,String(pid),"comm"),"utf8")))?.trim();if(comm===void 0||!isDevProgram(comm))return;let cwd=await quietly(async()=>readlink(join14(root,String(pid),"cwd"))),argv=(await quietly(async()=>readFile(join14(root,String(pid),"cmdline"),"utf8")))?.split("\x00").filter((arg)=>arg.startsWith("/"))??[],who=`pid ${pid} ${comm}`;for(let path of[cwd,...argv.slice(1)])if(path!==void 0)places.push({path,who})})),places}async function containerPlaces(){let ids=await quietly(async()=>runCommand(["docker","ps","-q"],{timeoutMs:DOCKER_MS}));if(ids===void 0||ids.code!==0||ids.text.trim()==="")return[];let inspected=await quietly(async()=>runCommand(["docker","inspect","--format",'{{.Name}}{{range .Mounts}}{{if eq .Type "bind"}}\t{{.Source}}{{end}}{{end}}',...ids.text.trim().split(`
|
|
94
|
+
`)],{timeoutMs:DOCKER_MS}));if(inspected===void 0||inspected.code!==0)return[];return inspected.text.trim().split(`
|
|
95
|
+
`).flatMap((line)=>{let[name="",...sources]=line.split("\t");return sources.map((path)=>({path,who:`container ${basename5(name)}`}))})}var within=(path,folder)=>path===folder||path.startsWith(`${folder}/`);function userOf(folder,processes,containers){return processes.find((place)=>within(place.path,folder))?.who??containers.find((place)=>within(place.path,folder)||within(folder,place.path))?.who}var LARGE=104857600,BIG=1073741824,USAGE3=`ws sweep [options] [root]: lists the regenerable folders, caches and worktrees under root (the configured workspace by default, ${MAX_DEPTH3} levels down), largest first with the age of the repo's last commit
|
|
3394
96
|
|
|
3395
97
|
Dry unless --apply, which deletes for good, not trashed, after a confirm showing the total (off a terminal, pass --yes).
|
|
3396
98
|
Never touched: a symlink, a folder git tracks files in, a build folder git does not ignore. A worktree is removed with \`git worktree remove\`, never forced, and only when it is clean and every commit of its branch is on another branch or a remote.
|
|
3397
|
-
What a running dev process or container uses, a folder holding files another user owns and a worktree that is not removable stay listed as kept, with the reason, and count for nothing in the total
|
|
3398
|
-
var EXITS3 = [[0, "it listed, or removed every entry it was allowed to"], [1, "a removal failed or the confirm was declined"], [2, "a usage error, a missing root, or --apply off a terminal without --yes"]];
|
|
3399
|
-
var ONLY_KINDS = { worktrees: "worktree", folders: "folder", caches: "cache" };
|
|
3400
|
-
var OPTIONS3 = {
|
|
3401
|
-
apply: { type: "boolean", description: "delete what is listed as removable, after the confirm" },
|
|
3402
|
-
yes: { type: "boolean", short: "y", description: "with --apply, skip the confirm" },
|
|
3403
|
-
older: { type: "string", description: "only the entries whose repo last committed longer ago than this (30d, 12h)" },
|
|
3404
|
-
min: { type: "string", description: "only the entries of at least this size (500K, 10M, 1G)" },
|
|
3405
|
-
only: { type: "string", choices: Object.keys(ONLY_KINDS), description: "leave the other kinds out (.nuxt, .next, .turbo, .svelte-kit, __pycache__ and .gradle are caches; the global caches are listed with no root or with caches)" },
|
|
3406
|
-
docker: { type: "boolean", description: "add the docker system df output, which alone takes about ten seconds" },
|
|
3407
|
-
json: jsonOption("{root, entries: [{path, kind (folder, worktree or cache), bytes, committedAt, action (remove or keep), reason}], skipped: [{path, reason}], reclaimable, docker, removed?}")
|
|
3408
|
-
};
|
|
3409
|
-
async function dockerUsage() {
|
|
3410
|
-
if (Bun.which("docker") === null)
|
|
3411
|
-
return;
|
|
3412
|
-
try {
|
|
3413
|
-
const { code, stdout } = await runTool("docker system df", ["docker", "system", "df"], { timeoutMs: 1e4 });
|
|
3414
|
-
return code === 0 ? stdout.trimEnd() : undefined;
|
|
3415
|
-
} catch {
|
|
3416
|
-
return;
|
|
3417
|
-
}
|
|
3418
|
-
}
|
|
3419
|
-
async function sweep(args) {
|
|
3420
|
-
const { values, positionals } = parse(args, USAGE3, OPTIONS3, { exits: EXITS3, positionals: ["[root]"], replaces: "find ~/Workspace -name node_modules, du -sh and rm -rf by hand", examples: ["ws sweep", "ws sweep ~/Workspace --older 30d --min 100M --apply", "ws sweep --only worktrees --apply"] });
|
|
3421
|
-
if (positionals.length > 1)
|
|
3422
|
-
badUsage("give one root");
|
|
3423
|
-
const root = workspaceRoot({ given: positionals[0] });
|
|
3424
|
-
if (!existsSync11(root) || !statSync4(root).isDirectory())
|
|
3425
|
-
fail(`${root} is not a folder`);
|
|
3426
|
-
const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0);
|
|
3427
|
-
const minBytes = values.min === undefined ? 0 : parseSize(values.min);
|
|
3428
|
-
if (minBytes === undefined)
|
|
3429
|
-
badUsage(`--min takes a size such as 500K, 10M or 1G, not ${values.min}`);
|
|
3430
|
-
const now = Date.now();
|
|
3431
|
-
const progress = progressLine();
|
|
3432
|
-
let scanned;
|
|
3433
|
-
try {
|
|
3434
|
-
progress.update({ step: "finding the folders" });
|
|
3435
|
-
const found = await findCandidates(root, homedir6(), positionals.length === 0 || values.only === "caches");
|
|
3436
|
-
const wanted = values.only === undefined ? found.candidates : found.candidates.filter((candidate) => candidate.kind === ONLY_KINDS[values.only]);
|
|
3437
|
-
progress.update({ step: "sizing", done: 0, total: wanted.length, unit: "folders" });
|
|
3438
|
-
scanned = await inspect2({ candidates: wanted, skipped: found.skipped }, (done, total) => progress.update({ step: "sizing", done, total, unit: "folders" }));
|
|
3439
|
-
progress.update({ step: "looking for running servers and containers" });
|
|
3440
|
-
await keepWhatIsInUse(scanned.entries);
|
|
3441
|
-
} finally {
|
|
3442
|
-
progress.stop();
|
|
3443
|
-
}
|
|
3444
|
-
const { entries: all, skipped } = scanned;
|
|
3445
|
-
const entries = all.filter((entry) => entry.bytes >= minBytes && (olderMs === undefined || entry.committedAt !== undefined && now - entry.committedAt >= olderMs)).sort((a, b) => b.bytes - a.bytes || a.path.localeCompare(b.path));
|
|
3446
|
-
const removable = entries.filter((entry) => entry.action === "remove");
|
|
3447
|
-
const reclaimable = removable.reduce((sum, entry) => sum + entry.bytes, 0);
|
|
3448
|
-
const docker = values.docker === true ? await dockerUsage() : undefined;
|
|
3449
|
-
const json = values.json === true;
|
|
3450
|
-
if (values.apply === true && removable.length > 0 && values.yes !== true) {
|
|
3451
|
-
if (!json)
|
|
3452
|
-
print(root, entries, skipped.length, reclaimable, now);
|
|
3453
|
-
const agreed = await confirm(`Delete ${removable.length} ${removable.length === 1 ? "entry" : "entries"} (${tt(reclaimable)})?`, { default: false, hint: "pass --yes to skip the confirm" });
|
|
3454
|
-
if (agreed !== true) {
|
|
3455
|
-
if (json)
|
|
3456
|
-
fail("nothing deleted: the confirm was declined", 1, "pass --yes to skip the confirm");
|
|
3457
|
-
note("nothing deleted");
|
|
3458
|
-
return 1;
|
|
3459
|
-
}
|
|
3460
|
-
}
|
|
3461
|
-
const outcomes = values.apply === true ? await applyAll(removable, (outcome) => report2(root, outcome, json)) : undefined;
|
|
3462
|
-
const failed = outcomes?.filter((outcome) => !outcome.removed).length ?? 0;
|
|
3463
|
-
if (json) {
|
|
3464
|
-
printJson({ root, entries: entries.map((entry) => ({ path: entry.path, kind: entry.kind, bytes: entry.bytes, committedAt: entry.committedAt === undefined ? null : new Date(entry.committedAt).toISOString(), action: entry.action, reason: entry.reason ?? null })), skipped, reclaimable, docker: docker ?? null, ...outcomes === undefined ? {} : { removed: outcomes } });
|
|
3465
|
-
return failed === 0 ? 0 : 1;
|
|
3466
|
-
}
|
|
3467
|
-
if (outcomes === undefined) {
|
|
3468
|
-
print(root, entries, skipped.length, reclaimable, now);
|
|
3469
|
-
if (removable.length > 0)
|
|
3470
|
-
console.log("dry run, pass --apply to delete");
|
|
3471
|
-
} else {
|
|
3472
|
-
const bytes = new Map(removable.map((entry) => [entry.path, entry.bytes]));
|
|
3473
|
-
note(`freed ${tt(outcomes.reduce((sum, outcome) => sum + (outcome.removed ? bytes.get(outcome.path) ?? 0 : 0), 0))}`);
|
|
3474
|
-
}
|
|
3475
|
-
if (docker !== undefined)
|
|
3476
|
-
console.log(`
|
|
99
|
+
What a running dev process or container uses, a folder holding files another user owns and a worktree that is not removable stay listed as kept, with the reason, and count for nothing in the total.`,EXITS3=[[0,"it listed, or removed every entry it was allowed to"],[1,"a removal failed or the confirm was declined"],[2,"a usage error, a missing root, or --apply off a terminal without --yes"]],ONLY_KINDS={worktrees:"worktree",folders:"folder",caches:"cache"},OPTIONS3={apply:{type:"boolean",description:"delete what is listed as removable, after the confirm"},yes:{type:"boolean",short:"y",description:"with --apply, skip the confirm"},older:{type:"string",description:"only the entries whose repo last committed longer ago than this (30d, 12h)"},min:{type:"string",description:"only the entries of at least this size (500K, 10M, 1G)"},only:{type:"string",choices:Object.keys(ONLY_KINDS),description:"leave the other kinds out (.nuxt, .next, .turbo, .svelte-kit, __pycache__ and .gradle are caches; the global caches are listed with no root or with caches)"},docker:{type:"boolean",description:"add the docker system df output, which alone takes about ten seconds"},json:jsonOption("{root, entries: [{path, kind (folder, worktree or cache), bytes, committedAt, action (remove or keep), reason}], skipped: [{path, reason}], reclaimable, docker, removed?}")};async function dockerUsage(){if(Bun.which("docker")===null)return;try{let{code,stdout}=await runTool("docker system df",["docker","system","df"],{timeoutMs:1e4});return code===0?stdout.trimEnd():void 0}catch{return}}async function sweep(args){let{values,positionals}=parse(args,USAGE3,OPTIONS3,{exits:EXITS3,positionals:["[root]"],replaces:"find ~/Workspace -name node_modules, du -sh and rm -rf by hand",examples:["ws sweep","ws sweep ~/Workspace --older 30d --min 100M --apply","ws sweep --only worktrees --apply"]});if(positionals.length>1)badUsage("give one root");let root=workspaceRoot({given:positionals[0]});if(!existsSync11(root)||!statSync5(root).isDirectory())fail(`${root} is not a folder`);let olderMs=values.older===void 0?void 0:duration(values.older,"older",0),minBytes=values.min===void 0?0:parseSize(values.min);if(minBytes===void 0)badUsage(`--min takes a size such as 500K, 10M or 1G, not ${values.min}`);let now=Date.now(),progress=progressLine(),scanned;try{progress.update({step:"finding the folders"});let found=await findCandidates(root,homedir6(),positionals.length===0||values.only==="caches"),wanted=values.only===void 0?found.candidates:found.candidates.filter((candidate)=>candidate.kind===ONLY_KINDS[values.only]);progress.update({step:"sizing",done:0,total:wanted.length,unit:"folders"}),scanned=await inspect2({candidates:wanted,skipped:found.skipped},(done,total)=>progress.update({step:"sizing",done,total,unit:"folders"})),progress.update({step:"looking for running servers and containers"}),await keepWhatIsInUse(scanned.entries)}finally{progress.stop()}let{entries:all,skipped}=scanned,entries=all.filter((entry)=>entry.bytes>=minBytes&&(olderMs===void 0||entry.committedAt!==void 0&&now-entry.committedAt>=olderMs)).sort((a,b)=>b.bytes-a.bytes||a.path.localeCompare(b.path)),removable=entries.filter((entry)=>entry.action==="remove"),reclaimable=removable.reduce((sum,entry)=>sum+entry.bytes,0),docker=values.docker===!0?await dockerUsage():void 0,json=values.json===!0;if(values.apply===!0&&removable.length>0&&values.yes!==!0){if(!json)print(root,entries,skipped.length,reclaimable,now);if(await confirm(`Delete ${removable.length} ${removable.length===1?"entry":"entries"} (${tt(reclaimable)})?`,{default:!1,hint:"pass --yes to skip the confirm"})!==!0){if(json)fail("nothing deleted: the confirm was declined",1,"pass --yes to skip the confirm");return note("nothing deleted"),1}}let outcomes=values.apply===!0?await applyAll(removable,(outcome)=>report2(root,outcome,json)):void 0,failed=outcomes?.filter((outcome)=>!outcome.removed).length??0;if(json)return printJson({root,entries:entries.map((entry)=>({path:entry.path,kind:entry.kind,bytes:entry.bytes,committedAt:entry.committedAt===void 0?null:new Date(entry.committedAt).toISOString(),action:entry.action,reason:entry.reason??null})),skipped,reclaimable,docker:docker??null,...outcomes===void 0?{}:{removed:outcomes}}),failed===0?0:1;if(outcomes===void 0){if(print(root,entries,skipped.length,reclaimable,now),removable.length>0)console.log("dry run, pass --apply to delete")}else{let bytes=new Map(removable.map((entry)=>[entry.path,entry.bytes]));note(`freed ${tt(outcomes.reduce((sum,outcome)=>sum+(outcome.removed?bytes.get(outcome.path)??0:0),0))}`)}if(docker!==void 0)console.log(`
|
|
3477
100
|
docker (left to dclean):
|
|
3478
|
-
${docker}`);
|
|
3479
|
-
|
|
3480
|
-
}
|
|
3481
|
-
function report2(root, outcome, json) {
|
|
3482
|
-
if (json)
|
|
3483
|
-
return;
|
|
3484
|
-
if (outcome.removed)
|
|
3485
|
-
ok(`removed ${relative3(root, outcome.path)}`);
|
|
3486
|
-
else
|
|
3487
|
-
problem(`kept ${relative3(root, outcome.path)}`, outcome.error);
|
|
3488
|
-
}
|
|
3489
|
-
async function keepWhatIsInUse(entries) {
|
|
3490
|
-
const candidates = entries.filter((entry) => entry.action === "remove" && entry.project !== undefined);
|
|
3491
|
-
if (candidates.length === 0)
|
|
3492
|
-
return;
|
|
3493
|
-
const [processes, containers] = await Promise.all([processPlaces(), containerPlaces()]);
|
|
3494
|
-
for (const entry of candidates) {
|
|
3495
|
-
const who = userOf(entry.project, processes, containers);
|
|
3496
|
-
if (who !== undefined) {
|
|
3497
|
-
entry.action = "keep";
|
|
3498
|
-
entry.reason = `in use by ${who}`;
|
|
3499
|
-
}
|
|
3500
|
-
}
|
|
3501
|
-
}
|
|
3502
|
-
function print(root, entries, skipped, reclaimable, now) {
|
|
3503
|
-
if (entries.length === 0) {
|
|
3504
|
-
console.log("nothing to sweep");
|
|
3505
|
-
return;
|
|
3506
|
-
}
|
|
3507
|
-
const colors = paint(process.stdout);
|
|
3508
|
-
const path = role("path", process.stdout);
|
|
3509
|
-
const sized = (bytes) => {
|
|
3510
|
-
if (bytes >= BIG)
|
|
3511
|
-
return colors.red(tt(bytes));
|
|
3512
|
-
return bytes >= LARGE ? colors.yellow(tt(bytes)) : tt(bytes);
|
|
3513
|
-
};
|
|
3514
|
-
console.log(table([["size", "age", "what", "path", "note"], ...entries.map((entry) => [sized(entry.bytes), entry.committedAt === undefined ? colors.dim("-") : colors.dim(formatAge(entry.committedAt, now)), entry.kind, path(relative3(root, entry.path)), entry.action === "keep" ? colors.dim(`kept: ${entry.reason}`) : ""])], { header: true, align: ["right", "right", "left", "left", "left"] }));
|
|
3515
|
-
console.log(`
|
|
3516
|
-
${tt(reclaimable)} reclaimable${skipped === 0 ? "" : `, ${skipped} skipped (symlinks, tracked or not ignored by git)`}`);
|
|
3517
|
-
}
|
|
3518
|
-
|
|
3519
|
-
// src/cli.ts
|
|
3520
|
-
process26.exitCode = await runCli({
|
|
3521
|
-
name: "ws",
|
|
3522
|
-
about: "the repositories under a root: the ones needing attention, the folders worth reclaiming and their known vulnerabilities",
|
|
3523
|
-
replaces: "a cd, git status and du loop over each repository of the workspace, and a bun audit run in each",
|
|
3524
|
-
examples: ["ws repos", ["ws sweep --older 30d", "what a month of idle repos weighs"], "ws audit"],
|
|
3525
|
-
commands: {
|
|
3526
|
-
repos: { summary: "the git repositories that need attention: dirty, ahead or behind, worktrees, unreleased commits", run: repos },
|
|
3527
|
-
sweep: { summary: "the regenerable folders, caches and clean worktrees, largest first, deleted only on --apply", run: sweep },
|
|
3528
|
-
audit: { summary: "the known vulnerabilities of the Bun, Composer, Cargo and uv repositories, one table per repository", run: audit }
|
|
3529
|
-
}
|
|
3530
|
-
});
|
|
101
|
+
${docker}`);return failed===0?0:1}function report2(root,outcome,json){if(json)return;if(outcome.removed)ok(`removed ${relative3(root,outcome.path)}`);else problem(`kept ${relative3(root,outcome.path)}`,outcome.error)}async function keepWhatIsInUse(entries){let candidates=entries.filter((entry)=>entry.action==="remove"&&entry.project!==void 0);if(candidates.length===0)return;let[processes,containers]=await Promise.all([processPlaces(),containerPlaces()]);for(let entry of candidates){let who=userOf(entry.project,processes,containers);if(who!==void 0)entry.action="keep",entry.reason=`in use by ${who}`}}function print(root,entries,skipped,reclaimable,now){if(entries.length===0){console.log("nothing to sweep");return}let colors=paint(process.stdout),path=role("path",process.stdout),sized=(bytes)=>{if(bytes>=BIG)return colors.red(tt(bytes));return bytes>=LARGE?colors.yellow(tt(bytes)):tt(bytes)};console.log(table([["size","age","what","path","note"],...entries.map((entry)=>[sized(entry.bytes),entry.committedAt===void 0?colors.dim("-"):colors.dim(formatAge(entry.committedAt,now)),entry.kind,path(relative3(root,entry.path)),entry.action==="keep"?colors.dim(`kept: ${entry.reason}`):""])],{header:!0,align:["right","right","left","left","left"]})),console.log(`
|
|
102
|
+
${tt(reclaimable)} reclaimable${skipped===0?"":`, ${skipped} skipped (symlinks, tracked or not ignored by git)`}`)}process26.exitCode=await runCli({name:"ws",about:"the repositories under a root: the ones needing attention, the folders worth reclaiming and their known vulnerabilities",replaces:"a cd, git status and du loop over each repository of the workspace, and a bun audit run in each",examples:["ws repos",["ws sweep --older 30d","what a month of idle repos weighs"],"ws audit"],commands:{repos:{summary:"the git repositories that need attention: dirty, ahead or behind, worktrees, unreleased commits",run:repos},sweep:{summary:"the regenerable folders, caches and clean worktrees, largest first, deleted only on --apply",run:sweep},audit:{summary:"the known vulnerabilities of the Bun, Composer, Cargo and uv repositories, one table per repository",run:audit}}});
|