@kaynooo/cli-git 0.15.0 → 0.15.2

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