@kaynooo/cli-workspace 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1684 @@
1
+ #!/usr/bin/env -S bun --no-env-file
2
+ // @bun
3
+
4
+ // src/repos-cli.ts
5
+ import process16 from "process";
6
+
7
+ // ../kit/src/advisory.ts
8
+ var SEVERITIES = ["low", "moderate", "high", "critical"];
9
+ function severityRank(severity) {
10
+ return SEVERITIES.indexOf(severity);
11
+ }
12
+ function isIgnored(advisory, ignore) {
13
+ return ignore.includes(advisory.ghsa ?? "") || ignore.includes(String(advisory.id));
14
+ }
15
+ // ../kit/src/args.ts
16
+ import process8 from "process";
17
+ import { parseArgs } from "util";
18
+
19
+ // ../kit/src/format.ts
20
+ import process6 from "process";
21
+
22
+ // ../kit/src/style.ts
23
+ import process5 from "process";
24
+
25
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
26
+ function x(s) {
27
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
28
+ if (!/^[a-f0-9]+$/.test(r))
29
+ return [0, 0, 0];
30
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
31
+ if (t === 3 || t === 4) {
32
+ let c = n(r[0] + r[0]), u = n(r[1] + r[1]), h = n(r[2] + r[2]), g = t === 4 ? n(r[3] + r[3]) : undefined;
33
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
34
+ }
35
+ if (t !== 6 && t !== 8)
36
+ throw Error(`Invalid hex color length: ${t}`);
37
+ let a = n(r.slice(0, 2)), b = n(r.slice(2, 4)), o = n(r.slice(4, 6)), y = t === 8 ? n(r.slice(6, 8)) : undefined;
38
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
39
+ throw Error(`Invalid hex color value: ${s}`);
40
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
41
+ }
42
+ function A(s) {
43
+ let [r, t, n, a] = s;
44
+ if (a)
45
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
46
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
47
+ }
48
+ function R(s, r, t) {
49
+ s = (s % 360 + 360) % 360, t /= 100;
50
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
51
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
52
+ return Math.round(255 * y);
53
+ };
54
+ return [a(0), a(8), a(4)];
55
+ }
56
+ function k(s) {
57
+ let [r, t, n] = s;
58
+ r /= 255, t /= 255, n /= 255;
59
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
60
+ if (a !== b) {
61
+ let u = a - b;
62
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
63
+ o = (t - n) / u + (t < n ? 6 : 0);
64
+ else if (a === t)
65
+ o = (n - r) / u + 2;
66
+ else
67
+ o = (r - t) / u + 4;
68
+ o /= 6;
69
+ }
70
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
71
+ }
72
+ function H(s, r, t) {
73
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
74
+ let n = (a) => {
75
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
76
+ return Math.round(255 * o);
77
+ };
78
+ return [n(5), n(3), n(1)];
79
+ }
80
+ function f(s) {
81
+ let [r, t, n] = s;
82
+ r /= 255, t /= 255, n /= 255;
83
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = a - b, y = 0, c = a === 0 ? 0 : o / a, u = a;
84
+ if (o !== 0) {
85
+ if (a === r)
86
+ y = (t - n) / o + (t < n ? 6 : 0);
87
+ else if (a === t)
88
+ y = (n - r) / o + 2;
89
+ else
90
+ y = (r - t) / o + 4;
91
+ y /= 6;
92
+ }
93
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
94
+ }
95
+ function O(s) {
96
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
97
+ if (a === 1)
98
+ return [0, 0, 0, 100];
99
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
100
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
101
+ }
102
+ function v(s, r, t, n) {
103
+ return s /= 100, r /= 100, t /= 100, n /= 100, [Math.round(255 * (1 - s) * (1 - n)), Math.round(255 * (1 - r) * (1 - n)), Math.round(255 * (1 - t) * (1 - n))];
104
+ }
105
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
106
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
107
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
108
+ function T(s) {
109
+ let r = m(s[0] / 255), t = m(s[1] / 255), n = m(s[2] / 255), a = Math.cbrt(0.4122214708 * r + 0.5363325363 * t + 0.0514459929 * n), b = Math.cbrt(0.2119034982 * r + 0.6806995451 * t + 0.1073969566 * n), o = Math.cbrt(0.0883024619 * r + 0.2817188376 * t + 0.6299787005 * n);
110
+ return [i(0.2104542553 * a + 0.793617785 * b - 0.0040720468 * o, 4), i(1.9779984951 * a - 2.428592205 * b + 0.4505937099 * o, 4), i(0.0259040371 * a + 0.7827717662 * b - 0.808675766 * o, 4)];
111
+ }
112
+ function M(s, r, t) {
113
+ let n = (s + 0.3963377774 * r + 0.2158037573 * t) ** 3, a = (s - 0.1055613458 * r - 0.0638541728 * t) ** 3, b = (s - 0.0894841775 * r - 1.291485548 * t) ** 3, o = p(4.0767416621 * n - 3.3077115913 * a + 0.2309699292 * b), y = p(-1.2684380046 * n + 2.6097574011 * a - 0.3413193965 * b), c = p(-0.0041960863 * n - 0.7034186147 * a + 1.707614701 * b), u = (h) => Math.min(255, Math.max(0, Math.round(h * 255)));
114
+ return [u(o), u(y), u(c)];
115
+ }
116
+ function d(s) {
117
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
118
+ return [i(r, 4), i(a, 4), i(b, 2)];
119
+ }
120
+ function C(s, r, t) {
121
+ let n = t * Math.PI / 180;
122
+ return M(s, r * Math.cos(n), r * Math.sin(n));
123
+ }
124
+ function l(s) {
125
+ let r = s / 255;
126
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
127
+ }
128
+
129
+ class e {
130
+ r;
131
+ g;
132
+ b;
133
+ a;
134
+ constructor(s, r, t, n = 1) {
135
+ this.r = s, this.g = r, this.b = t, this.a = n;
136
+ }
137
+ static from(s, r) {
138
+ if (s === "hex") {
139
+ let [t, n, a, b] = x(r);
140
+ return new e(t, n, a, b);
141
+ }
142
+ if (s === "rgb") {
143
+ if (Array.isArray(r)) {
144
+ let [o, y, c, u] = r;
145
+ return new e(o, y, c, u);
146
+ }
147
+ let { r: t, g: n, b: a, a: b } = r;
148
+ return new e(t, n, a, b);
149
+ }
150
+ if (s === "hsl") {
151
+ let t, n, a, b;
152
+ if (Array.isArray(r))
153
+ [t, n, a, b] = r;
154
+ else
155
+ ({ h: t, s: n, l: a, a: b } = r);
156
+ let [o, y, c] = R(t, n, a);
157
+ return new e(o, y, c, b);
158
+ }
159
+ if (s === "hsv") {
160
+ let t, n, a, b;
161
+ if (Array.isArray(r))
162
+ [t, n, a, b] = r;
163
+ else
164
+ ({ h: t, s: n, v: a, a: b } = r);
165
+ let [o, y, c] = H(t, n, a);
166
+ return new e(o, y, c, b);
167
+ }
168
+ if (s === "cmyk") {
169
+ let t, n, a, b, o;
170
+ if (Array.isArray(r))
171
+ [t, n, a, b, o] = r;
172
+ else
173
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
174
+ let [y, c, u] = v(t, n, a, b);
175
+ return new e(y, c, u, o);
176
+ }
177
+ if (s === "oklch") {
178
+ let t, n, a, b;
179
+ if (Array.isArray(r))
180
+ [t, n, a, b] = r;
181
+ else
182
+ ({ l: t, c: n, h: a, a: b } = r);
183
+ let [o, y, c] = C(t, n, a);
184
+ return new e(o, y, c, b);
185
+ }
186
+ if (s === "oklab") {
187
+ let t, n, a, b;
188
+ if (Array.isArray(r))
189
+ [t, n, a, b] = r;
190
+ else
191
+ ({ l: t, a: n, b: a, alpha: b } = r);
192
+ let [o, y, c] = M(t, n, a);
193
+ return new e(o, y, c, b);
194
+ }
195
+ throw Error("Invalid input");
196
+ }
197
+ to(s) {
198
+ switch (s) {
199
+ case "rgb":
200
+ return [this.r, this.g, this.b];
201
+ case "rgba":
202
+ return [this.r, this.g, this.b, this.a];
203
+ case "hex":
204
+ return A([this.r, this.g, this.b]);
205
+ case "hexa":
206
+ return A([this.r, this.g, this.b, this.a]);
207
+ case "hsl":
208
+ return k([this.r, this.g, this.b]);
209
+ case "hsla":
210
+ return [...k([this.r, this.g, this.b]), this.a];
211
+ case "hsv":
212
+ return f([this.r, this.g, this.b]);
213
+ case "hsva":
214
+ return [...f([this.r, this.g, this.b]), this.a];
215
+ case "cmyk":
216
+ return O([this.r, this.g, this.b]);
217
+ case "cmyka":
218
+ return [...O([this.r, this.g, this.b]), this.a];
219
+ case "oklch":
220
+ return d([this.r, this.g, this.b]);
221
+ case "oklcha":
222
+ return [...d([this.r, this.g, this.b]), this.a];
223
+ case "oklab":
224
+ return T([this.r, this.g, this.b]);
225
+ case "oklaba":
226
+ return [...T([this.r, this.g, this.b]), this.a];
227
+ default:
228
+ return [this.r, this.g, this.b];
229
+ }
230
+ }
231
+ getLuminance() {
232
+ let s = l(this.r), r = l(this.g), t = l(this.b);
233
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
234
+ }
235
+ contrastRatio(s) {
236
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
237
+ return (n + 0.05) / (a + 0.05);
238
+ }
239
+ bestContrastForeground() {
240
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
241
+ return t >= n ? s : r;
242
+ }
243
+ }
244
+
245
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
246
+ var r = 39;
247
+ var o = 49;
248
+ var f2 = "\x1B[";
249
+ var C2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, r], red: [31, r], green: [32, r], yellow: [33, r], blue: [34, r], magenta: [35, r], cyan: [36, r], white: [37, r], gray: [90, r], grey: [90, r], blackBright: [90, r], redBright: [91, r], greenBright: [92, r], yellowBright: [93, r], blueBright: [94, r], magentaBright: [95, r], cyanBright: [96, r], whiteBright: [97, r], bgBlack: [40, o], bgRed: [41, o], bgGreen: [42, o], bgYellow: [43, o], bgBlue: [44, o], bgMagenta: [45, o], bgCyan: [46, o], bgWhite: [47, o], bgBlackBright: [100, o], bgRedBright: [101, o], bgGreenBright: [102, o], bgYellowBright: [103, o], bgBlueBright: [104, o], bgMagentaBright: [105, o], bgCyanBright: [106, o], bgWhiteBright: [107, o], rgb: (i, n, a, l = "fg") => [`${l === "fg" ? 38 : 48};2;${i};${n};${a}`, l === "fg" ? r : o], hex: (i, n = "fg") => {
250
+ let [a, l, s] = e.from("hex", i).to("rgb");
251
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
252
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
253
+ var b = new Set(["", "1", "2", "3", "true"]);
254
+ function h(i, n = globalThis.process?.env ?? {}) {
255
+ if (n.FORCE_COLOR !== undefined)
256
+ return b.has(n.FORCE_COLOR);
257
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
258
+ return false;
259
+ return i?.isTTY === true;
260
+ }
261
+ function d2(i, n, a) {
262
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
263
+ return n;
264
+ let l = "", s = "";
265
+ for (let g = 0, y = i.length;g < y; g++) {
266
+ let [c, p] = i[g];
267
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
268
+ }
269
+ return l + n + s;
270
+ }
271
+ function u(i, n = []) {
272
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
273
+ let g = C2[s];
274
+ if (Array.isArray(g))
275
+ return u(i, [...n, g]);
276
+ if (typeof g === "function")
277
+ return (...y) => u(i, [...n, g(...y)]);
278
+ throw Error(`Unknown style: ${String(s)}`);
279
+ } });
280
+ }
281
+ function le(i = {}) {
282
+ return u(i);
283
+ }
284
+ var t = le();
285
+
286
+ // ../kit/src/theme.ts
287
+ import { existsSync as existsSync3, readFileSync, statSync } from "fs";
288
+ import { homedir as homedir2 } from "os";
289
+ import { join as join3, resolve as resolve2 } from "path";
290
+ import process4 from "process";
291
+
292
+ // ../kit/src/config.ts
293
+ import { existsSync } from "fs";
294
+ import { dirname, join, resolve } from "path";
295
+ import process2 from "process";
296
+ function findUp(names, from = process2.cwd(), stop = () => false) {
297
+ const wanted = typeof names === "string" ? [names] : names;
298
+ for (let dir = resolve(from);; dir = dirname(dir)) {
299
+ const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
300
+ if (found !== undefined)
301
+ return found;
302
+ if (stop(dir) || dirname(dir) === dir)
303
+ return;
304
+ }
305
+ }
306
+
307
+ // ../kit/src/user-config.ts
308
+ import { existsSync as existsSync2 } from "fs";
309
+ import { homedir } from "os";
310
+ import { join as join2 } from "path";
311
+ import process3 from "process";
312
+ function configBase(where = {}) {
313
+ const xdg = where.xdg ?? (where.home === undefined ? process3.env.XDG_CONFIG_HOME : undefined);
314
+ return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
315
+ }
316
+ function userConfigPath(bin, where = {}) {
317
+ return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
318
+ }
319
+ function userConfigReadPath(bin, legacy = [], where = {}) {
320
+ const current = userConfigPath(bin, where);
321
+ if (existsSync2(current))
322
+ return current;
323
+ const base = configBase(where);
324
+ return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
325
+ }
326
+
327
+ // ../kit/src/theme.ts
328
+ var DEFAULT = {
329
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
330
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501" },
331
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
332
+ bins: {}
333
+ };
334
+ var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
335
+ var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
336
+ var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#" };
337
+ var PRESETS = {
338
+ default: {},
339
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"] },
340
+ mono: { colors: MONO, accents: ["bold"] },
341
+ ascii: { glyphs: ASCII }
342
+ };
343
+ var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
344
+ var HEX = /^#[0-9a-f]{6}$/i;
345
+ var CONTROL = /\p{Cc}/u;
346
+ var MAX_FILE_BYTES = 64 * 1024;
347
+ var SPACES = /\s+/;
348
+ function isColorSpec(spec) {
349
+ if (typeof spec === "number")
350
+ return Number.isInteger(spec) && spec >= 0 && spec <= 255;
351
+ return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
352
+ }
353
+ function tinted(colors, spec) {
354
+ if (typeof spec === "number")
355
+ return colors.ansi256(spec);
356
+ return spec.trim().split(SPACES).reduce((chain, token) => HEX.test(token) ? chain.hex(token) : chain[token] ?? chain, colors);
357
+ }
358
+ function isRecord(value) {
359
+ return typeof value === "object" && value !== null && !Array.isArray(value);
360
+ }
361
+ function readThemeFile(path, warn) {
362
+ try {
363
+ const stat = statSync(path, { throwIfNoEntry: false });
364
+ if (stat === undefined)
365
+ return;
366
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
367
+ warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
368
+ return;
369
+ }
370
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
371
+ if (isRecord(parsed))
372
+ return parsed;
373
+ warn(`${path} is not a JSON object, theme ignored`);
374
+ } catch (error) {
375
+ warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
376
+ }
377
+ return;
378
+ }
379
+ function applyPreset(theme, name, warn, where) {
380
+ if (name === undefined)
381
+ return;
382
+ if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
383
+ warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
384
+ return;
385
+ }
386
+ const preset = PRESETS[name];
387
+ Object.assign(theme.colors, preset.colors);
388
+ Object.assign(theme.glyphs, preset.glyphs);
389
+ if (preset.accents !== undefined)
390
+ theme.accents = [...preset.accents];
391
+ return name;
392
+ }
393
+ function applyFile(theme, file, where, warn) {
394
+ if (isRecord(file.colors)) {
395
+ for (const [key, value] of Object.entries(file.colors)) {
396
+ if (!Object.hasOwn(DEFAULT.colors, key))
397
+ warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
398
+ else if (!isColorSpec(value))
399
+ warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
400
+ else
401
+ theme.colors[key] = value;
402
+ }
403
+ }
404
+ if (isRecord(file.glyphs)) {
405
+ for (const [key, value] of Object.entries(file.glyphs)) {
406
+ if (!Object.hasOwn(DEFAULT.glyphs, key))
407
+ warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
408
+ else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
409
+ warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
410
+ else
411
+ theme.glyphs[key] = value;
412
+ }
413
+ }
414
+ if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
415
+ theme.accents = [...file.accents];
416
+ else if (file.accents !== undefined)
417
+ warn(`${where}: accents must be a non-empty list of colours`);
418
+ if (isRecord(file.bins)) {
419
+ for (const [bin, value] of Object.entries(file.bins)) {
420
+ if (isColorSpec(value))
421
+ theme.bins[bin] = value;
422
+ else
423
+ warn(`${where}: bin ${bin} has no valid colour`);
424
+ }
425
+ }
426
+ }
427
+ function endsWalk(home) {
428
+ return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
429
+ }
430
+ var warned = new Set;
431
+ function warnOnce(message) {
432
+ if (warned.has(message))
433
+ return;
434
+ warned.add(message);
435
+ console.error(`warning: theme ${message}`);
436
+ }
437
+ function isPath(chosen) {
438
+ return chosen.includes("/") || chosen.endsWith(".json");
439
+ }
440
+ function loadTheme({ env = process4.env, from = process4.cwd(), home = homedir2(), warn = warnOnce } = {}) {
441
+ const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
442
+ const sources = [];
443
+ const chosen = env.KIT_THEME ?? "";
444
+ const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
445
+ if (isPath(chosen))
446
+ wanted.push(resolve2(from, chosen));
447
+ const files = [];
448
+ for (const path of wanted) {
449
+ const file = path === undefined ? undefined : readThemeFile(path, warn);
450
+ if (path !== undefined && file !== undefined)
451
+ files.push({ path, file });
452
+ }
453
+ let preset = "default";
454
+ if (chosen !== "" && !isPath(chosen)) {
455
+ preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
456
+ } else {
457
+ const named = files.findLast(({ file }) => file.preset !== undefined);
458
+ if (named !== undefined)
459
+ preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
460
+ }
461
+ for (const { path, file } of files) {
462
+ applyFile(theme, file, path, warn);
463
+ sources.push(path);
464
+ }
465
+ return { theme, sources, preset };
466
+ }
467
+ var current;
468
+ var currentKey = "";
469
+ function activeTheme() {
470
+ const key = `${process4.cwd()}\x00${process4.env.KIT_THEME ?? ""}\x00${process4.env.XDG_CONFIG_HOME ?? ""}`;
471
+ if (current === undefined || key !== currentKey) {
472
+ current = loadTheme();
473
+ currentKey = key;
474
+ }
475
+ return current;
476
+ }
477
+
478
+ // ../kit/src/style.ts
479
+ var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:" };
480
+ function takesControlCodes(stream, env = process5.env) {
481
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
482
+ }
483
+ function paint(stream, env = process5.env) {
484
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
485
+ }
486
+ function marked(mark, text, stream, detail, env = process5.env) {
487
+ const colors = paint(stream, env);
488
+ let head = MARK_WORDS[mark];
489
+ if (takesControlCodes(stream, env)) {
490
+ const { theme } = activeTheme();
491
+ head = tinted(colors.bold, theme.colors[mark])(theme.glyphs[mark]);
492
+ }
493
+ return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
494
+ }
495
+ function ok(text, detail) {
496
+ console.log(marked("ok", text, process5.stdout, detail));
497
+ }
498
+ function note(text, detail) {
499
+ console.log(marked("note", text, process5.stdout, detail));
500
+ }
501
+ function problem(text, detail) {
502
+ console.error(marked("problem", text, process5.stderr, detail));
503
+ }
504
+ function role(name, stream, env = process5.env) {
505
+ const colors = paint(stream, env);
506
+ return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name]) : colors;
507
+ }
508
+ var STATUS_WORDS = {
509
+ passed: ["passed", "success", "succeeded", "ok"],
510
+ failed: ["failed", "failure", "error", "errored"],
511
+ running: ["running", "in_progress", "started"],
512
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
513
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
514
+ };
515
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
516
+
517
+ // ../kit/src/format.ts
518
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
519
+ function formatSeconds(total) {
520
+ let rest = Math.max(0, Math.round(total));
521
+ const amounts = UNITS.map(([unit, size]) => {
522
+ const amount = Math.floor(rest / size);
523
+ rest -= amount * size;
524
+ return `${amount}${unit}`;
525
+ });
526
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
527
+ if (first === -1)
528
+ return "0s";
529
+ const next = amounts[first + 1];
530
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
531
+ }
532
+ function formatDuration(ms) {
533
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
534
+ }
535
+ function upTo(text, separator) {
536
+ const end = text.indexOf(separator);
537
+ return end === -1 ? text : text.slice(0, end);
538
+ }
539
+ function formatAge(date, now = Date.now()) {
540
+ const at = typeof date === "number" ? date : Date.parse(date);
541
+ if (Number.isNaN(at))
542
+ return "-";
543
+ const seconds = (now - at) / 1000;
544
+ return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
545
+ }
546
+ function truncate(text, width) {
547
+ return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
548
+ }
549
+ var LINE_BREAKS = /\s*\n\s*/g;
550
+ var ESCAPE = String.fromCharCode(27);
551
+ function textWidth(text) {
552
+ return Bun.stringWidth(text);
553
+ }
554
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process6.stdout } = {}) {
555
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
556
+ const widths = [];
557
+ for (const row of cells) {
558
+ for (const [index, cell] of row.entries())
559
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
560
+ }
561
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
562
+ const colors = paint(stream);
563
+ const lines = shown.map((row) => row.map((cell, index) => {
564
+ const width = widths[index] ?? 0;
565
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
566
+ if (align[index] === "right")
567
+ return `${gap}${cell}`;
568
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
569
+ }).join(" ").trimEnd());
570
+ const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
571
+ return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
572
+ `);
573
+ }
574
+ function narrow(rows, widths, limit) {
575
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
576
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
577
+ const floor = 8;
578
+ while (used() > limit) {
579
+ let widest = -1;
580
+ for (const [index, width] of widths.entries()) {
581
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
582
+ widest = index;
583
+ }
584
+ if (widest === -1)
585
+ break;
586
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
587
+ }
588
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
589
+ }
590
+ function printJson(value) {
591
+ console.log(JSON.stringify(value, undefined, 2));
592
+ }
593
+
594
+ // ../kit/src/help.ts
595
+ import process7 from "process";
596
+ var OPTIONAL = /\[[^\]]+\]/g;
597
+ var USAGE_PREFIX = /^usage:\s*/i;
598
+ var FULL_STOP = /\.$/;
599
+ function usageLine(usage, colors = paint(process7.stdout)) {
600
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
601
+ }
602
+ function helpText(usage, options, colors = paint(process7.stdout), { examples = [], replaces, exits = [] } = {}) {
603
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
604
+ `);
605
+ }
606
+ function exitRows(exits, colors = paint(process7.stdout)) {
607
+ if (exits.length === 0)
608
+ return [];
609
+ const width = Math.max(...exits.map(([code]) => String(code).length));
610
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
611
+ }
612
+ function replacesRows(replaces, colors = paint(process7.stdout)) {
613
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
614
+ }
615
+ function wantsHelpJson(env = process7.env) {
616
+ return env.KIT_HELP === "json";
617
+ }
618
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
619
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
620
+ `);
621
+ const first = lines[0];
622
+ const colon = first.indexOf(": ");
623
+ const prose = lines[lines.indexOf("") + 1] ?? "";
624
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
625
+ return {
626
+ synopsis: colon === -1 ? first : first.slice(0, colon),
627
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
628
+ ...replaces === undefined ? {} : { replaces },
629
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
630
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
631
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
632
+ };
633
+ }
634
+ function exampleRows(examples, colors = paint(process7.stdout)) {
635
+ if (examples.length === 0)
636
+ return [];
637
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
638
+ }
639
+ function optionRows(options, colors = paint(process7.stdout)) {
640
+ const rows = Object.entries(options).map(([name, option]) => {
641
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
642
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
643
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
644
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
645
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
646
+ });
647
+ const width = Math.max(0, ...rows.map((row) => row.width));
648
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
649
+ }
650
+
651
+ // ../kit/src/text.ts
652
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
653
+ function distance(a, b) {
654
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
655
+ for (const [i, left] of [...a].entries()) {
656
+ const current = [i + 1];
657
+ for (const [j, right] of [...b].entries())
658
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
659
+ previous = current;
660
+ }
661
+ return previous[b.length] ?? 0;
662
+ }
663
+ function closest(name, names) {
664
+ const started = names.find((known) => known.startsWith(name));
665
+ if (started !== undefined)
666
+ return started;
667
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
668
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
669
+ }
670
+ // ../kit/src/input.ts
671
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
672
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
673
+ function duration(value, name, fallback, unit = "s") {
674
+ if (value === undefined)
675
+ return fallback;
676
+ const match = DURATION.exec(value.trim());
677
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
678
+ if (ms < 1)
679
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
680
+ return ms;
681
+ }
682
+
683
+ // ../kit/src/args.ts
684
+ var DASHES = /^-+/;
685
+ function jsonOption(holds) {
686
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
687
+ }
688
+
689
+ class Exit extends Error {
690
+ code;
691
+ hint;
692
+ constructor(message, code, hint) {
693
+ super(message);
694
+ this.code = code;
695
+ this.hint = hint;
696
+ }
697
+ }
698
+ function fail(message, code = 2, hint) {
699
+ throw new Exit(message, code, hint);
700
+ }
701
+
702
+ class UsageError extends Exit {
703
+ constructor(message, hint) {
704
+ super(message, 2, hint);
705
+ }
706
+ }
707
+ function badUsage(message) {
708
+ throw new UsageError(message);
709
+ }
710
+
711
+ class HelpShown extends Exit {
712
+ constructor() {
713
+ super("help shown", 0);
714
+ }
715
+ }
716
+
717
+ class Completing {
718
+ options;
719
+ positionals;
720
+ candidates;
721
+ constructor(options, positionals = [], candidates = {}) {
722
+ this.options = options;
723
+ this.positionals = positionals;
724
+ this.candidates = candidates;
725
+ }
726
+ }
727
+ var completion = { active: false };
728
+ var OUTPUT_OPTIONS = {
729
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
730
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
731
+ };
732
+ function applyOutput(color, plain, env = process8.env) {
733
+ const when = plain === true ? "never" : color ?? "auto";
734
+ if (when === "auto")
735
+ return;
736
+ if (when !== "always" && when !== "never")
737
+ badUsage(`--color takes auto, always or never, not ${when}`);
738
+ if (when === "always") {
739
+ env.FORCE_COLOR = "1";
740
+ delete env.NO_COLOR;
741
+ } else {
742
+ env.NO_COLOR = "1";
743
+ delete env.FORCE_COLOR;
744
+ }
745
+ }
746
+ function parse(args, usage, options, settings = {}) {
747
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
748
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
749
+ const listing = listed(all, settings.allowNegative === true);
750
+ if (completion.active)
751
+ throw new Completing(listing, settings.positionals, settings.candidates);
752
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
753
+ let parsed;
754
+ try {
755
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
756
+ } catch (error) {
757
+ const message = parseError(error);
758
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
759
+ }
760
+ const values = parsed.values;
761
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
762
+ if (values.help === true) {
763
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
764
+ throw new HelpShown;
765
+ }
766
+ checkChoices(parsed.values, all);
767
+ checkConflicts(parsed.values, all);
768
+ if (settings.positionals !== undefined)
769
+ checkPositionals(parsed.positionals, settings.positionals);
770
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
771
+ }
772
+ function splitRest(args, passes) {
773
+ const separator = passes ? args.indexOf("--") : -1;
774
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
775
+ }
776
+ function splitTrailing(args, options, count) {
777
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
778
+ let seen = 0;
779
+ if (count === 0)
780
+ return { own: args, rest: undefined };
781
+ for (let at = 0;at < args.length; at++) {
782
+ const word = args[at];
783
+ if (word === "--")
784
+ break;
785
+ if (word.startsWith("-")) {
786
+ if (takesValue(word))
787
+ at++;
788
+ continue;
789
+ }
790
+ seen++;
791
+ if (seen === count)
792
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
793
+ }
794
+ return { own: args, rest: undefined };
795
+ }
796
+ function listed(options, allowNegative) {
797
+ if (!allowNegative)
798
+ return options;
799
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
800
+ if (option.type !== "boolean" || option.negative === undefined)
801
+ return [[name, option]];
802
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
803
+ }));
804
+ }
805
+ function withAliases(args, options) {
806
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
807
+ if (named.size === 0)
808
+ return args;
809
+ const separator = args.indexOf("--");
810
+ const own = separator === -1 ? args : args.slice(0, separator);
811
+ return [...own.map((arg) => {
812
+ const at = arg.indexOf("=");
813
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
814
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
815
+ }), ...separator === -1 ? [] : args.slice(separator)];
816
+ }
817
+ function withBare(args, options) {
818
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
819
+ if (bare.size === 0)
820
+ return args;
821
+ const separator = args.indexOf("--");
822
+ const own = separator === -1 ? args : args.slice(0, separator);
823
+ return [...own.flatMap((arg, index) => {
824
+ const optional = bare.get(arg);
825
+ const next = own[index + 1];
826
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
827
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
828
+ }), ...separator === -1 ? [] : args.slice(separator)];
829
+ }
830
+ function checkConflicts(values, options) {
831
+ const given = (name) => values[name] !== undefined && values[name] !== false;
832
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
833
+ const other = given(name) ? conflicts.find(given) : undefined;
834
+ if (other !== undefined)
835
+ badUsage(`--${name} cannot be used with --${other}`);
836
+ }
837
+ }
838
+ function checkChoices(values, options) {
839
+ for (const [name, option] of Object.entries(options)) {
840
+ if (option.choices === undefined)
841
+ continue;
842
+ const given = values[name];
843
+ for (const value of Array.isArray(given) ? given : [given]) {
844
+ if (typeof value === "string")
845
+ oneOf(value, name, option.choices);
846
+ }
847
+ }
848
+ }
849
+ function oneOf(value, name, choices) {
850
+ if (!choices.includes(value))
851
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
852
+ return value;
853
+ }
854
+ function checkPositionals(given, names) {
855
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
856
+ const required = names.filter((name) => !name.startsWith("[")).length;
857
+ if (given.length < required)
858
+ badUsage(`missing ${names[given.length]}`);
859
+ if (!variadic && given.length > names.length)
860
+ badUsage(`unexpected argument ${given[names.length]}`);
861
+ }
862
+ function joinDashValues(args, options) {
863
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
864
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
865
+ const joined = [];
866
+ for (let i = 0;i < args.length; i++) {
867
+ const arg = args[i] ?? "";
868
+ if (arg === "--")
869
+ return [...joined, ...args.slice(i)];
870
+ const name = longOf.get(arg);
871
+ const next = args[i + 1];
872
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
873
+ joined.push(`--${name}=${next}`);
874
+ i++;
875
+ } else {
876
+ joined.push(arg);
877
+ }
878
+ }
879
+ return joined;
880
+ }
881
+ function parseError(error) {
882
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
883
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
884
+ }
885
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
886
+ function nearestOption(message, options, allowNegative) {
887
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
888
+ if (typed === undefined)
889
+ return;
890
+ const word = typed.replace(DASHES, "");
891
+ if (word.length < 2 && !typed.startsWith("--"))
892
+ return;
893
+ const known = Object.entries(options).flatMap(([name, option]) => [
894
+ ...option.short === undefined ? [] : [`-${option.short}`],
895
+ `--${name}`,
896
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
897
+ ]);
898
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
899
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
900
+ }
901
+ // ../kit/src/process.ts
902
+ import { constants } from "os";
903
+ import process9 from "process";
904
+ var KILL_GRACE_MS = 2000;
905
+ function exitCodeOf(code, signal) {
906
+ if (code !== null)
907
+ return code;
908
+ if (typeof signal === "number")
909
+ return 128 + signal;
910
+ return signal === null ? 129 : 128 + constants.signals[signal];
911
+ }
912
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
913
+ const chunks = [];
914
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
915
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
916
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
917
+ const timers = [];
918
+ const killGroup = (killing) => {
919
+ if (state.done)
920
+ return;
921
+ try {
922
+ if (grouped)
923
+ process9.kill(-proc.pid, killing);
924
+ else
925
+ proc.kill(killing);
926
+ } catch {}
927
+ };
928
+ const stop = () => {
929
+ killGroup("SIGTERM");
930
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
931
+ };
932
+ const onAbort = () => stop();
933
+ if (timeoutMs !== undefined) {
934
+ timers.push(setTimeout(() => {
935
+ state.timedOut = true;
936
+ stop();
937
+ }, timeoutMs));
938
+ }
939
+ if (signal?.aborted === true)
940
+ onAbort();
941
+ else
942
+ signal?.addEventListener("abort", onAbort, { once: true });
943
+ onStart?.({ kill: (killing) => killGroup(killing) });
944
+ const drain = async (stream, name) => {
945
+ for await (const data of stream) {
946
+ if (state.failure !== undefined)
947
+ continue;
948
+ try {
949
+ onChunk?.({ stream: name, data });
950
+ } catch (error) {
951
+ state.failure = error;
952
+ stop();
953
+ continue;
954
+ }
955
+ if (state.kept + data.length > maxBytes) {
956
+ state.truncated = true;
957
+ continue;
958
+ }
959
+ state.kept += data.length;
960
+ chunks.push({ stream: name, data });
961
+ }
962
+ };
963
+ try {
964
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
965
+ await proc.exited;
966
+ } finally {
967
+ state.done = true;
968
+ for (const timer of timers)
969
+ clearTimeout(timer);
970
+ signal?.removeEventListener("abort", onAbort);
971
+ }
972
+ if (state.failure !== undefined)
973
+ throw state.failure;
974
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
975
+ let output;
976
+ let text;
977
+ return {
978
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
979
+ chunks,
980
+ timedOut: state.timedOut,
981
+ truncated: state.truncated,
982
+ get output() {
983
+ return output ??= joined();
984
+ },
985
+ get text() {
986
+ return text ??= (output ??= joined()).toString();
987
+ }
988
+ };
989
+ }
990
+
991
+ // ../kit/src/progress.ts
992
+ var ESC = String.fromCharCode(27);
993
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
994
+ var RESET_STYLE = `${ESC}[0m`;
995
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
996
+
997
+ // ../kit/src/tool.ts
998
+ import process10 from "process";
999
+ function cwdGone() {
1000
+ try {
1001
+ process10.cwd();
1002
+ return false;
1003
+ } catch {
1004
+ return true;
1005
+ }
1006
+ }
1007
+
1008
+ class SpawnError extends Error {
1009
+ missing;
1010
+ constructor(message, missing) {
1011
+ super(message);
1012
+ this.missing = missing;
1013
+ }
1014
+ }
1015
+ function spawnFailure(command, error) {
1016
+ const gone = cwdGone();
1017
+ const missing = !gone && error?.code === "ENOENT";
1018
+ return new SpawnError(`${command}: ${error instanceof Error ? error.message : String(error)}${gone ? " (the working directory was removed)" : ""}`, missing);
1019
+ }
1020
+ async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
1021
+ let ran;
1022
+ try {
1023
+ ran = await runCommand(argv, { env: process10.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
1024
+ } catch (error) {
1025
+ throw spawnFailure(label, error);
1026
+ }
1027
+ if (ran.timedOut)
1028
+ throw new Error(`${label}: no answer in ${formatDuration(timeoutMs ?? 0)}`);
1029
+ const decoders = { stdout: new TextDecoder, stderr: new TextDecoder };
1030
+ const streams = { stdout: "", stderr: "" };
1031
+ for (const { stream, data } of ran.chunks)
1032
+ streams[stream] += decoders[stream].decode(data, { stream: true });
1033
+ streams.stdout += decoders.stdout.decode();
1034
+ streams.stderr += decoders.stderr.decode();
1035
+ return { code: ran.code, ...streams };
1036
+ }
1037
+ // ../kit/src/cli.ts
1038
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
1039
+ import { dirname as dirname3, join as join5 } from "path";
1040
+ import process12 from "process";
1041
+
1042
+ // ../kit/src/usage.ts
1043
+ import { appendFileSync, mkdirSync } from "fs";
1044
+ import { homedir as homedir3 } from "os";
1045
+ import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1046
+ import process11 from "process";
1047
+
1048
+ // ../kit/src/logs.ts
1049
+ var DAY_MS = 24 * 60 * 60 * 1000;
1050
+ var CLI_FOLDER = "kaynooo-cli";
1051
+
1052
+ // ../kit/src/usage.ts
1053
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1054
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1055
+ var LONGEST_NAME = 40;
1056
+ var usageError;
1057
+ function noteUsageError(message) {
1058
+ usageError = message;
1059
+ }
1060
+ function stateHome(env = process11.env) {
1061
+ const dir = env.XDG_STATE_HOME;
1062
+ return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1063
+ }
1064
+ function usagePath(env = process11.env) {
1065
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1066
+ }
1067
+ function usageRecorded(env = process11.env) {
1068
+ const off = env.KAYNOOO_CLI_NO_USAGE;
1069
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1070
+ }
1071
+ function flagNames(argv) {
1072
+ const end = argv.indexOf("--");
1073
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1074
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1075
+ }
1076
+ function usageEntry(bin, command, argv, code, now = new Date) {
1077
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1078
+ usageError = undefined;
1079
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1080
+ }
1081
+ function recordUsage(entry, env = process11.env) {
1082
+ if (!usageRecorded(env))
1083
+ return;
1084
+ try {
1085
+ const path = usagePath(env);
1086
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1087
+ appendFileSync(path, `${JSON.stringify(entry)}
1088
+ `, { mode: 384 });
1089
+ } catch {}
1090
+ }
1091
+
1092
+ // ../kit/src/cli.ts
1093
+ var LEVEL_OPTIONS = {
1094
+ ...OUTPUT_OPTIONS,
1095
+ help: { type: "boolean", short: "h", description: "show this help" }
1096
+ };
1097
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1098
+ async function commandRows(all, colors) {
1099
+ const commands = shown(all);
1100
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
1101
+ const groups = new Map([["Commands:", []]]);
1102
+ const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
1103
+ for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
1104
+ const heading = group === undefined ? "Commands:" : `${group}:`;
1105
+ const rows = groups.get(heading) ?? [];
1106
+ rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
1107
+ groups.set(heading, rows);
1108
+ }
1109
+ return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
1110
+ }
1111
+ function shown(commands) {
1112
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
1113
+ }
1114
+ function takeOutputFlags(argv) {
1115
+ let index = 0;
1116
+ for (;index < argv.length; index++) {
1117
+ const word = argv[index];
1118
+ if (word === "--plain")
1119
+ applyOutput(undefined, true);
1120
+ else if (word.startsWith("--color="))
1121
+ applyOutput(word.slice("--color=".length), undefined);
1122
+ else if (word === "--color" && argv[index + 1] !== undefined)
1123
+ applyOutput(argv[++index], undefined);
1124
+ else
1125
+ break;
1126
+ }
1127
+ return argv.slice(index);
1128
+ }
1129
+ async function resolveSummary(summary) {
1130
+ return typeof summary === "string" ? summary : summary();
1131
+ }
1132
+ function scopeOf(commands, extra, aliases) {
1133
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
1134
+ }
1135
+ async function expand(scope, words) {
1136
+ if (scope.lazy.length === 0)
1137
+ return scope;
1138
+ const commands = { ...scope.commands };
1139
+ for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
1140
+ for (const [name, command] of Object.entries(added))
1141
+ commands[name] ??= command;
1142
+ }
1143
+ return { ...scope, commands, lazy: [] };
1144
+ }
1145
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
1146
+ const colors = paint(stream);
1147
+ const prefix = path.join(" ");
1148
+ const summary = await resolveSummary(lazySummary);
1149
+ if (wantsHelpJson())
1150
+ return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
1151
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1152
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
1153
+ const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
1154
+ return [
1155
+ header(colors, summary),
1156
+ "",
1157
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
1158
+ ...replacesRows(replaces, colors),
1159
+ "",
1160
+ ...await commandRows(commands, colors),
1161
+ ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
1162
+ "",
1163
+ colors.bold("Options:"),
1164
+ ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
1165
+ ...exampleRows(examples ?? [], colors),
1166
+ "",
1167
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
1168
+ ].join(`
1169
+ `);
1170
+ }
1171
+ function printError(prefix, message, hint, cause) {
1172
+ const colors = paint(process12.stderr);
1173
+ const styled = takesControlCodes(process12.stderr);
1174
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1175
+ const under = (label, text, tint) => text === undefined ? "" : `
1176
+ ${styled ? tint(label) : `${label}:`} ${text}`;
1177
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1178
+ }
1179
+ function printJsonError(message, hint, cause) {
1180
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1181
+ }
1182
+ function wantsJson(argv) {
1183
+ const end = argv.indexOf("--");
1184
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1185
+ }
1186
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
1187
+ if (error instanceof HelpShown)
1188
+ return 0;
1189
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1190
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1191
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1192
+ if (error instanceof Exit && error.code === 2)
1193
+ noteUsageError(error.message);
1194
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1195
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1196
+ return error instanceof Exit ? error.code : 1;
1197
+ }
1198
+ async function dispatch(level, typed, { version, redact }) {
1199
+ const prefix = level.path.join(" ");
1200
+ let argv;
1201
+ try {
1202
+ argv = takeOutputFlags(typed);
1203
+ } catch (error) {
1204
+ return reportThrown(prefix, error);
1205
+ }
1206
+ const [name, ...args] = argv;
1207
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
1208
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
1209
+ try {
1210
+ return await fallback.run([]);
1211
+ } catch (error) {
1212
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
1213
+ }
1214
+ }
1215
+ if (name === undefined && level.path.length > 1) {
1216
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stderr));
1217
+ return 2;
1218
+ }
1219
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1220
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stdout));
1221
+ return 0;
1222
+ }
1223
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
1224
+ console.log(version);
1225
+ return 0;
1226
+ }
1227
+ let command = level.commands[level.aliases?.[name] ?? name];
1228
+ let rest = args;
1229
+ let ran = name;
1230
+ if (command === undefined && level.lazy.length > 0) {
1231
+ level = await expand(level, [...level.path.slice(1), ...argv]);
1232
+ command = level.commands[level.aliases?.[name] ?? name];
1233
+ }
1234
+ if (command === undefined && level.defaultCommand !== undefined) {
1235
+ command = level.commands[level.defaultCommand];
1236
+ rest = argv;
1237
+ ran = level.defaultCommand;
1238
+ }
1239
+ if (command === undefined) {
1240
+ const meant = closest(name, Object.keys(shown(level.commands)));
1241
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
1242
+ return 2;
1243
+ }
1244
+ if ("commands" in command) {
1245
+ const { summary } = command;
1246
+ 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 });
1247
+ }
1248
+ try {
1249
+ return await command.run(rest);
1250
+ } catch (error) {
1251
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
1252
+ }
1253
+ }
1254
+ var COMPLETE = "__complete";
1255
+ var FILES = "__files__";
1256
+ async function completingOf(run) {
1257
+ completion.active = true;
1258
+ try {
1259
+ await run([]);
1260
+ } catch (error) {
1261
+ if (error instanceof Completing)
1262
+ return error;
1263
+ } finally {
1264
+ completion.active = false;
1265
+ }
1266
+ return new Completing({});
1267
+ }
1268
+ async function optionsOf(run) {
1269
+ return (await completingOf(run)).options;
1270
+ }
1271
+ function candidateLine(candidate) {
1272
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
1273
+ }
1274
+ function positionalBeingTyped(before, { options, positionals }) {
1275
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1276
+ let index = 0;
1277
+ let at = 0;
1278
+ while (at < before.length) {
1279
+ const word = before[at];
1280
+ if (word === "--") {
1281
+ index += before.length - at - 1;
1282
+ break;
1283
+ }
1284
+ if (!word.startsWith("-"))
1285
+ index++;
1286
+ else if (takesValue(word))
1287
+ at++;
1288
+ at++;
1289
+ }
1290
+ const last = positionals.at(-1);
1291
+ if (index < positionals.length)
1292
+ return positionals[index];
1293
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1294
+ }
1295
+ async function leafCandidates(run, words) {
1296
+ const completing = await completingOf(run);
1297
+ if ((words.at(-1) ?? "").startsWith("-"))
1298
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1299
+ const flag = words.at(-2);
1300
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1301
+ if (option?.type === "string") {
1302
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1303
+ return values === undefined ? [FILES] : values.map(candidateLine);
1304
+ }
1305
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
1306
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
1307
+ return values === undefined ? [FILES] : values.map(candidateLine);
1308
+ }
1309
+ async function candidates(scope, defaultCommand, words, before = []) {
1310
+ const [word = "", ...rest] = words;
1311
+ const listing = rest.length === 0 && !word.startsWith("-");
1312
+ let { commands, aliases } = scope;
1313
+ let command = commands[aliases?.[word] ?? word];
1314
+ if (listing || command === undefined) {
1315
+ ({ commands, aliases } = await expand(scope, [...before, ...words]));
1316
+ command = commands[aliases?.[word] ?? word];
1317
+ }
1318
+ if (listing) {
1319
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1320
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1321
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1322
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1323
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
1324
+ }
1325
+ if (command === undefined) {
1326
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1327
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
1328
+ }
1329
+ return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1330
+ }
1331
+ async function printCandidates(found) {
1332
+ for (const line of await found)
1333
+ console.log(line);
1334
+ return 0;
1335
+ }
1336
+ function packageVersion(entry = Bun.main) {
1337
+ for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1338
+ try {
1339
+ const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
1340
+ if (typeof version === "string")
1341
+ return version;
1342
+ } catch {}
1343
+ if (dirname3(dir) === dir)
1344
+ return "0.0.0";
1345
+ }
1346
+ }
1347
+ async function runCli(cli, argv = process12.argv.slice(2)) {
1348
+ const version = cli.version ?? packageVersion();
1349
+ if (argv[0] === COMPLETE)
1350
+ return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1351
+ 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 });
1352
+ if (cli.usage !== false) {
1353
+ try {
1354
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1355
+ } catch {}
1356
+ }
1357
+ return code;
1358
+ }
1359
+ function commandPath(scope, argv) {
1360
+ const path = [];
1361
+ let level = scope;
1362
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
1363
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1364
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1365
+ if (command === undefined)
1366
+ break;
1367
+ path.push(word);
1368
+ if (!("commands" in command))
1369
+ break;
1370
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
1371
+ }
1372
+ return path.length === 0 ? undefined : path.join(" ");
1373
+ }
1374
+ async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1375
+ if (argv[0] === COMPLETE)
1376
+ return printCandidates(leafCandidates(run, argv.slice(1)));
1377
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1378
+ console.log(version ?? packageVersion());
1379
+ return 0;
1380
+ }
1381
+ let code;
1382
+ try {
1383
+ code = await run(argv);
1384
+ } catch (error) {
1385
+ code = reportThrown(name, error, redact, wantsJson(argv));
1386
+ }
1387
+ if (usage !== false) {
1388
+ try {
1389
+ recordUsage(usageEntry(name, undefined, argv, code));
1390
+ } catch {}
1391
+ }
1392
+ return code;
1393
+ }
1394
+ // ../kit/src/secrets.ts
1395
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1396
+ // ../kit/src/sessions.ts
1397
+ var {Glob } = globalThis.Bun;
1398
+ var SESSION_FILES = new Glob("*.json");
1399
+ var ACCOUNT_DIRS = new Glob("*/sessions");
1400
+ // ../kit/src/size.ts
1401
+ var SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i;
1402
+ var POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
1403
+ function parseSize(text, bareUnit = 1) {
1404
+ const match = SIZE.exec(text.trim());
1405
+ if (match === null)
1406
+ return;
1407
+ const suffix = match[2].toLowerCase();
1408
+ return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
1409
+ }
1410
+ // src/repos.ts
1411
+ import { existsSync as existsSync5, statSync as statSync2 } from "fs";
1412
+ import { homedir as homedir4 } from "os";
1413
+ import { join as join7, relative, resolve as resolve3 } from "path";
1414
+ import process15 from "process";
1415
+
1416
+ // src/repos-scan.ts
1417
+ import { existsSync as existsSync4 } from "fs";
1418
+ import { readdir } from "fs/promises";
1419
+ import { basename, join as join6 } from "path";
1420
+ import process14 from "process";
1421
+ var MAX_DEPTH = 3;
1422
+ var CONCURRENCY = 8;
1423
+ var GIT_MS = 1e4;
1424
+ var FETCH_MS = 30000;
1425
+ var AHEAD_BEHIND = /\+(\d+) -(\d+)/;
1426
+ var PACKAGE_TAG = /^(.+)-v\d/;
1427
+ var REASONS = ["dirty", "unpushed", "unreleased", "behind"];
1428
+ function reasonsOf(repo) {
1429
+ const reasons = [];
1430
+ if (repo.dirty > 0)
1431
+ reasons.push("dirty");
1432
+ if ((repo.ahead ?? 0) > 0)
1433
+ reasons.push("unpushed");
1434
+ if ((repo.behind ?? 0) > 0)
1435
+ reasons.push("behind");
1436
+ if ((repo.unreleased ?? 0) > 0)
1437
+ reasons.push("unreleased");
1438
+ return reasons;
1439
+ }
1440
+ async function findRepos(root, skip) {
1441
+ if (existsSync4(join6(root, ".git")))
1442
+ return [root];
1443
+ const found = [];
1444
+ async function walk(dir, depth) {
1445
+ let entries;
1446
+ try {
1447
+ entries = await readdir(dir, { withFileTypes: true });
1448
+ } catch {
1449
+ return;
1450
+ }
1451
+ for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
1452
+ if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith(".") || skip.has(entry.name))
1453
+ continue;
1454
+ const path = join6(dir, entry.name);
1455
+ if (existsSync4(join6(path, ".git")))
1456
+ found.push(path);
1457
+ else if (depth < MAX_DEPTH)
1458
+ await walk(path, depth + 1);
1459
+ }
1460
+ }
1461
+ await walk(root, 1);
1462
+ return found;
1463
+ }
1464
+ async function read(path, args, timeoutMs = GIT_MS) {
1465
+ try {
1466
+ const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...process14.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs });
1467
+ return ran.code === 0 && !ran.timedOut ? ran.text.trim() : undefined;
1468
+ } catch {
1469
+ return;
1470
+ }
1471
+ }
1472
+ async function commitsSince(path, tag, folder) {
1473
+ const count = await read(path, ["rev-list", "--count", `${tag}..HEAD`, ...folder === undefined ? [] : ["--", folder]]);
1474
+ return Number(count ?? 0);
1475
+ }
1476
+ async function packageReleases(path) {
1477
+ const names = new Set;
1478
+ for (const tag of (await read(path, ["tag", "--list"]) ?? "").split(`
1479
+ `)) {
1480
+ const name = PACKAGE_TAG.exec(tag)?.[1];
1481
+ if (name !== undefined)
1482
+ names.add(name);
1483
+ }
1484
+ const releases = [];
1485
+ for (const name of [...names].toSorted()) {
1486
+ const folder = [join6("packages", name), name].find((candidate) => existsSync4(join6(path, candidate)));
1487
+ const tag = folder === undefined ? undefined : await read(path, ["describe", "--tags", "--abbrev=0", "--match", `${name}-v*`]);
1488
+ if (folder !== undefined && tag !== undefined && tag !== "")
1489
+ releases.push({ name, tag, unreleased: await commitsSince(path, tag, folder) });
1490
+ }
1491
+ return releases;
1492
+ }
1493
+ async function inspect(path, fetch) {
1494
+ const fetched = fetch ? await read(path, ["fetch", "--quiet"], FETCH_MS) : "";
1495
+ const [status, worktrees, packages] = await Promise.all([
1496
+ read(path, ["status", "--porcelain=v2", "--branch"]),
1497
+ read(path, ["worktree", "list", "--porcelain"]),
1498
+ packageReleases(path)
1499
+ ]);
1500
+ 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 };
1501
+ for (const line of (status ?? "").split(`
1502
+ `)) {
1503
+ if (line.startsWith("# branch.head "))
1504
+ state.branch = line.slice("# branch.head ".length);
1505
+ else if (line.startsWith("# branch.upstream "))
1506
+ state.upstream = line.slice("# branch.upstream ".length);
1507
+ else if (line.startsWith("# branch.ab "))
1508
+ [state.ahead, state.behind] = AHEAD_BEHIND.exec(line)?.slice(1).map(Number);
1509
+ else if (line !== "" && !line.startsWith("#"))
1510
+ state.dirty++;
1511
+ }
1512
+ state.worktrees = Math.max(0, (worktrees ?? "").split(`
1513
+ `).filter((line) => line.startsWith("worktree ")).length - 1);
1514
+ if (packages.length > 0) {
1515
+ state.unreleased = packages.reduce((sum, release) => sum + release.unreleased, 0);
1516
+ } else {
1517
+ const tag = await read(path, ["describe", "--tags", "--abbrev=0"]);
1518
+ if (tag !== undefined && tag !== "") {
1519
+ state.tag = tag;
1520
+ state.unreleased = await commitsSince(path, tag);
1521
+ }
1522
+ }
1523
+ return state;
1524
+ }
1525
+ function pullBlocker(repo) {
1526
+ if (repo.unreadable)
1527
+ return "unreadable";
1528
+ if (repo.fetchFailed)
1529
+ return "fetch failed";
1530
+ if (repo.branch === "(detached)")
1531
+ return "detached HEAD";
1532
+ if (repo.upstream === null)
1533
+ return "no upstream";
1534
+ if (repo.dirty > 0)
1535
+ return `${repo.dirty} dirty ${repo.dirty === 1 ? "file" : "files"}`;
1536
+ return (repo.ahead ?? 0) > 0 ? `diverged, ${repo.ahead} ahead` : undefined;
1537
+ }
1538
+ function firstLine(text) {
1539
+ const end = text.indexOf(`
1540
+ `);
1541
+ return end === -1 ? text : text.slice(0, end);
1542
+ }
1543
+ async function fastForward(path) {
1544
+ try {
1545
+ const ran = await runCommand(["git", "--no-optional-locks", "merge", "--ff-only", "--quiet", "@{upstream}"], { cwd: path, env: { ...process14.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs: GIT_MS });
1546
+ if (ran.timedOut)
1547
+ return "timed out";
1548
+ return ran.code === 0 ? undefined : firstLine(ran.text.trim()) || `exit ${ran.code}`;
1549
+ } catch (error) {
1550
+ return error instanceof Error ? error.message : String(error);
1551
+ }
1552
+ }
1553
+ async function pool(items, limit, task) {
1554
+ const results = new Array(items.length);
1555
+ let next = 0;
1556
+ async function worker() {
1557
+ while (next < items.length) {
1558
+ const index = next++;
1559
+ results[index] = await task(items[index]);
1560
+ }
1561
+ }
1562
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1563
+ return results;
1564
+ }
1565
+
1566
+ // src/repos.ts
1567
+ var USAGE = `repos [options] [root]: the git repositories under root (~/Workspace by default) that need attention, with their branch, dirty files, ahead/behind their upstream, linked worktrees and commits since their latest tag
1568
+
1569
+ A repository with nothing to report is left out unless --all. A monorepo tagging its packages <folder>-v<version> counts the unreleased commits per package folder. The walk goes ${MAX_DEPTH} levels deep, stops at a .git and skips node_modules, hidden folders and the names in "skip" of ~/.config/kaynooo-cli/repos.json.
1570
+
1571
+ Ahead and behind are those of the last fetch unless --fetch refreshes the upstreams first, which reaches the remote.
1572
+ --pull fetches, then fast-forwards the repositories listed that are clean, on a branch and only behind their upstream, and touches nothing else: a dirty, ahead, diverged or detached one is reported as skipped. A repository pulled is listed again as it now stands.
1573
+ --path prints only the paths of the repositories listed, one per line, for xargs -d '\\n'.`;
1574
+ var EXITS = [[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"]];
1575
+ var OPTIONS = {
1576
+ all: { type: "boolean", short: "a", description: "list the repositories with nothing to report too" },
1577
+ only: { type: "string", choices: REASONS, description: "only the repositories with this reason: dirty, unpushed, unreleased or behind" },
1578
+ fetch: { type: "boolean", description: "refresh the upstreams first (reaches the remote)" },
1579
+ pull: { type: "boolean", description: "fetch, then fast-forward the clean repositories listed that are only behind their upstream (reaches the remote)" },
1580
+ path: { type: "boolean", conflicts: ["json"], description: "print only the paths of the repositories listed, one per line" },
1581
+ json: jsonOption("[{name, path, branch, upstream, dirty, ahead, behind, worktrees, tag, unreleased, packages, reasons, fetchFailed, unreadable}]")
1582
+ };
1583
+ async function skipped() {
1584
+ const file = userConfigReadPath("repos");
1585
+ if (!existsSync5(file))
1586
+ return new Set;
1587
+ try {
1588
+ const config = await Bun.file(file).json();
1589
+ return new Set(Array.isArray(config.skip) ? config.skip.filter((name) => typeof name === "string") : []);
1590
+ } catch (error) {
1591
+ fail(`${file} does not parse: ${error instanceof Error ? error.message : String(error)}`);
1592
+ }
1593
+ }
1594
+ function releasedCell(repo) {
1595
+ if (repo.packages.length > 0)
1596
+ return repo.packages.filter((release) => release.unreleased > 0).map((release) => `${release.name} ${release.unreleased}`).join(", ") || "-";
1597
+ return repo.tag === null || repo.unreleased === 0 ? "-" : `${repo.unreleased} since ${repo.tag}`;
1598
+ }
1599
+ function syncCell(repo, stream = process15.stdout) {
1600
+ const colors = paint(stream);
1601
+ const ahead = repo.ahead ?? 0;
1602
+ const behind = repo.behind ?? 0;
1603
+ if (repo.upstream === null)
1604
+ return colors.dim("no upstream");
1605
+ const parts = [ahead > 0 ? colors.green(`+${ahead}`) : "", behind > 0 ? colors.red(`-${behind}`) : ""].filter(Boolean);
1606
+ const diverged = takesControlCodes(stream) && ahead > 0 && behind > 0;
1607
+ return parts.length === 0 ? colors.dim("-") : `${parts.join(" ")}${diverged ? colors.yellow(" diverged") : ""}`;
1608
+ }
1609
+ function branchCell(repo) {
1610
+ const colors = paint(process15.stdout);
1611
+ if (repo.unreadable)
1612
+ return colors.red("? (unreadable)");
1613
+ return repo.branch === "(detached)" ? colors.yellow(repo.branch) : repo.branch;
1614
+ }
1615
+ function row(repo, shown) {
1616
+ const colors = paint(process15.stdout);
1617
+ const tint = role("path", process15.stdout);
1618
+ const unreleased = releasedCell(repo);
1619
+ return [
1620
+ tint(shown),
1621
+ branchCell(repo),
1622
+ repo.dirty === 0 ? colors.dim("-") : colors.yellow(String(repo.dirty)),
1623
+ syncCell(repo),
1624
+ repo.worktrees === 0 ? colors.dim("-") : String(repo.worktrees),
1625
+ unreleased === "-" ? colors.dim("-") : colors.cyan(unreleased)
1626
+ ];
1627
+ }
1628
+ async function repos(args) {
1629
+ const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["[root]"], exits: EXITS, replaces: "a cd, git status, git log and git tag loop over each repository of the workspace", examples: ["repos", "repos ~/Workspace --only unreleased --fetch", ["repos --only behind --pull", "fast-forward what is behind and clean"], ["repos --only dirty --path", "the paths, for xargs"]] });
1630
+ const root = resolve3(positionals[0] ?? join7(homedir4(), "Workspace"));
1631
+ if (!existsSync5(root) || !statSync2(root).isDirectory())
1632
+ fail(`no folder ${root}`);
1633
+ const only = values.only === undefined ? undefined : oneOf(values.only, "only", REASONS);
1634
+ const paths = await findRepos(root, await skipped());
1635
+ const states = await pool(paths, CONCURRENCY, async (path) => inspect(path, values.fetch === true || values.pull === true));
1636
+ const keeps = (repo) => {
1637
+ const reasons = reasonsOf(repo);
1638
+ return only === undefined ? values.all === true || reasons.length > 0 || repo.unreadable : reasons.includes(only);
1639
+ };
1640
+ let failedPulls = 0;
1641
+ if (values.pull === true) {
1642
+ const log = values.json === true || values.path === true ? console.error : console.log;
1643
+ for (const [index, repo] of states.entries()) {
1644
+ if (!keeps(repo) || (repo.behind ?? 0) === 0)
1645
+ continue;
1646
+ const blocker = pullBlocker(repo);
1647
+ const refused = blocker === undefined ? await fastForward(repo.path) : undefined;
1648
+ if (blocker !== undefined) {
1649
+ log(marked("note", `${repo.name} skipped`, process15.stdout, blocker));
1650
+ } else if (refused !== undefined) {
1651
+ failedPulls++;
1652
+ log(marked("problem", `${repo.name} not pulled`, process15.stdout, refused));
1653
+ } else {
1654
+ log(marked("ok", `${repo.name} pulled`, process15.stdout, `${repo.behind} ${repo.behind === 1 ? "commit" : "commits"}`));
1655
+ states[index] = await inspect(repo.path, false);
1656
+ }
1657
+ }
1658
+ }
1659
+ const kept = states.filter(keeps);
1660
+ if (values.path === true) {
1661
+ for (const repo of kept)
1662
+ console.log(repo.path);
1663
+ return failedPulls > 0 ? 1 : 0;
1664
+ }
1665
+ if (values.json === true) {
1666
+ printJson(kept.map((repo) => ({ ...repo, reasons: reasonsOf(repo) })));
1667
+ return failedPulls > 0 ? 1 : 0;
1668
+ }
1669
+ const label = role("label", process15.stdout);
1670
+ if (kept.length === 0) {
1671
+ console.log(label(`nothing needs attention in ${states.length} repositories`));
1672
+ return failedPulls > 0 ? 1 : 0;
1673
+ }
1674
+ console.log(table([["repo", "branch", "dirty", "ahead/behind", "worktrees", "unreleased"], ...kept.map((repo) => row(repo, relative(root, repo.path) || repo.name))], { header: true, align: ["left", "left", "right", "left", "right", "left"] }));
1675
+ const failed = kept.filter((repo) => repo.fetchFailed).map((repo) => repo.name);
1676
+ if (failed.length > 0)
1677
+ console.log(label(`fetch failed for ${failed.join(", ")}`));
1678
+ if (values.fetch !== true)
1679
+ console.log(label("ahead/behind as of the last fetch, --fetch refreshes them"));
1680
+ return failedPulls > 0 ? 1 : 0;
1681
+ }
1682
+
1683
+ // src/repos-cli.ts
1684
+ process16.exitCode = await runMain({ name: "repos", run: repos });