@kaynooo/cli-base 0.0.0-stage → 0.4.1

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/proof.js ADDED
@@ -0,0 +1,1168 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/proof.ts
5
+ import process9 from "process";
6
+
7
+ // ../kit/src/args.ts
8
+ import process3 from "process";
9
+ import { parseArgs } from "util";
10
+
11
+ // ../kit/src/style.ts
12
+ import process from "process";
13
+
14
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
15
+ function x(s) {
16
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
17
+ if (!/^[a-f0-9]+$/.test(r))
18
+ return [0, 0, 0];
19
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
20
+ if (t === 3 || t === 4) {
21
+ 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;
22
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
23
+ }
24
+ if (t !== 6 && t !== 8)
25
+ throw Error(`Invalid hex color length: ${t}`);
26
+ 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;
27
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
28
+ throw Error(`Invalid hex color value: ${s}`);
29
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
30
+ }
31
+ function A(s) {
32
+ let [r, t, n, a] = s;
33
+ if (a)
34
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
35
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
36
+ }
37
+ function R(s, r, t) {
38
+ s = (s % 360 + 360) % 360, t /= 100;
39
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
40
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
41
+ return Math.round(255 * y);
42
+ };
43
+ return [a(0), a(8), a(4)];
44
+ }
45
+ function k(s) {
46
+ let [r, t, n] = s;
47
+ r /= 255, t /= 255, n /= 255;
48
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
49
+ if (a !== b) {
50
+ let u = a - b;
51
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
52
+ o = (t - n) / u + (t < n ? 6 : 0);
53
+ else if (a === t)
54
+ o = (n - r) / u + 2;
55
+ else
56
+ o = (r - t) / u + 4;
57
+ o /= 6;
58
+ }
59
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
60
+ }
61
+ function H(s, r, t) {
62
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
63
+ let n = (a) => {
64
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
65
+ return Math.round(255 * o);
66
+ };
67
+ return [n(5), n(3), n(1)];
68
+ }
69
+ function f(s) {
70
+ let [r, t, n] = s;
71
+ r /= 255, t /= 255, n /= 255;
72
+ 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;
73
+ if (o !== 0) {
74
+ if (a === r)
75
+ y = (t - n) / o + (t < n ? 6 : 0);
76
+ else if (a === t)
77
+ y = (n - r) / o + 2;
78
+ else
79
+ y = (r - t) / o + 4;
80
+ y /= 6;
81
+ }
82
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
83
+ }
84
+ function O(s) {
85
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
86
+ if (a === 1)
87
+ return [0, 0, 0, 100];
88
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
89
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
90
+ }
91
+ function v(s, r, t, n) {
92
+ 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))];
93
+ }
94
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
95
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
96
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
97
+ function T(s) {
98
+ 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);
99
+ 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)];
100
+ }
101
+ function M(s, r, t) {
102
+ 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)));
103
+ return [u(o), u(y), u(c)];
104
+ }
105
+ function d(s) {
106
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
107
+ return [i(r, 4), i(a, 4), i(b, 2)];
108
+ }
109
+ function C(s, r, t) {
110
+ let n = t * Math.PI / 180;
111
+ return M(s, r * Math.cos(n), r * Math.sin(n));
112
+ }
113
+ function l(s) {
114
+ let r = s / 255;
115
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
116
+ }
117
+
118
+ class e {
119
+ r;
120
+ g;
121
+ b;
122
+ a;
123
+ constructor(s, r, t, n = 1) {
124
+ this.r = s, this.g = r, this.b = t, this.a = n;
125
+ }
126
+ static from(s, r) {
127
+ if (s === "hex") {
128
+ let [t, n, a, b] = x(r);
129
+ return new e(t, n, a, b);
130
+ }
131
+ if (s === "rgb") {
132
+ if (Array.isArray(r)) {
133
+ let [o, y, c, u] = r;
134
+ return new e(o, y, c, u);
135
+ }
136
+ let { r: t, g: n, b: a, a: b } = r;
137
+ return new e(t, n, a, b);
138
+ }
139
+ if (s === "hsl") {
140
+ let t, n, a, b;
141
+ if (Array.isArray(r))
142
+ [t, n, a, b] = r;
143
+ else
144
+ ({ h: t, s: n, l: a, a: b } = r);
145
+ let [o, y, c] = R(t, n, a);
146
+ return new e(o, y, c, b);
147
+ }
148
+ if (s === "hsv") {
149
+ let t, n, a, b;
150
+ if (Array.isArray(r))
151
+ [t, n, a, b] = r;
152
+ else
153
+ ({ h: t, s: n, v: a, a: b } = r);
154
+ let [o, y, c] = H(t, n, a);
155
+ return new e(o, y, c, b);
156
+ }
157
+ if (s === "cmyk") {
158
+ let t, n, a, b, o;
159
+ if (Array.isArray(r))
160
+ [t, n, a, b, o] = r;
161
+ else
162
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
163
+ let [y, c, u] = v(t, n, a, b);
164
+ return new e(y, c, u, o);
165
+ }
166
+ if (s === "oklch") {
167
+ let t, n, a, b;
168
+ if (Array.isArray(r))
169
+ [t, n, a, b] = r;
170
+ else
171
+ ({ l: t, c: n, h: a, a: b } = r);
172
+ let [o, y, c] = C(t, n, a);
173
+ return new e(o, y, c, b);
174
+ }
175
+ if (s === "oklab") {
176
+ let t, n, a, b;
177
+ if (Array.isArray(r))
178
+ [t, n, a, b] = r;
179
+ else
180
+ ({ l: t, a: n, b: a, alpha: b } = r);
181
+ let [o, y, c] = M(t, n, a);
182
+ return new e(o, y, c, b);
183
+ }
184
+ throw Error("Invalid input");
185
+ }
186
+ to(s) {
187
+ switch (s) {
188
+ case "rgb":
189
+ return [this.r, this.g, this.b];
190
+ case "rgba":
191
+ return [this.r, this.g, this.b, this.a];
192
+ case "hex":
193
+ return A([this.r, this.g, this.b]);
194
+ case "hexa":
195
+ return A([this.r, this.g, this.b, this.a]);
196
+ case "hsl":
197
+ return k([this.r, this.g, this.b]);
198
+ case "hsla":
199
+ return [...k([this.r, this.g, this.b]), this.a];
200
+ case "hsv":
201
+ return f([this.r, this.g, this.b]);
202
+ case "hsva":
203
+ return [...f([this.r, this.g, this.b]), this.a];
204
+ case "cmyk":
205
+ return O([this.r, this.g, this.b]);
206
+ case "cmyka":
207
+ return [...O([this.r, this.g, this.b]), this.a];
208
+ case "oklch":
209
+ return d([this.r, this.g, this.b]);
210
+ case "oklcha":
211
+ return [...d([this.r, this.g, this.b]), this.a];
212
+ case "oklab":
213
+ return T([this.r, this.g, this.b]);
214
+ case "oklaba":
215
+ return [...T([this.r, this.g, this.b]), this.a];
216
+ default:
217
+ return [this.r, this.g, this.b];
218
+ }
219
+ }
220
+ getLuminance() {
221
+ let s = l(this.r), r = l(this.g), t = l(this.b);
222
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
223
+ }
224
+ contrastRatio(s) {
225
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
226
+ return (n + 0.05) / (a + 0.05);
227
+ }
228
+ bestContrastForeground() {
229
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
230
+ return t >= n ? s : r;
231
+ }
232
+ }
233
+
234
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
235
+ var r = 39;
236
+ var o = 49;
237
+ var f2 = "\x1B[";
238
+ 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") => {
239
+ let [a, l, s] = e.from("hex", i).to("rgb");
240
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
241
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
242
+ var b = new Set(["", "1", "2", "3", "true"]);
243
+ function h(i, n = globalThis.process?.env ?? {}) {
244
+ if (n.FORCE_COLOR !== undefined)
245
+ return b.has(n.FORCE_COLOR);
246
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
247
+ return false;
248
+ return i?.isTTY === true;
249
+ }
250
+ function d2(i, n, a) {
251
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
252
+ return n;
253
+ let l = "", s = "";
254
+ for (let g = 0, y = i.length;g < y; g++) {
255
+ let [c, p] = i[g];
256
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
257
+ }
258
+ return l + n + s;
259
+ }
260
+ function u(i, n = []) {
261
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
262
+ let g = C2[s];
263
+ if (Array.isArray(g))
264
+ return u(i, [...n, g]);
265
+ if (typeof g === "function")
266
+ return (...y) => u(i, [...n, g(...y)]);
267
+ throw Error(`Unknown style: ${String(s)}`);
268
+ } });
269
+ }
270
+ function le(i = {}) {
271
+ return u(i);
272
+ }
273
+ var t = le();
274
+
275
+ // ../kit/src/style.ts
276
+ function takesControlCodes(stream, env = process.env) {
277
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
278
+ }
279
+ function paint(stream, env = process.env) {
280
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
281
+ }
282
+ var STATUSES = {
283
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
284
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
285
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
286
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
287
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
288
+ };
289
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
290
+
291
+ // ../kit/src/format.ts
292
+ function upTo(text, separator) {
293
+ const end = text.indexOf(separator);
294
+ return end === -1 ? text : text.slice(0, end);
295
+ }
296
+ var ESCAPE = String.fromCharCode(27);
297
+ function printJson(value) {
298
+ console.log(JSON.stringify(value, undefined, 2));
299
+ }
300
+
301
+ // ../kit/src/help.ts
302
+ import process2 from "process";
303
+ var OPTIONAL = /\[[^\]]+\]/g;
304
+ var USAGE_PREFIX = /^usage:\s*/i;
305
+ var FULL_STOP = /\.$/;
306
+ function usageLine(usage, colors = paint(process2.stdout)) {
307
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
308
+ }
309
+ function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
310
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
311
+ `);
312
+ }
313
+ function replacesRows(replaces, colors = paint(process2.stdout)) {
314
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
315
+ }
316
+ function wantsHelpJson(env = process2.env) {
317
+ return env.KIT_HELP === "json";
318
+ }
319
+ function description(usage, { examples = [], replaces } = {}) {
320
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
321
+ `);
322
+ const first = lines[0];
323
+ const colon = first.indexOf(": ");
324
+ const prose = lines[lines.indexOf("") + 1] ?? "";
325
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
326
+ return {
327
+ synopsis: colon === -1 ? first : first.slice(0, colon),
328
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
329
+ ...replaces === undefined ? {} : { replaces },
330
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
331
+ };
332
+ }
333
+ function exampleRows(examples, colors = paint(process2.stdout)) {
334
+ if (examples.length === 0)
335
+ return [];
336
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
337
+ }
338
+ function optionRows(options, colors = paint(process2.stdout)) {
339
+ const rows = Object.entries(options).map(([name, option]) => {
340
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
341
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
342
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
343
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
344
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
345
+ });
346
+ const width = Math.max(0, ...rows.map((row) => row.width));
347
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
348
+ }
349
+
350
+ // ../kit/src/text.ts
351
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
352
+ function distance(a, b) {
353
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
354
+ for (const [i, left] of [...a].entries()) {
355
+ const current = [i + 1];
356
+ for (const [j, right] of [...b].entries())
357
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
358
+ previous = current;
359
+ }
360
+ return previous[b.length] ?? 0;
361
+ }
362
+ function closest(name, names) {
363
+ const started = names.find((known) => known.startsWith(name));
364
+ if (started !== undefined)
365
+ return started;
366
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
367
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
368
+ }
369
+
370
+ // ../kit/src/args.ts
371
+ var DASHES = /^-+/;
372
+ function jsonOption(holds) {
373
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
374
+ }
375
+
376
+ class Exit extends Error {
377
+ code;
378
+ hint;
379
+ constructor(message, code, hint) {
380
+ super(message);
381
+ this.code = code;
382
+ this.hint = hint;
383
+ }
384
+ }
385
+ function fail(message, code = 2, hint) {
386
+ throw new Exit(message, code, hint);
387
+ }
388
+
389
+ class UsageError extends Exit {
390
+ constructor(message, hint) {
391
+ super(message, 2, hint);
392
+ }
393
+ }
394
+ function badUsage(message) {
395
+ throw new UsageError(message);
396
+ }
397
+
398
+ class HelpShown extends Exit {
399
+ constructor() {
400
+ super("help shown", 0);
401
+ }
402
+ }
403
+
404
+ class Completing {
405
+ options;
406
+ positionals;
407
+ candidates;
408
+ constructor(options, positionals = [], candidates = {}) {
409
+ this.options = options;
410
+ this.positionals = positionals;
411
+ this.candidates = candidates;
412
+ }
413
+ }
414
+ var completion = { active: false };
415
+ var OUTPUT_OPTIONS = {
416
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
417
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
418
+ };
419
+ function applyOutput(color, plain, env = process3.env) {
420
+ const when = plain === true ? "never" : color ?? "auto";
421
+ if (when === "auto")
422
+ return;
423
+ if (when !== "always" && when !== "never")
424
+ badUsage(`--color takes auto, always or never, not ${when}`);
425
+ if (when === "always") {
426
+ env.FORCE_COLOR = "1";
427
+ delete env.NO_COLOR;
428
+ } else {
429
+ env.NO_COLOR = "1";
430
+ delete env.FORCE_COLOR;
431
+ }
432
+ }
433
+ function parse(args, usage, options, settings = {}) {
434
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
435
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
436
+ const listing = listed(all, settings.allowNegative === true);
437
+ if (completion.active)
438
+ throw new Completing(listing, settings.positionals, settings.candidates);
439
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
440
+ let parsed;
441
+ try {
442
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
443
+ } catch (error) {
444
+ const message = parseError(error);
445
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
446
+ }
447
+ const values = parsed.values;
448
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
449
+ if (values.help === true) {
450
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
451
+ throw new HelpShown;
452
+ }
453
+ checkChoices(parsed.values, all);
454
+ checkConflicts(parsed.values, all);
455
+ if (settings.positionals !== undefined)
456
+ checkPositionals(parsed.positionals, settings.positionals);
457
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
458
+ }
459
+ function splitRest(args, passes) {
460
+ const separator = passes ? args.indexOf("--") : -1;
461
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
462
+ }
463
+ function splitTrailing(args, options, count) {
464
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
465
+ let seen = 0;
466
+ if (count === 0)
467
+ return { own: args, rest: undefined };
468
+ for (let at = 0;at < args.length; at++) {
469
+ const word = args[at];
470
+ if (word === "--")
471
+ break;
472
+ if (word.startsWith("-")) {
473
+ if (takesValue(word))
474
+ at++;
475
+ continue;
476
+ }
477
+ seen++;
478
+ if (seen === count)
479
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
480
+ }
481
+ return { own: args, rest: undefined };
482
+ }
483
+ function listed(options, allowNegative) {
484
+ if (!allowNegative)
485
+ return options;
486
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
487
+ if (option.type !== "boolean" || option.negative === undefined)
488
+ return [[name, option]];
489
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
490
+ }));
491
+ }
492
+ function withBare(args, options) {
493
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
494
+ if (bare.size === 0)
495
+ return args;
496
+ const separator = args.indexOf("--");
497
+ const own = separator === -1 ? args : args.slice(0, separator);
498
+ return [...own.flatMap((arg, index) => {
499
+ const optional = bare.get(arg);
500
+ const next = own[index + 1];
501
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
502
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
503
+ }), ...separator === -1 ? [] : args.slice(separator)];
504
+ }
505
+ function checkConflicts(values, options) {
506
+ const given = (name) => values[name] !== undefined && values[name] !== false;
507
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
508
+ const other = given(name) ? conflicts.find(given) : undefined;
509
+ if (other !== undefined)
510
+ badUsage(`--${name} cannot be used with --${other}`);
511
+ }
512
+ }
513
+ function checkChoices(values, options) {
514
+ for (const [name, option] of Object.entries(options)) {
515
+ if (option.choices === undefined)
516
+ continue;
517
+ const given = values[name];
518
+ for (const value of Array.isArray(given) ? given : [given]) {
519
+ if (typeof value === "string")
520
+ oneOf(value, name, option.choices);
521
+ }
522
+ }
523
+ }
524
+ function oneOf(value, name, choices) {
525
+ if (!choices.includes(value))
526
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
527
+ return value;
528
+ }
529
+ function checkPositionals(given, names) {
530
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
531
+ const required = names.filter((name) => !name.startsWith("[")).length;
532
+ if (given.length < required)
533
+ badUsage(`missing ${names[given.length]}`);
534
+ if (!variadic && given.length > names.length)
535
+ badUsage(`unexpected argument ${given[names.length]}`);
536
+ }
537
+ function joinDashValues(args, options) {
538
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
539
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
540
+ const joined = [];
541
+ for (let i = 0;i < args.length; i++) {
542
+ const arg = args[i] ?? "";
543
+ if (arg === "--")
544
+ return [...joined, ...args.slice(i)];
545
+ const name = longOf.get(arg);
546
+ const next = args[i + 1];
547
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
548
+ joined.push(`--${name}=${next}`);
549
+ i++;
550
+ } else {
551
+ joined.push(arg);
552
+ }
553
+ }
554
+ return joined;
555
+ }
556
+ function parseError(error) {
557
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
558
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
559
+ }
560
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
561
+ function nearestOption(message, options, allowNegative) {
562
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
563
+ if (typed === undefined)
564
+ return;
565
+ const word = typed.replace(DASHES, "");
566
+ if (word.length < 2 && !typed.startsWith("--"))
567
+ return;
568
+ const known = Object.entries(options).flatMap(([name, option]) => [
569
+ ...option.short === undefined ? [] : [`-${option.short}`],
570
+ `--${name}`,
571
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
572
+ ]);
573
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
574
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
575
+ }
576
+ // ../kit/src/process.ts
577
+ import { constants } from "os";
578
+ import process4 from "process";
579
+ var KILL_GRACE_MS = 2000;
580
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
581
+ function exitCodeOf(code, signal) {
582
+ if (code !== null)
583
+ return code;
584
+ if (typeof signal === "number")
585
+ return 128 + signal;
586
+ return signal === null ? 129 : 128 + constants.signals[signal];
587
+ }
588
+ function holdSignals(cleanup) {
589
+ let received;
590
+ let child;
591
+ const held = {
592
+ get signal() {
593
+ return received;
594
+ },
595
+ forward: (to) => {
596
+ child = to;
597
+ },
598
+ release: () => {
599
+ for (const signal of SIGNALS)
600
+ process4.off(signal, onSignal);
601
+ }
602
+ };
603
+ function onSignal(signal) {
604
+ received = signal;
605
+ if (child !== undefined) {
606
+ child.kill(signal);
607
+ return;
608
+ }
609
+ if (cleanup === undefined)
610
+ return;
611
+ held.release();
612
+ cleanup(signal);
613
+ process4.kill(process4.pid, signal);
614
+ }
615
+ for (const signal of SIGNALS)
616
+ process4.on(signal, onSignal);
617
+ return held;
618
+ }
619
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
620
+ const chunks = [];
621
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
622
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
623
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
624
+ const timers = [];
625
+ const killGroup = (killing) => {
626
+ if (state.done)
627
+ return;
628
+ try {
629
+ if (grouped)
630
+ process4.kill(-proc.pid, killing);
631
+ else
632
+ proc.kill(killing);
633
+ } catch {}
634
+ };
635
+ const stop = () => {
636
+ killGroup("SIGTERM");
637
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
638
+ };
639
+ const onAbort = () => stop();
640
+ if (timeoutMs !== undefined) {
641
+ timers.push(setTimeout(() => {
642
+ state.timedOut = true;
643
+ stop();
644
+ }, timeoutMs));
645
+ }
646
+ if (signal?.aborted === true)
647
+ onAbort();
648
+ else
649
+ signal?.addEventListener("abort", onAbort, { once: true });
650
+ onStart?.({ kill: (killing) => killGroup(killing) });
651
+ const drain = async (stream, name) => {
652
+ for await (const data of stream) {
653
+ if (state.failure !== undefined)
654
+ continue;
655
+ try {
656
+ onChunk?.({ stream: name, data });
657
+ } catch (error) {
658
+ state.failure = error;
659
+ stop();
660
+ continue;
661
+ }
662
+ if (state.kept + data.length > maxBytes) {
663
+ state.truncated = true;
664
+ continue;
665
+ }
666
+ state.kept += data.length;
667
+ chunks.push({ stream: name, data });
668
+ }
669
+ };
670
+ try {
671
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
672
+ await proc.exited;
673
+ } finally {
674
+ state.done = true;
675
+ for (const timer of timers)
676
+ clearTimeout(timer);
677
+ signal?.removeEventListener("abort", onAbort);
678
+ }
679
+ if (state.failure !== undefined)
680
+ throw state.failure;
681
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
682
+ let output;
683
+ let text;
684
+ return {
685
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
686
+ chunks,
687
+ timedOut: state.timedOut,
688
+ truncated: state.truncated,
689
+ get output() {
690
+ return output ??= joined();
691
+ },
692
+ get text() {
693
+ return text ??= (output ??= joined()).toString();
694
+ }
695
+ };
696
+ }
697
+
698
+ // ../kit/src/progress.ts
699
+ var ESC = String.fromCharCode(27);
700
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
701
+ var RESET_STYLE = `${ESC}[0m`;
702
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
703
+ // ../kit/src/cli.ts
704
+ import process6 from "process";
705
+
706
+ // ../kit/src/usage.ts
707
+ import { appendFileSync, mkdirSync } from "fs";
708
+ import { homedir } from "os";
709
+ import { dirname, isAbsolute, join } from "path";
710
+ import process5 from "process";
711
+
712
+ // ../kit/src/logs.ts
713
+ var DAY_MS = 24 * 60 * 60 * 1000;
714
+ var CLI_FOLDER = "kaynooo-cli";
715
+
716
+ // ../kit/src/usage.ts
717
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
718
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
719
+ var LONGEST_NAME = 40;
720
+ var usageError;
721
+ function noteUsageError(message) {
722
+ usageError = message;
723
+ }
724
+ function stateHome(env = process5.env) {
725
+ const dir = env.XDG_STATE_HOME;
726
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
727
+ }
728
+ function usagePath(env = process5.env) {
729
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
730
+ }
731
+ function usageRecorded(env = process5.env) {
732
+ const off = env.KAYNOOO_CLI_NO_USAGE;
733
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
734
+ }
735
+ function flagNames(argv) {
736
+ const end = argv.indexOf("--");
737
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
738
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
739
+ }
740
+ function usageEntry(bin, command, argv, code, now = new Date) {
741
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
742
+ usageError = undefined;
743
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
744
+ }
745
+ function recordUsage(entry, env = process5.env) {
746
+ if (!usageRecorded(env))
747
+ return;
748
+ try {
749
+ const path = usagePath(env);
750
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
751
+ appendFileSync(path, `${JSON.stringify(entry)}
752
+ `, { mode: 384 });
753
+ } catch {}
754
+ }
755
+
756
+ // ../kit/src/cli.ts
757
+ var LEVEL_OPTIONS = {
758
+ ...OUTPUT_OPTIONS,
759
+ help: { type: "boolean", short: "h", description: "show this help" }
760
+ };
761
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
762
+ function printError(prefix, message, hint, cause) {
763
+ const colors = paint(process6.stderr);
764
+ const styled = takesControlCodes(process6.stderr);
765
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
766
+ const under = (label, text, tint) => text === undefined ? "" : `
767
+ ${styled ? tint(label) : `${label}:`} ${text}`;
768
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
769
+ }
770
+ function printJsonError(message, hint, cause) {
771
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
772
+ }
773
+ function wantsJson(argv) {
774
+ const end = argv.indexOf("--");
775
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
776
+ }
777
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
778
+ if (error instanceof HelpShown)
779
+ return 0;
780
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
781
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
782
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
783
+ if (error instanceof UsageError)
784
+ noteUsageError(error.message);
785
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
786
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
787
+ return error instanceof Exit ? error.code : 1;
788
+ }
789
+ var COMPLETE = "__complete";
790
+ var FILES = "__files__";
791
+ async function completingOf(run) {
792
+ completion.active = true;
793
+ try {
794
+ await run([]);
795
+ } catch (error) {
796
+ if (error instanceof Completing)
797
+ return error;
798
+ } finally {
799
+ completion.active = false;
800
+ }
801
+ return new Completing({});
802
+ }
803
+ function candidateLine(candidate) {
804
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
805
+ }
806
+ function positionalBeingTyped(before, { options, positionals }) {
807
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
808
+ let index = 0;
809
+ let at = 0;
810
+ while (at < before.length) {
811
+ const word = before[at];
812
+ if (word === "--") {
813
+ index += before.length - at - 1;
814
+ break;
815
+ }
816
+ if (!word.startsWith("-"))
817
+ index++;
818
+ else if (takesValue(word))
819
+ at++;
820
+ at++;
821
+ }
822
+ const last = positionals.at(-1);
823
+ if (index < positionals.length)
824
+ return positionals[index];
825
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
826
+ }
827
+ async function leafCandidates(run, words) {
828
+ const completing = await completingOf(run);
829
+ if ((words.at(-1) ?? "").startsWith("-"))
830
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
831
+ const flag = words.at(-2);
832
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
833
+ if (option?.type === "string") {
834
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
835
+ return values === undefined ? [FILES] : values.map(candidateLine);
836
+ }
837
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
838
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
839
+ return values === undefined ? [FILES] : values.map(candidateLine);
840
+ }
841
+ async function printCandidates(found) {
842
+ for (const line of await found)
843
+ console.log(line);
844
+ return 0;
845
+ }
846
+ async function runMain({ name, version, run, redact, usage }, argv = process6.argv.slice(2)) {
847
+ if (argv[0] === COMPLETE)
848
+ return printCandidates(leafCandidates(run, argv.slice(1)));
849
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
850
+ console.log(version);
851
+ return 0;
852
+ }
853
+ let code;
854
+ try {
855
+ code = await run(argv);
856
+ } catch (error) {
857
+ code = reportThrown(name, error, redact, wantsJson(argv));
858
+ }
859
+ if (usage !== false)
860
+ recordUsage(usageEntry(name, undefined, argv, code));
861
+ return code;
862
+ }
863
+ // ../kit/src/secrets.ts
864
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
865
+ // ../kit/src/sessions.ts
866
+ var {Glob } = globalThis.Bun;
867
+ var SESSION_FILES = new Glob("*.json");
868
+ var ACCOUNT_DIRS = new Glob("*/sessions");
869
+ // package.json
870
+ var version = "0.4.1";
871
+
872
+ // src/worktree.ts
873
+ import { cpSync, existsSync, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync, rmSync, symlinkSync, unlinkSync } from "fs";
874
+ import { tmpdir } from "os";
875
+ import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join2, relative, resolve, sep } from "path";
876
+ import process8 from "process";
877
+ var WHITESPACE = /\s/;
878
+ var ENV_FILE = /^\.env(?:\..+)?$/;
879
+ var DEPENDENCIES = new Set(["node_modules", "vendor", ".venv"]);
880
+ var TRAILING_SLASH = /\/$/;
881
+ var PARENT = `..${sep}`;
882
+ var BASE_DIR = /^base-\w{6}$/;
883
+ var CONTAINER = /(?:^|[\s;&|(])(?:docker\s+compose|docker-compose)\s+(?:-\S+(?:\s+[^-\s]\S*)?\s+)*(?:exec|run)\b|(?:^|[\s;&|(])docker\s+exec\b/;
884
+ function stdoutOf(ran) {
885
+ return Buffer.concat(ran.chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString().trim();
886
+ }
887
+ async function git2(args, cwd) {
888
+ return runCommand(["git", ...args], { cwd });
889
+ }
890
+ function runsInContainer(command) {
891
+ return CONTAINER.test(command.join(" "));
892
+ }
893
+ async function checkout(cwd) {
894
+ const ran = await git2(["rev-parse", "--show-toplevel", "--show-prefix"], cwd);
895
+ if (ran.code !== 0)
896
+ fail("not inside a git repository");
897
+ const [root = "", prefix = ""] = stdoutOf(ran).split(`
898
+ `);
899
+ return { root, prefix };
900
+ }
901
+ async function resolveRef(root, ref) {
902
+ const ran = await git2(["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`], root);
903
+ if (ran.code !== 0)
904
+ fail(`no commit ${ref} in this repository`);
905
+ return stdoutOf(ran);
906
+ }
907
+ function keptPaths(root, cwd, paths) {
908
+ const realRoot = realpathSync(root);
909
+ return paths.map((path) => {
910
+ const absolute = resolve(cwd, path);
911
+ const inRepo = relative(realRoot, join2(realpathSync(dirname2(absolute)), basename(absolute)));
912
+ if (inRepo === "" || inRepo === ".." || inRepo.startsWith(PARENT) || isAbsolute2(inRepo))
913
+ fail(`--keep ${path} is outside the repository`);
914
+ if (!existsSync(absolute))
915
+ fail(`--keep ${path}: no such file`);
916
+ return inRepo;
917
+ });
918
+ }
919
+ function checkNoSymlink(dir, path) {
920
+ let current = dir;
921
+ for (const part of dirname2(path).split(sep)) {
922
+ current = join2(current, part);
923
+ if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink() === true)
924
+ fail(`--keep ${path} goes through the symlink ${relative(dir, current)} of the ref, which would write outside the worktree`);
925
+ }
926
+ }
927
+ async function linkedEntries(root) {
928
+ const ran = await git2(["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"], root);
929
+ if (ran.code !== 0)
930
+ return [];
931
+ return stdoutOf(ran).split("\x00").filter((entry) => {
932
+ const folder = entry.endsWith("/");
933
+ const name = basename(entry);
934
+ return folder ? DEPENDENCIES.has(name) : ENV_FILE.test(name);
935
+ }).map((entry) => entry.replace(TRAILING_SLASH, ""));
936
+ }
937
+ async function addWorktree(root, sha) {
938
+ const dir = join2(mkdtempSync(join2(tmpdir(), "base-")), basename(root));
939
+ const ran = await git2(["worktree", "add", "--detach", dir, sha], root);
940
+ if (ran.code !== 0) {
941
+ rmSync(dirname2(dir), { recursive: true, force: true });
942
+ fail(`git worktree add failed:
943
+ ${ran.text.trim()}`);
944
+ }
945
+ return dir;
946
+ }
947
+ function copyKept(root, dir, paths) {
948
+ for (const path of paths) {
949
+ checkNoSymlink(dir, path);
950
+ const target = join2(dir, path);
951
+ rmSync(target, { recursive: true, force: true });
952
+ mkdirSync2(dirname2(target), { recursive: true });
953
+ cpSync(join2(root, path), target, { recursive: true });
954
+ }
955
+ }
956
+ function linkEntries(root, dir, entries) {
957
+ const links = [];
958
+ for (const entry of entries) {
959
+ const link = join2(dir, entry);
960
+ if (existsSync(link))
961
+ continue;
962
+ mkdirSync2(dirname2(link), { recursive: true });
963
+ if (basename(entry) === "node_modules" && hasWorkspaceLinks(root, entry)) {
964
+ links.push(...linkModules(root, dir, entry));
965
+ continue;
966
+ }
967
+ symlinkSync(join2(root, entry), link);
968
+ links.push(link);
969
+ }
970
+ return links;
971
+ }
972
+ function moduleLinks(root, folder) {
973
+ const found = [];
974
+ for (const entry of readdirSync(join2(root, folder), { withFileTypes: true })) {
975
+ if (entry.isSymbolicLink())
976
+ found.push({ path: join2(folder, entry.name), name: entry.name });
977
+ else if (entry.isDirectory() && entry.name.startsWith("@"))
978
+ found.push(...moduleLinks(root, join2(folder, entry.name)));
979
+ }
980
+ return found;
981
+ }
982
+ function workspaceTarget(root, path) {
983
+ try {
984
+ const inRepo = relative(realpathSync(root), realpathSync(join2(root, path)));
985
+ return inRepo === "" || inRepo.startsWith(PARENT) || inRepo.split(sep).includes("node_modules") ? undefined : inRepo;
986
+ } catch {
987
+ return;
988
+ }
989
+ }
990
+ function hasWorkspaceLinks(root, folder) {
991
+ return moduleLinks(root, folder).some(({ path }) => workspaceTarget(root, path) !== undefined);
992
+ }
993
+ function linkModules(root, dir, folder) {
994
+ const links = [];
995
+ mkdirSync2(join2(dir, folder), { recursive: true });
996
+ for (const entry of readdirSync(join2(root, folder), { withFileTypes: true })) {
997
+ const path = join2(folder, entry.name);
998
+ const link = join2(dir, path);
999
+ if (entry.isDirectory() && entry.name.startsWith("@")) {
1000
+ links.push(...linkModules(root, dir, path));
1001
+ continue;
1002
+ }
1003
+ const workspace = entry.isSymbolicLink() ? workspaceTarget(root, path) : undefined;
1004
+ symlinkSync(workspace === undefined ? join2(root, path) : join2(dir, workspace), link);
1005
+ links.push(link);
1006
+ }
1007
+ return links;
1008
+ }
1009
+ var STALE_AFTER = 24 * 60 * 60 * 1000;
1010
+ async function sweepStale(root) {
1011
+ for (const name of readdirSync(tmpdir())) {
1012
+ if (!BASE_DIR.test(name))
1013
+ continue;
1014
+ const path = join2(tmpdir(), name);
1015
+ const stat = lstatSync(path, { throwIfNoEntry: false });
1016
+ if (stat?.isDirectory() === true && stat.uid === process8.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1017
+ rmSync(path, { recursive: true, force: true });
1018
+ }
1019
+ await git2(["worktree", "prune"], root);
1020
+ }
1021
+ async function removeWorktree(root, dir, links) {
1022
+ for (const link of links) {
1023
+ if (lstatSync(link, { throwIfNoEntry: false })?.isSymbolicLink() === true)
1024
+ unlinkSync(link);
1025
+ }
1026
+ await git2(["worktree", "remove", "--force", dir], root);
1027
+ rmSync(dirname2(dir), { recursive: true, force: true });
1028
+ await git2(["worktree", "prune"], root);
1029
+ }
1030
+ function shellCommand(given) {
1031
+ const [only] = given;
1032
+ return given.length === 1 && only !== undefined && WHITESPACE.test(only) ? ["sh", "-c", only] : given;
1033
+ }
1034
+ async function runIn(dir, command, signals, capture = false) {
1035
+ if (signals.signal !== undefined)
1036
+ return { code: exitCodeOf(null, signals.signal), output: "", started: true };
1037
+ let child;
1038
+ try {
1039
+ child = Bun.spawn(command, { cwd: dir, stdin: "inherit", stdout: capture ? "pipe" : "inherit", stderr: capture ? "pipe" : "inherit" });
1040
+ } catch (error) {
1041
+ return { code: 127, output: `cannot run ${command[0]}: ${error instanceof Error ? error.message : String(error)}`, started: false };
1042
+ }
1043
+ signals.forward(child);
1044
+ const chunks = [];
1045
+ if (capture)
1046
+ await Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]);
1047
+ await child.exited;
1048
+ return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true };
1049
+ }
1050
+ async function collect(stream, chunks) {
1051
+ for await (const chunk of stream)
1052
+ chunks.push(chunk);
1053
+ }
1054
+ var FOLD_OVER = 120;
1055
+ var FOLD_HEAD = 20;
1056
+ var FOLD_TAIL = 80;
1057
+ function folded(output) {
1058
+ const lines = output.trimEnd().split(`
1059
+ `);
1060
+ if (lines.length <= FOLD_OVER)
1061
+ return lines.join(`
1062
+ `);
1063
+ return [...lines.slice(0, FOLD_HEAD), `... ${lines.length - FOLD_HEAD - FOLD_TAIL} lines omitted, --json has them all ...`, ...lines.slice(-FOLD_TAIL)].join(`
1064
+ `);
1065
+ }
1066
+ async function inWorktree(options, body) {
1067
+ const { root, prefix, sha, ref, kept, link } = options;
1068
+ let links = [];
1069
+ const signals = options.signals ?? holdSignals();
1070
+ await sweepStale(root);
1071
+ const dir = await addWorktree(root, sha);
1072
+ try {
1073
+ copyKept(root, dir, kept);
1074
+ links = link ? linkEntries(root, dir, await linkedEntries(root)) : [];
1075
+ const runDir = join2(dir, prefix);
1076
+ if (!existsSync(runDir))
1077
+ fail(`${prefix} does not exist at ${ref}`);
1078
+ return await body(runDir, signals);
1079
+ } finally {
1080
+ await removeWorktree(root, dir, links);
1081
+ if (options.signals === undefined)
1082
+ signals.release();
1083
+ }
1084
+ }
1085
+
1086
+ // src/proof.ts
1087
+ var USAGE = `proof [--ref <rev>] [--keep <path>...] [--no-link] [--json] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, then in the working tree, to show that a test fails before a change and passes after it
1088
+
1089
+ Exits 0 when the command fails before and passes now, 1 when it passes before too, fails now too, or passes before and fails now, 2 on a usage error, an unknown ref, a command that cannot start or ends with exit 126, 127 or a signal, or 128 plus the signal when interrupted.`;
1090
+ var OPTIONS = {
1091
+ ref: { type: "string", short: "r", description: "the commit to run before at (default HEAD)" },
1092
+ keep: { type: "string", short: "k", multiple: true, description: "a working-tree file or folder copied over to the ref, such as the new test, repeatable" },
1093
+ "no-link": { type: "boolean", description: "do not link the ignored env files, node_modules, vendor and .venv of the checkout" },
1094
+ json: jsonOption("{outcome, proved, ref, sha, before: {code, output}, now: {code, output}}")
1095
+ };
1096
+ function abnormal(code) {
1097
+ return code === 126 || code === 127 || code > 128 && code < 160;
1098
+ }
1099
+ function outcomeOf(before, now) {
1100
+ if (before !== 0 && now === 0)
1101
+ return "proved";
1102
+ if (before === 0 && now === 0)
1103
+ return "passes-before";
1104
+ return before !== 0 ? "fails-both" : "regressed";
1105
+ }
1106
+ function describe(outcome, at) {
1107
+ switch (outcome) {
1108
+ case "proved":
1109
+ return { message: `fails at ${at}, passes now`, side: "before" };
1110
+ case "passes-before":
1111
+ return { message: `passes at ${at} too: it does not fail without the change`, side: "before" };
1112
+ case "fails-both":
1113
+ return { message: `fails at ${at} and fails now too`, side: "now" };
1114
+ case "regressed":
1115
+ return { message: `passes at ${at}, fails now`, side: "now" };
1116
+ }
1117
+ }
1118
+ async function main(argv) {
1119
+ const bare = argv[0] !== undefined && !argv[0].startsWith("-");
1120
+ const parsed = parse(bare ? [] : argv, USAGE, OPTIONS, { rest: true, replaces: "running a test, stashing the change and running it again", examples: [["proof --keep tests/fix.test.ts -- bun test tests/fix.test.ts", "the new test fails at HEAD and passes now"], ["proof --ref v1.2.0 --keep tests/fix.test.ts -- bun test tests/fix.test.ts", "the same against a release"]] });
1121
+ const given = bare ? argv : parsed.rest ?? [];
1122
+ if (given.length === 0 || parsed.positionals.length > 0)
1123
+ fail(`give the command after --
1124
+
1125
+ ${USAGE}`);
1126
+ if (runsInContainer(given))
1127
+ fail("a container of the compose project mounts the main checkout, not the temporary worktree, so the command would not run at the ref: run the tool on the host, or check the ref out by hand");
1128
+ const command = shellCommand(given);
1129
+ const cwd = process9.cwd();
1130
+ const { root, prefix } = await checkout(cwd);
1131
+ const ref = parsed.values.ref ?? "HEAD";
1132
+ const sha = await resolveRef(root, ref);
1133
+ const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
1134
+ const signals = holdSignals();
1135
+ let before;
1136
+ let now;
1137
+ try {
1138
+ before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true));
1139
+ if (signals.signal === undefined)
1140
+ now = await runIn(cwd, command, signals, true);
1141
+ } finally {
1142
+ signals.release();
1143
+ }
1144
+ if (signals.signal !== undefined || now === undefined)
1145
+ return exitCodeOf(null, signals.signal ?? null);
1146
+ for (const [run, where] of [[before, `at ${sha.slice(0, 7)}`], [now, "now"]]) {
1147
+ if (!run.started)
1148
+ fail(run.output);
1149
+ if (abnormal(run.code))
1150
+ fail(`the command did not run properly ${where}: exit ${run.code}, a missing command or a kill, not a test result${run.output.trim() === "" ? "" : `
1151
+
1152
+ ${folded(run.output)}`}`);
1153
+ }
1154
+ const outcome = outcomeOf(before.code, now.code);
1155
+ const { message, side } = describe(outcome, sha.slice(0, 7));
1156
+ const proved = outcome === "proved";
1157
+ if (parsed.values.json === true) {
1158
+ printJson({ outcome, proved, ref, sha, before: { code: before.code, output: before.output }, now: { code: now.code, output: now.output } });
1159
+ return proved ? 0 : 1;
1160
+ }
1161
+ console.log(message);
1162
+ const shown = side === "before" ? before : now;
1163
+ if (shown.code !== 0 && shown.output.trim() !== "")
1164
+ console.log(`
1165
+ ${folded(shown.output)}`);
1166
+ return proved ? 0 : 1;
1167
+ }
1168
+ process9.exitCode = await runMain({ name: "proof", version, run: main });