@kaynooo/cli-check 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/j-cli.js ADDED
@@ -0,0 +1,1779 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/j-cli.ts
5
+ import process15 from "process";
6
+
7
+ // ../kit/src/args.ts
8
+ import process5 from "process";
9
+ import { parseArgs } from "util";
10
+
11
+ // ../kit/src/format.ts
12
+ import process2 from "process";
13
+
14
+ // ../kit/src/style.ts
15
+ import process from "process";
16
+
17
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
+ function x(s) {
19
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
20
+ if (!/^[a-f0-9]+$/.test(r))
21
+ return [0, 0, 0];
22
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
23
+ if (t === 3 || t === 4) {
24
+ 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;
25
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
26
+ }
27
+ if (t !== 6 && t !== 8)
28
+ throw Error(`Invalid hex color length: ${t}`);
29
+ 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;
30
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
31
+ throw Error(`Invalid hex color value: ${s}`);
32
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
33
+ }
34
+ function A(s) {
35
+ let [r, t, n, a] = s;
36
+ if (a)
37
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
38
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
39
+ }
40
+ function R(s, r, t) {
41
+ s = (s % 360 + 360) % 360, t /= 100;
42
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
43
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
44
+ return Math.round(255 * y);
45
+ };
46
+ return [a(0), a(8), a(4)];
47
+ }
48
+ function k(s) {
49
+ let [r, t, n] = s;
50
+ r /= 255, t /= 255, n /= 255;
51
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
52
+ if (a !== b) {
53
+ let u = a - b;
54
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
55
+ o = (t - n) / u + (t < n ? 6 : 0);
56
+ else if (a === t)
57
+ o = (n - r) / u + 2;
58
+ else
59
+ o = (r - t) / u + 4;
60
+ o /= 6;
61
+ }
62
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
63
+ }
64
+ function H(s, r, t) {
65
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
66
+ let n = (a) => {
67
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
68
+ return Math.round(255 * o);
69
+ };
70
+ return [n(5), n(3), n(1)];
71
+ }
72
+ function f(s) {
73
+ let [r, t, n] = s;
74
+ r /= 255, t /= 255, n /= 255;
75
+ 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;
76
+ if (o !== 0) {
77
+ if (a === r)
78
+ y = (t - n) / o + (t < n ? 6 : 0);
79
+ else if (a === t)
80
+ y = (n - r) / o + 2;
81
+ else
82
+ y = (r - t) / o + 4;
83
+ y /= 6;
84
+ }
85
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
86
+ }
87
+ function O(s) {
88
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
89
+ if (a === 1)
90
+ return [0, 0, 0, 100];
91
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
92
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
93
+ }
94
+ function v(s, r, t, n) {
95
+ 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))];
96
+ }
97
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
98
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
99
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
100
+ function T(s) {
101
+ 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);
102
+ 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)];
103
+ }
104
+ function M(s, r, t) {
105
+ 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)));
106
+ return [u(o), u(y), u(c)];
107
+ }
108
+ function d(s) {
109
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
110
+ return [i(r, 4), i(a, 4), i(b, 2)];
111
+ }
112
+ function C(s, r, t) {
113
+ let n = t * Math.PI / 180;
114
+ return M(s, r * Math.cos(n), r * Math.sin(n));
115
+ }
116
+ function l(s) {
117
+ let r = s / 255;
118
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
119
+ }
120
+
121
+ class e {
122
+ r;
123
+ g;
124
+ b;
125
+ a;
126
+ constructor(s, r, t, n = 1) {
127
+ this.r = s, this.g = r, this.b = t, this.a = n;
128
+ }
129
+ static from(s, r) {
130
+ if (s === "hex") {
131
+ let [t, n, a, b] = x(r);
132
+ return new e(t, n, a, b);
133
+ }
134
+ if (s === "rgb") {
135
+ if (Array.isArray(r)) {
136
+ let [o, y, c, u] = r;
137
+ return new e(o, y, c, u);
138
+ }
139
+ let { r: t, g: n, b: a, a: b } = r;
140
+ return new e(t, n, a, b);
141
+ }
142
+ if (s === "hsl") {
143
+ let t, n, a, b;
144
+ if (Array.isArray(r))
145
+ [t, n, a, b] = r;
146
+ else
147
+ ({ h: t, s: n, l: a, a: b } = r);
148
+ let [o, y, c] = R(t, n, a);
149
+ return new e(o, y, c, b);
150
+ }
151
+ if (s === "hsv") {
152
+ let t, n, a, b;
153
+ if (Array.isArray(r))
154
+ [t, n, a, b] = r;
155
+ else
156
+ ({ h: t, s: n, v: a, a: b } = r);
157
+ let [o, y, c] = H(t, n, a);
158
+ return new e(o, y, c, b);
159
+ }
160
+ if (s === "cmyk") {
161
+ let t, n, a, b, o;
162
+ if (Array.isArray(r))
163
+ [t, n, a, b, o] = r;
164
+ else
165
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
166
+ let [y, c, u] = v(t, n, a, b);
167
+ return new e(y, c, u, o);
168
+ }
169
+ if (s === "oklch") {
170
+ let t, n, a, b;
171
+ if (Array.isArray(r))
172
+ [t, n, a, b] = r;
173
+ else
174
+ ({ l: t, c: n, h: a, a: b } = r);
175
+ let [o, y, c] = C(t, n, a);
176
+ return new e(o, y, c, b);
177
+ }
178
+ if (s === "oklab") {
179
+ let t, n, a, b;
180
+ if (Array.isArray(r))
181
+ [t, n, a, b] = r;
182
+ else
183
+ ({ l: t, a: n, b: a, alpha: b } = r);
184
+ let [o, y, c] = M(t, n, a);
185
+ return new e(o, y, c, b);
186
+ }
187
+ throw Error("Invalid input");
188
+ }
189
+ to(s) {
190
+ switch (s) {
191
+ case "rgb":
192
+ return [this.r, this.g, this.b];
193
+ case "rgba":
194
+ return [this.r, this.g, this.b, this.a];
195
+ case "hex":
196
+ return A([this.r, this.g, this.b]);
197
+ case "hexa":
198
+ return A([this.r, this.g, this.b, this.a]);
199
+ case "hsl":
200
+ return k([this.r, this.g, this.b]);
201
+ case "hsla":
202
+ return [...k([this.r, this.g, this.b]), this.a];
203
+ case "hsv":
204
+ return f([this.r, this.g, this.b]);
205
+ case "hsva":
206
+ return [...f([this.r, this.g, this.b]), this.a];
207
+ case "cmyk":
208
+ return O([this.r, this.g, this.b]);
209
+ case "cmyka":
210
+ return [...O([this.r, this.g, this.b]), this.a];
211
+ case "oklch":
212
+ return d([this.r, this.g, this.b]);
213
+ case "oklcha":
214
+ return [...d([this.r, this.g, this.b]), this.a];
215
+ case "oklab":
216
+ return T([this.r, this.g, this.b]);
217
+ case "oklaba":
218
+ return [...T([this.r, this.g, this.b]), this.a];
219
+ default:
220
+ return [this.r, this.g, this.b];
221
+ }
222
+ }
223
+ getLuminance() {
224
+ let s = l(this.r), r = l(this.g), t = l(this.b);
225
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
226
+ }
227
+ contrastRatio(s) {
228
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
229
+ return (n + 0.05) / (a + 0.05);
230
+ }
231
+ bestContrastForeground() {
232
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
233
+ return t >= n ? s : r;
234
+ }
235
+ }
236
+
237
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
238
+ var r = 39;
239
+ var o = 49;
240
+ var f2 = "\x1B[";
241
+ 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") => {
242
+ let [a, l, s] = e.from("hex", i).to("rgb");
243
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
244
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
245
+ var b = new Set(["", "1", "2", "3", "true"]);
246
+ function h(i, n = globalThis.process?.env ?? {}) {
247
+ if (n.FORCE_COLOR !== undefined)
248
+ return b.has(n.FORCE_COLOR);
249
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
250
+ return false;
251
+ return i?.isTTY === true;
252
+ }
253
+ function d2(i, n, a) {
254
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
255
+ return n;
256
+ let l = "", s = "";
257
+ for (let g = 0, y = i.length;g < y; g++) {
258
+ let [c, p] = i[g];
259
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
260
+ }
261
+ return l + n + s;
262
+ }
263
+ function u(i, n = []) {
264
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
265
+ let g = C2[s];
266
+ if (Array.isArray(g))
267
+ return u(i, [...n, g]);
268
+ if (typeof g === "function")
269
+ return (...y) => u(i, [...n, g(...y)]);
270
+ throw Error(`Unknown style: ${String(s)}`);
271
+ } });
272
+ }
273
+ function le(i = {}) {
274
+ return u(i);
275
+ }
276
+ var t = le();
277
+
278
+ // ../kit/src/style.ts
279
+ var MARKS = {
280
+ ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
281
+ warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
282
+ problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
283
+ note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
284
+ };
285
+ function takesControlCodes(stream, env = process.env) {
286
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
287
+ }
288
+ function paint(stream, env = process.env) {
289
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
290
+ }
291
+ function marked(mark, text, stream, detail, env = process.env) {
292
+ const colors = paint(stream, env);
293
+ const { symbol, word, paint: tint } = MARKS[mark];
294
+ const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
295
+ return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
296
+ }
297
+ function warn(text, detail) {
298
+ console.error(marked("warn", text, process.stderr, detail));
299
+ }
300
+ var STATUSES = {
301
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
302
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
303
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
304
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
305
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
306
+ };
307
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
308
+
309
+ // ../kit/src/format.ts
310
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
311
+ function formatSeconds(total) {
312
+ let rest = Math.max(0, Math.round(total));
313
+ const amounts = UNITS.map(([unit, size]) => {
314
+ const amount = Math.floor(rest / size);
315
+ rest -= amount * size;
316
+ return `${amount}${unit}`;
317
+ });
318
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
319
+ if (first === -1)
320
+ return "0s";
321
+ const next = amounts[first + 1];
322
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
323
+ }
324
+ function formatDuration(ms) {
325
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
326
+ }
327
+ function upTo(text, separator) {
328
+ const end = text.indexOf(separator);
329
+ return end === -1 ? text : text.slice(0, end);
330
+ }
331
+ function truncate(text, width) {
332
+ return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
333
+ }
334
+ var LINE_BREAKS = /\s*\n\s*/g;
335
+ var ESCAPE = String.fromCharCode(27);
336
+ function textWidth(text) {
337
+ return Bun.stringWidth(text);
338
+ }
339
+ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
340
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
341
+ const widths = [];
342
+ for (const row of cells) {
343
+ for (const [index, cell] of row.entries())
344
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
345
+ }
346
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
347
+ const colors = paint(process2.stdout);
348
+ const lines = shown.map((row) => row.map((cell, index) => {
349
+ const width = widths[index] ?? 0;
350
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
351
+ if (align[index] === "right")
352
+ return `${gap}${cell}`;
353
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
354
+ }).join(" ").trimEnd());
355
+ return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
356
+ `);
357
+ }
358
+ function narrow(rows, widths, limit) {
359
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
360
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
361
+ const floor = 8;
362
+ while (used() > limit) {
363
+ let widest = -1;
364
+ for (const [index, width] of widths.entries()) {
365
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
366
+ widest = index;
367
+ }
368
+ if (widest === -1)
369
+ break;
370
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
371
+ }
372
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
373
+ }
374
+ function printJson(value) {
375
+ console.log(JSON.stringify(value, undefined, 2));
376
+ }
377
+
378
+ // ../kit/src/help.ts
379
+ import process3 from "process";
380
+ var OPTIONAL = /\[[^\]]+\]/g;
381
+ var USAGE_PREFIX = /^usage:\s*/i;
382
+ var FULL_STOP = /\.$/;
383
+ function usageLine(usage, colors = paint(process3.stdout)) {
384
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
385
+ }
386
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
387
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
388
+ `);
389
+ }
390
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
391
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
392
+ }
393
+ function wantsHelpJson(env = process3.env) {
394
+ return env.KIT_HELP === "json";
395
+ }
396
+ function description(usage, { examples = [], replaces } = {}) {
397
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
398
+ `);
399
+ const first = lines[0];
400
+ const colon = first.indexOf(": ");
401
+ const prose = lines[lines.indexOf("") + 1] ?? "";
402
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
403
+ return {
404
+ synopsis: colon === -1 ? first : first.slice(0, colon),
405
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
406
+ ...replaces === undefined ? {} : { replaces },
407
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
408
+ };
409
+ }
410
+ function exampleRows(examples, colors = paint(process3.stdout)) {
411
+ if (examples.length === 0)
412
+ return [];
413
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
414
+ }
415
+ function optionRows(options, colors = paint(process3.stdout)) {
416
+ const rows = Object.entries(options).map(([name, option]) => {
417
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
418
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
419
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
420
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
421
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
422
+ });
423
+ const width = Math.max(0, ...rows.map((row) => row.width));
424
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
425
+ }
426
+
427
+ // ../kit/src/text.ts
428
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
429
+ function stripAnsi(text) {
430
+ return text.replace(ANSI, "");
431
+ }
432
+ function distance(a, b) {
433
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
434
+ for (const [i, left] of [...a].entries()) {
435
+ const current = [i + 1];
436
+ for (const [j, right] of [...b].entries())
437
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
438
+ previous = current;
439
+ }
440
+ return previous[b.length] ?? 0;
441
+ }
442
+ function closest(name, names) {
443
+ const started = names.find((known) => known.startsWith(name));
444
+ if (started !== undefined)
445
+ return started;
446
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
447
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
448
+ }
449
+ // ../kit/src/input.ts
450
+ import process4 from "process";
451
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
452
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
453
+ function duration(value, name, fallback, unit = "s") {
454
+ if (value === undefined)
455
+ return fallback;
456
+ const match = DURATION.exec(value.trim());
457
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
458
+ if (ms < 1)
459
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
460
+ return ms;
461
+ }
462
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
463
+ if (path === "-") {
464
+ if (process4.stdin.isTTY)
465
+ fail(noStdin);
466
+ return Bun.stdin.text();
467
+ }
468
+ const file = Bun.file(path);
469
+ if (!await file.exists())
470
+ fail(`no file ${path}`);
471
+ return file.text();
472
+ }
473
+
474
+ // ../kit/src/args.ts
475
+ var DASHES = /^-+/;
476
+ function jsonOption(holds) {
477
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
478
+ }
479
+
480
+ class Exit extends Error {
481
+ code;
482
+ hint;
483
+ constructor(message, code, hint) {
484
+ super(message);
485
+ this.code = code;
486
+ this.hint = hint;
487
+ }
488
+ }
489
+ function fail(message, code = 2, hint) {
490
+ throw new Exit(message, code, hint);
491
+ }
492
+
493
+ class UsageError extends Exit {
494
+ constructor(message, hint) {
495
+ super(message, 2, hint);
496
+ }
497
+ }
498
+ function badUsage(message) {
499
+ throw new UsageError(message);
500
+ }
501
+
502
+ class HelpShown extends Exit {
503
+ constructor() {
504
+ super("help shown", 0);
505
+ }
506
+ }
507
+
508
+ class Completing {
509
+ options;
510
+ positionals;
511
+ candidates;
512
+ constructor(options, positionals = [], candidates = {}) {
513
+ this.options = options;
514
+ this.positionals = positionals;
515
+ this.candidates = candidates;
516
+ }
517
+ }
518
+ var completion = { active: false };
519
+ var OUTPUT_OPTIONS = {
520
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
521
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
522
+ };
523
+ function applyOutput(color, plain, env = process5.env) {
524
+ const when = plain === true ? "never" : color ?? "auto";
525
+ if (when === "auto")
526
+ return;
527
+ if (when !== "always" && when !== "never")
528
+ badUsage(`--color takes auto, always or never, not ${when}`);
529
+ if (when === "always") {
530
+ env.FORCE_COLOR = "1";
531
+ delete env.NO_COLOR;
532
+ } else {
533
+ env.NO_COLOR = "1";
534
+ delete env.FORCE_COLOR;
535
+ }
536
+ }
537
+ function parse(args, usage, options, settings = {}) {
538
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
539
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
540
+ const listing = listed(all, settings.allowNegative === true);
541
+ if (completion.active)
542
+ throw new Completing(listing, settings.positionals, settings.candidates);
543
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
544
+ let parsed;
545
+ try {
546
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
547
+ } catch (error) {
548
+ const message = parseError(error);
549
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
550
+ }
551
+ const values = parsed.values;
552
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
553
+ if (values.help === true) {
554
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
555
+ throw new HelpShown;
556
+ }
557
+ checkChoices(parsed.values, all);
558
+ checkConflicts(parsed.values, all);
559
+ if (settings.positionals !== undefined)
560
+ checkPositionals(parsed.positionals, settings.positionals);
561
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
562
+ }
563
+ function splitRest(args, passes) {
564
+ const separator = passes ? args.indexOf("--") : -1;
565
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
566
+ }
567
+ function splitTrailing(args, options, count) {
568
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
569
+ let seen = 0;
570
+ if (count === 0)
571
+ return { own: args, rest: undefined };
572
+ for (let at = 0;at < args.length; at++) {
573
+ const word = args[at];
574
+ if (word === "--")
575
+ break;
576
+ if (word.startsWith("-")) {
577
+ if (takesValue(word))
578
+ at++;
579
+ continue;
580
+ }
581
+ seen++;
582
+ if (seen === count)
583
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
584
+ }
585
+ return { own: args, rest: undefined };
586
+ }
587
+ function listed(options, allowNegative) {
588
+ if (!allowNegative)
589
+ return options;
590
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
591
+ if (option.type !== "boolean" || option.negative === undefined)
592
+ return [[name, option]];
593
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
594
+ }));
595
+ }
596
+ function withBare(args, options) {
597
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
598
+ if (bare.size === 0)
599
+ return args;
600
+ const separator = args.indexOf("--");
601
+ const own = separator === -1 ? args : args.slice(0, separator);
602
+ return [...own.flatMap((arg, index) => {
603
+ const optional = bare.get(arg);
604
+ const next = own[index + 1];
605
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
606
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
607
+ }), ...separator === -1 ? [] : args.slice(separator)];
608
+ }
609
+ function checkConflicts(values, options) {
610
+ const given = (name) => values[name] !== undefined && values[name] !== false;
611
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
612
+ const other = given(name) ? conflicts.find(given) : undefined;
613
+ if (other !== undefined)
614
+ badUsage(`--${name} cannot be used with --${other}`);
615
+ }
616
+ }
617
+ function checkChoices(values, options) {
618
+ for (const [name, option] of Object.entries(options)) {
619
+ if (option.choices === undefined)
620
+ continue;
621
+ const given = values[name];
622
+ for (const value of Array.isArray(given) ? given : [given]) {
623
+ if (typeof value === "string")
624
+ oneOf(value, name, option.choices);
625
+ }
626
+ }
627
+ }
628
+ function oneOf(value, name, choices) {
629
+ if (!choices.includes(value))
630
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
631
+ return value;
632
+ }
633
+ function checkPositionals(given, names) {
634
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
635
+ const required = names.filter((name) => !name.startsWith("[")).length;
636
+ if (given.length < required)
637
+ badUsage(`missing ${names[given.length]}`);
638
+ if (!variadic && given.length > names.length)
639
+ badUsage(`unexpected argument ${given[names.length]}`);
640
+ }
641
+ function joinDashValues(args, options) {
642
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
643
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
644
+ const joined = [];
645
+ for (let i = 0;i < args.length; i++) {
646
+ const arg = args[i] ?? "";
647
+ if (arg === "--")
648
+ return [...joined, ...args.slice(i)];
649
+ const name = longOf.get(arg);
650
+ const next = args[i + 1];
651
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
652
+ joined.push(`--${name}=${next}`);
653
+ i++;
654
+ } else {
655
+ joined.push(arg);
656
+ }
657
+ }
658
+ return joined;
659
+ }
660
+ function parseError(error) {
661
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
662
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
663
+ }
664
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
665
+ function nearestOption(message, options, allowNegative) {
666
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
667
+ if (typed === undefined)
668
+ return;
669
+ const word = typed.replace(DASHES, "");
670
+ if (word.length < 2 && !typed.startsWith("--"))
671
+ return;
672
+ const known = Object.entries(options).flatMap(([name, option]) => [
673
+ ...option.short === undefined ? [] : [`-${option.short}`],
674
+ `--${name}`,
675
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
676
+ ]);
677
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
678
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
679
+ }
680
+ // ../kit/src/process.ts
681
+ import { constants } from "os";
682
+ import process6 from "process";
683
+ var KILL_GRACE_MS = 2000;
684
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
685
+ function exitCodeOf(code, signal) {
686
+ if (code !== null)
687
+ return code;
688
+ if (typeof signal === "number")
689
+ return 128 + signal;
690
+ return signal === null ? 129 : 128 + constants.signals[signal];
691
+ }
692
+ function holdSignals(cleanup) {
693
+ let received;
694
+ let child;
695
+ const held = {
696
+ get signal() {
697
+ return received;
698
+ },
699
+ forward: (to) => {
700
+ child = to;
701
+ },
702
+ release: () => {
703
+ for (const signal of SIGNALS)
704
+ process6.off(signal, onSignal);
705
+ }
706
+ };
707
+ function onSignal(signal) {
708
+ received = signal;
709
+ if (child !== undefined) {
710
+ child.kill(signal);
711
+ return;
712
+ }
713
+ if (cleanup === undefined)
714
+ return;
715
+ held.release();
716
+ cleanup(signal);
717
+ process6.kill(process6.pid, signal);
718
+ }
719
+ for (const signal of SIGNALS)
720
+ process6.on(signal, onSignal);
721
+ return held;
722
+ }
723
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
724
+ const chunks = [];
725
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
726
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
727
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
728
+ const timers = [];
729
+ const killGroup = (killing) => {
730
+ if (state.done)
731
+ return;
732
+ try {
733
+ if (grouped)
734
+ process6.kill(-proc.pid, killing);
735
+ else
736
+ proc.kill(killing);
737
+ } catch {}
738
+ };
739
+ const stop = () => {
740
+ killGroup("SIGTERM");
741
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
742
+ };
743
+ const onAbort = () => stop();
744
+ if (timeoutMs !== undefined) {
745
+ timers.push(setTimeout(() => {
746
+ state.timedOut = true;
747
+ stop();
748
+ }, timeoutMs));
749
+ }
750
+ if (signal?.aborted === true)
751
+ onAbort();
752
+ else
753
+ signal?.addEventListener("abort", onAbort, { once: true });
754
+ onStart?.({ kill: (killing) => killGroup(killing) });
755
+ const drain = async (stream, name) => {
756
+ for await (const data of stream) {
757
+ if (state.failure !== undefined)
758
+ continue;
759
+ try {
760
+ onChunk?.({ stream: name, data });
761
+ } catch (error) {
762
+ state.failure = error;
763
+ stop();
764
+ continue;
765
+ }
766
+ if (state.kept + data.length > maxBytes) {
767
+ state.truncated = true;
768
+ continue;
769
+ }
770
+ state.kept += data.length;
771
+ chunks.push({ stream: name, data });
772
+ }
773
+ };
774
+ try {
775
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
776
+ await proc.exited;
777
+ } finally {
778
+ state.done = true;
779
+ for (const timer of timers)
780
+ clearTimeout(timer);
781
+ signal?.removeEventListener("abort", onAbort);
782
+ }
783
+ if (state.failure !== undefined)
784
+ throw state.failure;
785
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
786
+ let output;
787
+ let text;
788
+ return {
789
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
790
+ chunks,
791
+ timedOut: state.timedOut,
792
+ truncated: state.truncated,
793
+ get output() {
794
+ return output ??= joined();
795
+ },
796
+ get text() {
797
+ return text ??= (output ??= joined()).toString();
798
+ }
799
+ };
800
+ }
801
+
802
+ // ../kit/src/progress.ts
803
+ var ESC = String.fromCharCode(27);
804
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
805
+ var RESET_STYLE = `${ESC}[0m`;
806
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
807
+ // ../kit/src/cli.ts
808
+ import process9 from "process";
809
+
810
+ // ../kit/src/usage.ts
811
+ import { appendFileSync, mkdirSync } from "fs";
812
+ import { homedir as homedir2 } from "os";
813
+ import { dirname, isAbsolute, join as join2 } from "path";
814
+ import process8 from "process";
815
+
816
+ // ../kit/src/logs.ts
817
+ import { lstatSync, openSync } from "fs";
818
+ import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
819
+ import { homedir, tmpdir } from "os";
820
+ import { join } from "path";
821
+ import process7 from "process";
822
+ var DAY_MS = 24 * 60 * 60 * 1000;
823
+ var CLI_FOLDER = "kaynooo-cli";
824
+ function isPrivateDirectory(path) {
825
+ try {
826
+ const info = lstatSync(path, { throwIfNoEntry: false });
827
+ return info !== undefined && info.isDirectory() && info.uid === (process7.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
828
+ } catch {
829
+ return false;
830
+ }
831
+ }
832
+ async function privateLogDirectory(name, env = process7.env) {
833
+ const runtime = env.XDG_RUNTIME_DIR;
834
+ const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
835
+ const path = join(base, name);
836
+ try {
837
+ await mkdir(path, { recursive: true, mode: 448 });
838
+ if (isPrivateDirectory(path))
839
+ return path;
840
+ } catch {}
841
+ return mkdtemp(join(tmpdir(), `${name.replaceAll("/", "-")}-`));
842
+ }
843
+ async function sweepLogs(dir, maxAgeMs = DAY_MS, now = Date.now()) {
844
+ let names;
845
+ try {
846
+ names = await readdir(dir);
847
+ } catch {
848
+ return;
849
+ }
850
+ for (const name of names) {
851
+ const path = join(dir, name);
852
+ try {
853
+ const info = await stat(path);
854
+ if (info.isDirectory())
855
+ await sweepLogs(path, maxAgeMs, now);
856
+ if (now - info.mtimeMs > maxAgeMs)
857
+ await rm(path, { force: true, recursive: info.isDirectory() });
858
+ } catch {
859
+ continue;
860
+ }
861
+ }
862
+ }
863
+
864
+ // ../kit/src/usage.ts
865
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
866
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
867
+ var LONGEST_NAME = 40;
868
+ var usageError;
869
+ function noteUsageError(message) {
870
+ usageError = message;
871
+ }
872
+ function stateHome(env = process8.env) {
873
+ const dir = env.XDG_STATE_HOME;
874
+ return dir !== undefined && isAbsolute(dir) ? dir : join2(homedir2(), ".local", "state");
875
+ }
876
+ function usagePath(env = process8.env) {
877
+ return join2(stateHome(env), CLI_FOLDER, "usage.jsonl");
878
+ }
879
+ function usageRecorded(env = process8.env) {
880
+ const off = env.KAYNOOO_CLI_NO_USAGE;
881
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
882
+ }
883
+ function flagNames(argv) {
884
+ const end = argv.indexOf("--");
885
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
886
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
887
+ }
888
+ function usageEntry(bin, command, argv, code, now = new Date) {
889
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
890
+ usageError = undefined;
891
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
892
+ }
893
+ function recordUsage(entry, env = process8.env) {
894
+ if (!usageRecorded(env))
895
+ return;
896
+ try {
897
+ const path = usagePath(env);
898
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
899
+ appendFileSync(path, `${JSON.stringify(entry)}
900
+ `, { mode: 384 });
901
+ } catch {}
902
+ }
903
+
904
+ // ../kit/src/cli.ts
905
+ var LEVEL_OPTIONS = {
906
+ ...OUTPUT_OPTIONS,
907
+ help: { type: "boolean", short: "h", description: "show this help" }
908
+ };
909
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
910
+ function printError(prefix, message, hint, cause) {
911
+ const colors = paint(process9.stderr);
912
+ const styled = takesControlCodes(process9.stderr);
913
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
914
+ const under = (label, text, tint) => text === undefined ? "" : `
915
+ ${styled ? tint(label) : `${label}:`} ${text}`;
916
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
917
+ }
918
+ function printJsonError(message, hint, cause) {
919
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
920
+ }
921
+ function wantsJson(argv) {
922
+ const end = argv.indexOf("--");
923
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
924
+ }
925
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
926
+ if (error instanceof HelpShown)
927
+ return 0;
928
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
929
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
930
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
931
+ if (error instanceof UsageError)
932
+ noteUsageError(error.message);
933
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
934
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
935
+ return error instanceof Exit ? error.code : 1;
936
+ }
937
+ var COMPLETE = "__complete";
938
+ var FILES = "__files__";
939
+ async function completingOf(run) {
940
+ completion.active = true;
941
+ try {
942
+ await run([]);
943
+ } catch (error) {
944
+ if (error instanceof Completing)
945
+ return error;
946
+ } finally {
947
+ completion.active = false;
948
+ }
949
+ return new Completing({});
950
+ }
951
+ function candidateLine(candidate) {
952
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
953
+ }
954
+ function positionalBeingTyped(before, { options, positionals }) {
955
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
956
+ let index = 0;
957
+ let at = 0;
958
+ while (at < before.length) {
959
+ const word = before[at];
960
+ if (word === "--") {
961
+ index += before.length - at - 1;
962
+ break;
963
+ }
964
+ if (!word.startsWith("-"))
965
+ index++;
966
+ else if (takesValue(word))
967
+ at++;
968
+ at++;
969
+ }
970
+ const last = positionals.at(-1);
971
+ if (index < positionals.length)
972
+ return positionals[index];
973
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
974
+ }
975
+ async function leafCandidates(run, words) {
976
+ const completing = await completingOf(run);
977
+ if ((words.at(-1) ?? "").startsWith("-"))
978
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
979
+ const flag = words.at(-2);
980
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
981
+ if (option?.type === "string") {
982
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
983
+ return values === undefined ? [FILES] : values.map(candidateLine);
984
+ }
985
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
986
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
987
+ return values === undefined ? [FILES] : values.map(candidateLine);
988
+ }
989
+ async function printCandidates(found) {
990
+ for (const line of await found)
991
+ console.log(line);
992
+ return 0;
993
+ }
994
+ async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
995
+ if (argv[0] === COMPLETE)
996
+ return printCandidates(leafCandidates(run, argv.slice(1)));
997
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
998
+ console.log(version);
999
+ return 0;
1000
+ }
1001
+ let code;
1002
+ try {
1003
+ code = await run(argv);
1004
+ } catch (error) {
1005
+ code = reportThrown(name, error, redact, wantsJson(argv));
1006
+ }
1007
+ if (usage !== false)
1008
+ recordUsage(usageEntry(name, undefined, argv, code));
1009
+ return code;
1010
+ }
1011
+ // ../kit/src/secrets.ts
1012
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1013
+ // ../kit/src/sessions.ts
1014
+ var {Glob } = globalThis.Bun;
1015
+ var SESSION_FILES = new Glob("*.json");
1016
+ var ACCOUNT_DIRS = new Glob("*/sessions");
1017
+ // package.json
1018
+ var version = "0.11.0";
1019
+
1020
+ // src/j.ts
1021
+ import process14 from "process";
1022
+
1023
+ // ../kit/src/fzf.ts
1024
+ import { existsSync, mkdirSync as mkdirSync2, readFileSync, writeFileSync } from "fs";
1025
+ import { homedir as homedir3 } from "os";
1026
+ import { dirname as dirname2, join as join3 } from "path";
1027
+ import process11 from "process";
1028
+ var REMEMBERED = 20;
1029
+ function table2(rows) {
1030
+ const widths = rows[0]?.cells.map((_, index) => Math.max(...rows.map((row) => Bun.stringWidth(row.cells[index])))) ?? [];
1031
+ return rows.map((row) => [
1032
+ ...row.hidden,
1033
+ ...row.cells.map((cell, index) => index === row.cells.length - 1 ? cell.trimEnd() : `${cell}${" ".repeat(widths[index] + 1 - Bun.stringWidth(cell))}`)
1034
+ ].join("\t"));
1035
+ }
1036
+ function fzf(rows, options) {
1037
+ const hidden = options.hidden ?? rows[0]?.hidden.length ?? 0;
1038
+ const proc = Bun.spawnSync([
1039
+ "fzf",
1040
+ "--prompt",
1041
+ options.prompt,
1042
+ ...options.header === undefined ? [] : ["--header", options.header],
1043
+ ...(options.expect ?? []).length > 0 ? ["--expect", (options.expect ?? []).join(",")] : [],
1044
+ "--ansi",
1045
+ "--reverse",
1046
+ "--height",
1047
+ options.height ?? "100%",
1048
+ "--delimiter",
1049
+ "\t",
1050
+ "--with-nth",
1051
+ `${hidden + 1}..`,
1052
+ "--nth",
1053
+ `1..${options.searched}`,
1054
+ "--tabstop",
1055
+ "1",
1056
+ "--tiebreak",
1057
+ "chunk,index",
1058
+ ...options.preview === undefined ? [] : ["--preview", options.preview, "--preview-window", "down,40%"],
1059
+ ...(options.bind ?? []).flatMap((bind) => ["--bind", bind]),
1060
+ ...options.query === true ? ["--print-query"] : []
1061
+ ], {
1062
+ stdin: new TextEncoder().encode(table2(rows).join(`
1063
+ `)),
1064
+ stdout: "pipe",
1065
+ stderr: "inherit"
1066
+ });
1067
+ return picked(proc.stdout.toString(), hidden, options);
1068
+ }
1069
+ function picked(output, hidden, options) {
1070
+ const lines = output.split(`
1071
+ `);
1072
+ const query = options.query === true ? lines.shift() : "";
1073
+ const [key, line] = (options.expect ?? []).length > 0 ? [lines[0], lines[1]] : ["", lines[0]];
1074
+ if (line !== undefined && line !== "")
1075
+ return { key, hidden: line.split("\t").slice(0, hidden), query };
1076
+ return options.query === true && key !== "" ? { key, hidden: [], query } : undefined;
1077
+ }
1078
+ function heightFor(count) {
1079
+ return String(Math.max(15, Math.ceil((count + 4) / 0.6)));
1080
+ }
1081
+ function historyFile(name) {
1082
+ return join3(process11.env.XDG_CACHE_HOME ?? join3(homedir3(), ".cache"), name, "history.json");
1083
+ }
1084
+ function history(name) {
1085
+ try {
1086
+ const file = historyFile(name);
1087
+ return existsSync(file) ? JSON.parse(readFileSync(file, "utf-8")) : {};
1088
+ } catch {
1089
+ return {};
1090
+ }
1091
+ }
1092
+ function runs(name) {
1093
+ return history(name)[process11.cwd()] ?? [];
1094
+ }
1095
+ function record(name, run) {
1096
+ const all = history(name);
1097
+ const file = historyFile(name);
1098
+ all[process11.cwd()] = [run, ...(all[process11.cwd()] ?? []).filter((earlier) => earlier.id !== run.id)].slice(0, REMEMBERED);
1099
+ mkdirSync2(dirname2(file), { recursive: true });
1100
+ writeFileSync(file, JSON.stringify(all));
1101
+ }
1102
+ function byRecency(items, previous, idOf) {
1103
+ const rank = new Map(previous.map((run, index) => [run.id, index]));
1104
+ const recent = items.filter((item) => rank.has(idOf(item))).sort((a, b) => rank.get(idOf(a)) - rank.get(idOf(b)));
1105
+ return [...recent, ...items.filter((item) => !rank.has(idOf(item)))];
1106
+ }
1107
+ function word(arg) {
1108
+ if (typeof arg === "string")
1109
+ return `=${arg}`;
1110
+ return "given" in arg ? `+${arg.given}` : `?${arg.ask}`;
1111
+ }
1112
+ function emit(mode, typed, recorded, command) {
1113
+ const words = command.map(word);
1114
+ console.log([mode, typed, recorded, ...words].join(`
1115
+ `));
1116
+ }
1117
+ function list(rows) {
1118
+ console.log(JSON.stringify(rows));
1119
+ }
1120
+
1121
+ // ../kit/src/prompt.ts
1122
+ import process12 from "process";
1123
+ var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|[\s\S]/giu;
1124
+ var CONTROL = /^[\x00-\x1F\x7F]/;
1125
+ var KEYS = { "\x1B[A": "up", "\x1BOA": "up", "\x1B[B": "down", "\x1BOB": "down", "\r": "enter", "\n": "enter", "\x03": "cancel", "\x1B": "cancel", "\x7F": "erase", "\b": "erase" };
1126
+ function readKeys(input) {
1127
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => KEYS[sequence] ?? (CONTROL.test(sequence) ? [] : [{ text: sequence }]));
1128
+ }
1129
+ async function input2(question, { default: fallback, mask = false, validate, ...settings } = {}) {
1130
+ let value = "";
1131
+ let invalid;
1132
+ const taken = () => value === "" ? fallback ?? "" : value;
1133
+ const shown = () => mask ? "*".repeat([...taken()].length) : taken();
1134
+ const accepted = await ask(question, settings, (colors, state, { columns }) => {
1135
+ if (state !== "asking")
1136
+ return [answer(colors, question, state, shown())];
1137
+ const characters = [...shown()];
1138
+ const room = Math.max(columns - question.length - 5, 1);
1139
+ const tail = characters.length > room ? `\u2026${characters.slice(1 - room).join("")}` : shown();
1140
+ const typed = value === "" ? colors.dim(tail) : tail;
1141
+ return [`${colors.cyan("?")} ${question} ${typed}${colors.dim("\u2588")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`]];
1142
+ }, (key) => {
1143
+ if (key === "cancel")
1144
+ return "cancel";
1145
+ invalid = undefined;
1146
+ if (key === "enter") {
1147
+ invalid = validate?.(taken());
1148
+ return invalid === undefined ? "enter" : undefined;
1149
+ }
1150
+ if (key === "erase")
1151
+ value = [...value].slice(0, -1).join("");
1152
+ else if (typeof key === "object")
1153
+ value += key.text;
1154
+ return;
1155
+ });
1156
+ return accepted ? taken() : undefined;
1157
+ }
1158
+ function answer(colors, question, state, picked) {
1159
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1160
+ }
1161
+ async function ask(question, { hint, terminal = process12 }, render, press) {
1162
+ const { stdin, stderr } = terminal;
1163
+ if (stdin.isTTY !== true || stderr.isTTY !== true)
1164
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
1165
+ const colors = paint(stderr);
1166
+ let drawn = 0;
1167
+ let outcome;
1168
+ const draw = (state) => {
1169
+ const frame = render(colors, state, { columns: stderr.columns || 80, rows: stderr.rows || 24 });
1170
+ stderr.write(`${drawn > 1 ? `\x1B[${drawn - 1}A` : ""}\r\x1B[0J${frame.join(`
1171
+ `)}`);
1172
+ drawn = frame.length;
1173
+ };
1174
+ try {
1175
+ stdin.setRawMode(true);
1176
+ stdin.resume();
1177
+ stderr.write("\x1B[?25l");
1178
+ draw("asking");
1179
+ return await new Promise((resolve) => {
1180
+ function onData(data) {
1181
+ for (const key of readKeys(data.toString())) {
1182
+ const pressed = press(key);
1183
+ if (pressed !== undefined) {
1184
+ settle(pressed);
1185
+ return;
1186
+ }
1187
+ }
1188
+ draw("asking");
1189
+ }
1190
+ function onEnd() {
1191
+ settle("cancel");
1192
+ }
1193
+ function settle(settled) {
1194
+ outcome = settled;
1195
+ stdin.off("data", onData);
1196
+ stdin.off("end", onEnd);
1197
+ resolve(settled === "enter");
1198
+ }
1199
+ stdin.on("data", onData);
1200
+ stdin.on("end", onEnd);
1201
+ });
1202
+ } finally {
1203
+ draw(outcome ?? "cancel");
1204
+ stderr.write(`
1205
+ \x1B[?25h`);
1206
+ stdin.setRawMode(false);
1207
+ stdin.pause();
1208
+ }
1209
+ }
1210
+
1211
+ // src/job-picker.ts
1212
+ import process13 from "process";
1213
+
1214
+ // src/jobs.ts
1215
+ import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2 } from "fs";
1216
+ import { dirname as dirname3, join as join5, resolve as resolvePath } from "path";
1217
+
1218
+ // src/steps.ts
1219
+ import { readdir as readdir2 } from "fs/promises";
1220
+ import { join as join4 } from "path";
1221
+ var STEP_NAMES = ["check", "typecheck", "lint", "test"];
1222
+ var TARGET = /^@?([\w-]+)(?:[ \t][^:=\n]*)?:(?!=)/gm;
1223
+ var JUSTFILES = ["justfile", "Justfile", ".justfile"];
1224
+ var MAKEFILES = ["GNUmakefile", "makefile", "Makefile"];
1225
+ var CS_FIXER_CONFIGS = [".php-cs-fixer.php", ".php-cs-fixer.dist.php"];
1226
+ var JUST_TIMEOUT_MS = 1e4;
1227
+ var PHPSTAN_CONFIGS = ["phpstan.neon", "phpstan.neon.dist", "phpstan.dist.neon"];
1228
+ var PHPUNIT_CONFIGS = ["phpunit.xml", "phpunit.xml.dist", "phpunit.dist.xml"];
1229
+ var SKIPPED = new Set(["node_modules", "vendor", "dist", "build", "var", "tmp", "coverage"]);
1230
+ async function readFirst(dir, files) {
1231
+ for (const file of files) {
1232
+ const handle = Bun.file(join4(dir, file));
1233
+ if (await handle.exists())
1234
+ return { file, text: await handle.text() };
1235
+ }
1236
+ return;
1237
+ }
1238
+ async function read(dir, ...files) {
1239
+ for (const file of files) {
1240
+ const handle = Bun.file(join4(dir, file));
1241
+ if (await handle.exists())
1242
+ return handle.text();
1243
+ }
1244
+ return;
1245
+ }
1246
+ function scripts(file, text) {
1247
+ try {
1248
+ const parsed = JSON.parse(text);
1249
+ return parsed.scripts ?? {};
1250
+ } catch {
1251
+ throw new Error(`${file} is not valid JSON`);
1252
+ }
1253
+ }
1254
+ function targets(text) {
1255
+ return [...text.matchAll(TARGET)].map((match) => match[1] ?? "");
1256
+ }
1257
+ async function recipes(dir, file, text) {
1258
+ if (Bun.which("just") === null)
1259
+ return targets(text);
1260
+ try {
1261
+ const ran = await runCommand(["just", "--justfile", file, "--dump", "--dump-format", "json"], { cwd: dir, timeoutMs: JUST_TIMEOUT_MS });
1262
+ const dump = JSON.parse(ran.text);
1263
+ if (ran.code !== 0)
1264
+ return targets(text);
1265
+ return Object.entries(dump.recipes ?? {}).filter(([, recipe]) => recipe.private !== true && (recipe.parameters ?? []).every((parameter) => parameter.default !== null || parameter.kind === "star")).map(([name]) => name);
1266
+ } catch {
1267
+ return targets(text);
1268
+ }
1269
+ }
1270
+ function callsSelf(value, bin) {
1271
+ return typeof value === "string" && (value === bin || value.startsWith(`${bin} `) || value.startsWith(`${bin} `));
1272
+ }
1273
+ async function candidates(dir, bin) {
1274
+ const steps = [];
1275
+ const packageJson = await read(dir, "package.json");
1276
+ const composerJson = await read(dir, "composer.json");
1277
+ const justfile = await readFirst(dir, JUSTFILES);
1278
+ const makefile = await read(dir, ...MAKEFILES);
1279
+ if (packageJson !== undefined) {
1280
+ for (const [name, value] of Object.entries(scripts("package.json", packageJson))) {
1281
+ if (!callsSelf(value, bin))
1282
+ steps.push({ name, command: `bun run ${name}`, source: "package.json" });
1283
+ }
1284
+ }
1285
+ if (composerJson !== undefined) {
1286
+ for (const name of Object.keys(scripts("composer.json", composerJson)))
1287
+ steps.push({ name, command: `composer run ${name}`, source: "composer.json" });
1288
+ }
1289
+ if (justfile !== undefined) {
1290
+ for (const name of await recipes(dir, justfile.file, justfile.text))
1291
+ steps.push({ name, command: `just ${name}`, source: "Justfile" });
1292
+ }
1293
+ for (const name of targets(makefile ?? ""))
1294
+ steps.push({ name, command: `make ${name}`, source: "Makefile" });
1295
+ steps.push(...await phpSteps(dir));
1296
+ return steps;
1297
+ }
1298
+ async function firstFile(dir, names) {
1299
+ for (const name of names) {
1300
+ if (await Bun.file(join4(dir, name)).exists())
1301
+ return name;
1302
+ }
1303
+ return;
1304
+ }
1305
+ async function phpSteps(dir) {
1306
+ const steps = [];
1307
+ const phpstan = await firstFile(dir, PHPSTAN_CONFIGS);
1308
+ const csFixer = await firstFile(dir, CS_FIXER_CONFIGS);
1309
+ const phpunit = await firstFile(dir, PHPUNIT_CONFIGS);
1310
+ if (phpstan !== undefined)
1311
+ steps.push({ name: "typecheck", command: "vendor/bin/phpstan analyse --no-progress --memory-limit=1G", source: phpstan });
1312
+ if (csFixer !== undefined)
1313
+ steps.push({ name: "lint", command: "vendor/bin/php-cs-fixer fix --dry-run -v", source: csFixer });
1314
+ if (phpunit !== undefined)
1315
+ steps.push({ name: "test", command: "vendor/bin/phpunit", source: phpunit });
1316
+ return steps;
1317
+ }
1318
+ async function discoverProjects(dir) {
1319
+ const own = await discover(dir);
1320
+ if (own.length > 0)
1321
+ return [{ dir, steps: own }];
1322
+ const projects = [];
1323
+ const entries = await readdir2(dir, { withFileTypes: true });
1324
+ for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
1325
+ if (!entry.isDirectory() || entry.name.startsWith(".") || SKIPPED.has(entry.name))
1326
+ continue;
1327
+ const steps = await discover(join4(dir, entry.name));
1328
+ if (steps.length > 0)
1329
+ projects.push({ name: entry.name, dir: join4(dir, entry.name), steps });
1330
+ }
1331
+ return projects;
1332
+ }
1333
+ async function discover(dir) {
1334
+ const found = await candidates(dir, "check");
1335
+ return STEP_NAMES.flatMap((name) => {
1336
+ const step = found.find((candidate) => candidate.name === name);
1337
+ return step === undefined ? [] : [step];
1338
+ });
1339
+ }
1340
+
1341
+ // src/jobs.ts
1342
+ var JUSTFILE = /^\.?justfile$/i;
1343
+ var TASKFILES = ["Taskfile.yml", "taskfile.yml", "Taskfile.yaml", "taskfile.yaml", "Taskfile.dist.yml", "taskfile.dist.yml", "Taskfile.dist.yaml", "taskfile.dist.yaml"];
1344
+ var MISE_FILES = ["mise.toml", ".mise.toml", "mise.local.toml", ".mise.local.toml", "mise", ".mise", "mise-tasks", ".mise-tasks", ".config/mise.toml", ".config/mise"];
1345
+ var LOCKFILES = [
1346
+ ["bun.lock", "bun"],
1347
+ ["bun.lockb", "bun"],
1348
+ ["pnpm-lock.yaml", "pnpm"],
1349
+ ["yarn.lock", "yarn"],
1350
+ ["package-lock.json", "npm"]
1351
+ ];
1352
+ var SKIPPED2 = new Set(["node_modules", "vendor", "dist", "build", "target", "venv", "__pycache__"]);
1353
+ var QUALIFIED = /^([a-z]+):(?!:)(.+)$/;
1354
+ var BLANKS = /\s+/;
1355
+ var TRAILING_SLASHES = /\/+$/;
1356
+ var VERSION_SUFFIX = /@.*/;
1357
+ var LEADING_HASHES = /^#*/;
1358
+ var installed = new Map;
1359
+ function has(tool) {
1360
+ if (!installed.has(tool))
1361
+ installed.set(tool, Bun.which(tool) !== null);
1362
+ return installed.get(tool);
1363
+ }
1364
+ function list2(dir) {
1365
+ try {
1366
+ return readdirSync(dir);
1367
+ } catch {
1368
+ return [];
1369
+ }
1370
+ }
1371
+ function locate(dir, here, names) {
1372
+ for (let current = dir;; current = join5(current, "..")) {
1373
+ const found = names.find((name) => existsSync2(join5(current, name)));
1374
+ if (found !== undefined)
1375
+ return join5(current, found);
1376
+ const absolute = resolvePath(current);
1377
+ if (!here || existsSync2(join5(current, ".git")) || dirname3(absolute) === absolute)
1378
+ return;
1379
+ }
1380
+ }
1381
+ function children(dir = ".") {
1382
+ return readdirSync(dir, { withFileTypes: true }).filter((child) => child.isDirectory() && !child.name.startsWith(".") && !SKIPPED2.has(child.name)).map((child) => child.name).toSorted();
1383
+ }
1384
+ function build(base, items) {
1385
+ return items.map((item) => ({ ...base, doc: null, parameters: [], ...item }));
1386
+ }
1387
+ function text2(value) {
1388
+ if (typeof value === "string")
1389
+ return value;
1390
+ if (Array.isArray(value) && value.every((line) => typeof line === "string"))
1391
+ return value.join(`
1392
+ `);
1393
+ return Bun.YAML.stringify(value, null, 2) ?? "";
1394
+ }
1395
+ function field(value, key) {
1396
+ const found = value !== null && typeof value === "object" ? value[key] : undefined;
1397
+ return typeof found === "string" ? found : null;
1398
+ }
1399
+ function recipes2(tree) {
1400
+ return [...Object.values(tree.recipes).filter((recipe) => !recipe.private), ...Object.values(tree.modules).flatMap((module) => recipes2(module))];
1401
+ }
1402
+ function justFlags(dir, here) {
1403
+ if (here)
1404
+ return [];
1405
+ const file = list2(dir).find((name) => JUSTFILE.test(name));
1406
+ return file === undefined ? undefined : ["--justfile", join5(dir, file)];
1407
+ }
1408
+ function just(dir, here) {
1409
+ const flags = justFlags(dir, here);
1410
+ if (flags === undefined || !has("just"))
1411
+ return [];
1412
+ const proc = Bun.spawnSync(["just", ...flags, "--dump", "--dump-format", "json"], { stderr: "pipe" });
1413
+ if (!proc.success)
1414
+ return [];
1415
+ const items = recipes2(JSON.parse(proc.stdout.toString())).map((recipe) => ({ name: recipe.namepath, doc: recipe.doc, parameters: recipe.parameters }));
1416
+ return build({ kind: "just", tag: "just", runner: ["just"], separated: false, dir }, items);
1417
+ }
1418
+ function targets2(source) {
1419
+ const found = new Map;
1420
+ let pending = null;
1421
+ for (const line of source.split(`
1422
+ `)) {
1423
+ if (line.startsWith("\t"))
1424
+ continue;
1425
+ const [rule = "", ...rest] = line.split("#");
1426
+ const comment = rest.join("#").replace(LEADING_HASHES, "").trim() || null;
1427
+ if (rule.trim() === "") {
1428
+ pending = line.startsWith("##") ? comment : null;
1429
+ continue;
1430
+ }
1431
+ const colon = rule.indexOf(":");
1432
+ const assignment = rule[colon + 1] === "=" || rule.slice(colon + 1).startsWith(":=");
1433
+ if (colon === -1 || assignment) {
1434
+ pending = null;
1435
+ continue;
1436
+ }
1437
+ const doc = comment ?? pending;
1438
+ for (const name of rule.slice(0, colon).trim().split(BLANKS)) {
1439
+ if (name.startsWith(".") || name.includes("%") || name.includes("$"))
1440
+ continue;
1441
+ if (!found.has(name))
1442
+ found.set(name, doc);
1443
+ }
1444
+ pending = null;
1445
+ }
1446
+ return [...found].map(([name, doc]) => ({ name, doc }));
1447
+ }
1448
+ function show(source, target) {
1449
+ const lines = source.split(`
1450
+ `);
1451
+ const start = lines.findIndex((line) => {
1452
+ const hash = line.indexOf("#");
1453
+ const rule = hash === -1 ? line : line.slice(0, hash);
1454
+ const colon = rule.indexOf(":");
1455
+ return colon !== -1 && rule[colon + 1] !== "=" && rule.slice(0, colon).trim().split(BLANKS).includes(target);
1456
+ });
1457
+ if (start === -1)
1458
+ return target;
1459
+ let end = start + 1;
1460
+ while (end < lines.length && (lines[end].startsWith("\t") || lines[end].trim() === ""))
1461
+ end++;
1462
+ return lines.slice(start, end).join(`
1463
+ `).trimEnd();
1464
+ }
1465
+ function make(dir) {
1466
+ const file = MAKEFILES.find((name) => existsSync2(join5(dir, name)));
1467
+ if (file === undefined)
1468
+ return [];
1469
+ const source = readFileSync2(join5(dir, file), "utf-8");
1470
+ return build({ kind: "make", tag: "make", runner: ["make"], separated: false, dir }, targets2(source).map((target) => ({ ...target, body: show(source, target.name) })));
1471
+ }
1472
+ function manager(dir, manifest) {
1473
+ const declared = typeof manifest.packageManager === "string" ? manifest.packageManager.replace(VERSION_SUFFIX, "") : undefined;
1474
+ const known = LOCKFILES.find(([, name]) => name === declared);
1475
+ if (known !== undefined)
1476
+ return known[1];
1477
+ for (let current = resolvePath(dir);; current = dirname3(current)) {
1478
+ const found = LOCKFILES.find(([file]) => existsSync2(join5(current, file)));
1479
+ if (found !== undefined)
1480
+ return found[1];
1481
+ if (dirname3(current) === current)
1482
+ return "bun";
1483
+ }
1484
+ }
1485
+ function table3(value) {
1486
+ return value !== null && typeof value === "object" ? value : {};
1487
+ }
1488
+ function packageScripts(dir, here) {
1489
+ const file = locate(dir, here, ["package.json"]);
1490
+ if (file === undefined)
1491
+ return [];
1492
+ const manifest = JSON.parse(readFileSync2(file, "utf-8"));
1493
+ const tool = manager(dirname3(file), manifest);
1494
+ const items = Object.entries(table3(manifest.scripts)).map(([name, command]) => ({ name, body: text2(command) }));
1495
+ return build({ kind: "package", tag: tool, runner: [tool, "run"], separated: tool === "npm", dir: dirname3(file) }, items);
1496
+ }
1497
+ function composer(dir, here) {
1498
+ const file = locate(dir, here, ["composer.json"]);
1499
+ if (file === undefined)
1500
+ return [];
1501
+ const manifest = JSON.parse(readFileSync2(file, "utf-8"));
1502
+ const descriptions = table3(manifest["scripts-descriptions"]);
1503
+ const items = Object.entries(table3(manifest.scripts)).map(([name, command]) => ({ name, doc: field(descriptions, name), body: text2(command) }));
1504
+ return build({ kind: "composer", tag: "composer", runner: ["composer", "run"], separated: true, dir: dirname3(file) }, items);
1505
+ }
1506
+ function deno(dir, here) {
1507
+ const file = locate(dir, here, ["deno.json", "deno.jsonc"]);
1508
+ if (file === undefined)
1509
+ return [];
1510
+ const manifest = Bun.JSONC.parse(readFileSync2(file, "utf-8"));
1511
+ const items = Object.entries(table3(manifest.tasks)).map(([name, task]) => ({ name, doc: field(task, "description"), body: field(task, "command") ?? text2(task) }));
1512
+ return build({ kind: "deno", tag: "deno", runner: ["deno", "task"], separated: false, dir: dirname3(file) }, items);
1513
+ }
1514
+ function taskfile(dir, here) {
1515
+ const file = locate(dir, here, TASKFILES);
1516
+ if (file === undefined)
1517
+ return [];
1518
+ const tasks = table3(Bun.YAML.parse(readFileSync2(file, "utf-8"))?.tasks);
1519
+ const items = Object.entries(tasks).filter(([, task]) => !(task !== null && typeof task === "object" && task.internal === true)).map(([name, task]) => ({ name, doc: field(task, "desc") ?? field(task, "summary"), body: text2(task) }));
1520
+ return build({ kind: "task", tag: "task", runner: ["task"], separated: true, dir: dirname3(file) }, items);
1521
+ }
1522
+ function mise(dir, here) {
1523
+ if (!has("mise") || !here && !MISE_FILES.some((name) => existsSync2(join5(dir, name))))
1524
+ return [];
1525
+ const proc = Bun.spawnSync(["mise", "tasks", "ls", "--json"], { cwd: dir, stderr: "pipe" });
1526
+ if (!proc.success)
1527
+ return [];
1528
+ const root = `${resolvePath(dir)}/`;
1529
+ const items = JSON.parse(proc.stdout.toString()).filter((task) => !task.hide && (here || !task.global && task.source.startsWith(root))).map((task) => ({ name: task.name, doc: task.description || null, body: task.file ?? task.run.join(`
1530
+ `) }));
1531
+ return build({ kind: "mise", tag: "mise", runner: ["mise", "run"], separated: false, dir }, items);
1532
+ }
1533
+ function pyproject(dir, here) {
1534
+ const file = locate(dir, here, ["pyproject.toml"]);
1535
+ if (file === undefined)
1536
+ return [];
1537
+ const manifest = Bun.TOML.parse(readFileSync2(file, "utf-8"));
1538
+ const tool = table3(manifest.tool);
1539
+ const project = table3(manifest.project);
1540
+ const uv = locate(dirname3(file), true, ["uv.lock"]) !== undefined;
1541
+ const poe = Object.entries(table3(table3(tool.poe).tasks)).filter(([name]) => !name.startsWith("_")).map(([name, task]) => ({ name, doc: field(task, "help"), body: field(task, "cmd") ?? field(task, "shell") ?? text2(task) }));
1542
+ const entryPoints = Object.entries(table3(project.scripts)).map(([name, target]) => ({ name, body: text2(target) }));
1543
+ return [
1544
+ ...build({ kind: "poe", tag: "poe", runner: uv ? ["uv", "run", "poe"] : ["poe"], separated: false, dir: dirname3(file) }, poe),
1545
+ ...build({ kind: "uv", tag: "uv", runner: ["uv", "run"], separated: false, dir: dirname3(file) }, entryPoints)
1546
+ ];
1547
+ }
1548
+ var READERS = [just, make, packageScripts, composer, deno, taskfile, mise, pyproject];
1549
+ var READER_OF = {
1550
+ just,
1551
+ make,
1552
+ package: packageScripts,
1553
+ composer,
1554
+ deno,
1555
+ task: taskfile,
1556
+ mise,
1557
+ poe: pyproject,
1558
+ uv: pyproject
1559
+ };
1560
+ function workspaces() {
1561
+ const manifest = existsSync2("package.json") ? JSON.parse(readFileSync2("package.json", "utf-8")) : {};
1562
+ const declared = Array.isArray(manifest.workspaces) ? manifest.workspaces : table3(manifest.workspaces).packages;
1563
+ const pnpm = existsSync2("pnpm-workspace.yaml") ? table3(Bun.YAML.parse(readFileSync2("pnpm-workspace.yaml", "utf-8"))).packages : undefined;
1564
+ const patterns = [declared, pnpm].flatMap((value) => Array.isArray(value) ? value.filter((pattern) => typeof pattern === "string") : []);
1565
+ const excluded = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => new Bun.Glob(pattern.slice(1)));
1566
+ return patterns.filter((pattern) => !pattern.startsWith("!")).flatMap((pattern) => [...new Bun.Glob(`${pattern.replace(TRAILING_SLASHES, "")}/package.json`).scanSync({ cwd: "." })].map((file) => dirname3(file))).filter((dir) => !dir.split("/").includes("node_modules") && !excluded.some((glob) => glob.match(dir)));
1567
+ }
1568
+ function folders() {
1569
+ return [...new Set([...children(), ...workspaces()])].filter((dir) => dir !== ".");
1570
+ }
1571
+ function everything() {
1572
+ const here = READERS.flatMap((reader) => reader(".", true));
1573
+ const below = folders().flatMap((dir) => READERS.flatMap((reader) => reader(dir, false)));
1574
+ const seen = new Set;
1575
+ return [...here, ...below].filter((entry) => {
1576
+ const id = `${entry.kind} ${entry.dir} ${entry.name}`;
1577
+ const fresh = !seen.has(id);
1578
+ seen.add(id);
1579
+ return fresh;
1580
+ });
1581
+ }
1582
+ function readKind(kind, dir) {
1583
+ return READER_OF[kind](dir, dir === ".").filter((entry) => entry.kind === kind);
1584
+ }
1585
+ function key(entry) {
1586
+ return entry.dir === "." ? entry.name : `${entry.dir}/${entry.name}`;
1587
+ }
1588
+ function id(entry) {
1589
+ return `${entry.tag}:${key(entry)}`;
1590
+ }
1591
+ function resolve(entries, named) {
1592
+ const qualified = QUALIFIED.exec(named);
1593
+ const tagged = qualified && entries.some((entry) => entry.tag === qualified[1]) ? qualified : undefined;
1594
+ const pool = tagged ? entries.filter((entry) => entry.tag === tagged[1]) : entries;
1595
+ const rest = tagged ? tagged[2] : named;
1596
+ const exact = pool.filter((entry) => key(entry) === rest);
1597
+ return exact.length > 0 ? exact : pool.filter((entry) => entry.name === rest);
1598
+ }
1599
+ function shortest(entries, entry) {
1600
+ const found = resolve(entries, key(entry));
1601
+ return found.length === 1 && found[0] === entry ? key(entry) : id(entry);
1602
+ }
1603
+ function signature(entry) {
1604
+ return entry.parameters.map((parameter) => parameter.default === null && parameter.kind === "singular" ? `<${parameter.name}>` : `[${parameter.name}]`).join(" ");
1605
+ }
1606
+
1607
+ // src/job-picker.ts
1608
+ var TINTS = { just: "yellow", make: "blue", package: "magenta", composer: "cyan", deno: "green", task: "cyan", mise: "red", poe: "green", uv: "green" };
1609
+ function labelled(entries) {
1610
+ return new Set(entries.map((entry) => entry.tag)).size > 1;
1611
+ }
1612
+ function row(entry, labels, signed) {
1613
+ const colors = paint(process13.stderr);
1614
+ const keyed = entry.dir === "." ? entry.name : `${colors.dim(`${entry.dir}/`)}${entry.name}`;
1615
+ return {
1616
+ hidden: [entry.kind, entry.dir, entry.name, id(entry)],
1617
+ cells: [...labels ? [colors[TINTS[entry.kind]](entry.tag)] : [], keyed, ...signed ? [colors.cyan(signature(entry))] : [], colors.dim(entry.doc ?? "")]
1618
+ };
1619
+ }
1620
+ function pickJob(entries, narrowed = false) {
1621
+ const labels = labelled(entries);
1622
+ const signed = entries.some((entry) => signature(entry) !== "");
1623
+ const picked = fzf(entries.map((entry) => row(entry, labels, signed)), {
1624
+ prompt: `${[...new Set(entries.map((entry) => entry.tag))].join("/")}> `,
1625
+ searched: labels ? 2 : 1,
1626
+ ...narrowed ? { height: heightFor(entries.length) } : {},
1627
+ preview: `${process13.execPath} ${process13.argv[1]} --show {1} {2} {3}`
1628
+ });
1629
+ return entries.find((candidate) => id(candidate) === picked?.hidden[3]);
1630
+ }
1631
+
1632
+ // src/j.ts
1633
+ var usage2 = `j [name] [args...]
1634
+ j -
1635
+
1636
+ Without a name, picks a recipe, target, script or task of this folder, its parents and its child folders with fzf when it is installed and a terminal is attached, and runs it. The ones run last come first, per folder. Without fzf or a terminal it lists them instead.
1637
+ \`j -\` runs the last one again with the same arguments, \`j <name> [args...]\` runs without the picker, the words after the name filling the parameters in order and the required ones left being asked for.
1638
+ The sources are a Justfile, a Makefile, the scripts of a package.json (through its package manager), composer.json scripts, deno tasks, a Taskfile, mise tasks and a pyproject (poe tasks and entry points).
1639
+ A name is the key behind the folder it runs from, \`api/test\`, bare for this folder. A name several entries share offers them, unless it comes qualified by its runner: \`just:check\`, \`bun:api/test\`.
1640
+
1641
+ Exits with the code of the command it ran, 1 when there is nothing to run here or nothing by that name.`;
1642
+ var options = {
1643
+ json: jsonOption("[{ id, key, runner, dir, name, doc, parameters }]")
1644
+ };
1645
+ function preview(kind, dir, name) {
1646
+ const entry = readKind(kind, dir).find((candidate) => candidate.name === name);
1647
+ if (entry === undefined)
1648
+ return;
1649
+ const colors = paint(process14.stdout);
1650
+ console.log(`${colors.dim(`$ ${dir === "." ? "" : `env -C ${dir} `}`)}${colors.bold([...entry.runner, entry.name].join(" "))}
1651
+ `);
1652
+ if (entry.body !== undefined)
1653
+ console.log(entry.body);
1654
+ else
1655
+ Bun.spawnSync(["just", ...justFlags(dir, dir === ".") ?? [], "--show", name], { stdout: "inherit", stderr: "inherit" });
1656
+ }
1657
+ function names(found) {
1658
+ const described = (entry) => entry.doc === null || entry.doc === "" ? entry.tag : entry.doc;
1659
+ return [...new Set(found.map(key))].flatMap((name) => {
1660
+ const same = resolve(found, name);
1661
+ return same.length === 1 ? [[name, described(same[0])]] : [[name, same.map((entry) => entry.tag).join(", ")], ...same.map((entry) => [id(entry), described(entry)])];
1662
+ });
1663
+ }
1664
+ function listed2(found) {
1665
+ const labels = labelled(found);
1666
+ return byRecency(found, runs("j"), id).map((entry) => ({
1667
+ label: [labels ? entry.tag : "", key(entry), signature(entry)].filter(Boolean).join(" "),
1668
+ hint: entry.doc ?? "",
1669
+ typed: shortest(found, entry),
1670
+ preview: ["--show", entry.kind, entry.dir, entry.name],
1671
+ editsTyped: true
1672
+ }));
1673
+ }
1674
+ function table4(found) {
1675
+ const colors = paint(process14.stdout);
1676
+ const labels = labelled(found);
1677
+ const rows = found.map((entry) => [...labels ? [entry.tag] : [], key(entry), signature(entry)]);
1678
+ const widths = rows[0]?.map((_, column) => Math.max(...rows.map((cells) => cells[column].length))) ?? [];
1679
+ return found.map((entry, index) => `${rows[index].map((cell, column) => cell.padEnd(widths[column])).join(" ")} ${colors.dim(entry.doc ?? "")}`.trimEnd()).join(`
1680
+ `);
1681
+ }
1682
+ function missing(entry, given) {
1683
+ return entry.parameters.slice(given.length).filter((parameter) => parameter.default === null && parameter.kind === "singular").map((parameter) => parameter.name);
1684
+ }
1685
+ function commandOf(entry, args) {
1686
+ const separated = entry.separated && args.length > 0 ? ["--"] : [];
1687
+ return [...entry.dir === "." ? [] : ["env", "-C", entry.dir], ...entry.runner, entry.name, ...separated, ...args];
1688
+ }
1689
+ async function j(argv) {
1690
+ const [flag = ""] = argv;
1691
+ if (flag === "--show") {
1692
+ const [kind = "just", dir = ".", name = ""] = argv.slice(1);
1693
+ preview(kind, dir, name);
1694
+ return 0;
1695
+ }
1696
+ if (flag === "--record") {
1697
+ record("j", { id: argv[1] ?? "", args: argv.slice(2) });
1698
+ return 0;
1699
+ }
1700
+ if (flag === "--list" || flag === "--names") {
1701
+ const found = everything();
1702
+ if (found.length === 0)
1703
+ fail("nothing to run here: no recipe, target, script or task", 1);
1704
+ if (flag === "--list")
1705
+ list(listed2(found));
1706
+ else
1707
+ console.log(names(found).map(([name, description]) => `${name} ${description}`).join(`
1708
+ `));
1709
+ return 0;
1710
+ }
1711
+ const emitting = flag === "--emit";
1712
+ const args = emitting ? argv.slice(1) : argv;
1713
+ const last = args[0] === "-";
1714
+ const parsed = last ? { values: {}, positionals: ["-"], rest: args.slice(1) } : parse(args, usage2, options, {
1715
+ positionals: ["[name]"],
1716
+ trailing: true,
1717
+ replaces: "reading the Justfile, Makefile, package.json scripts or composer scripts to find what to run, then retyping it",
1718
+ examples: ["j", ["j test", "run the test recipe, script or task"], ["j api/test --watch", "a child folder's, with an argument"], ["j just:check", "the one of a runner, when several share the name"], ["j -", "the last one again"]]
1719
+ });
1720
+ const [named] = parsed.positionals;
1721
+ const given = parsed.rest ?? [];
1722
+ const found = everything();
1723
+ if (found.length === 0)
1724
+ fail("nothing to run here: no recipe, target, script or task", 1);
1725
+ const previous = runs("j");
1726
+ const interactive = process14.stdin.isTTY && process14.stderr.isTTY && parsed.values.json !== true;
1727
+ let entry;
1728
+ let words = given;
1729
+ if (named === "-") {
1730
+ const earlier = previous[0];
1731
+ entry = earlier && found.find((candidate) => id(candidate) === earlier.id);
1732
+ if (entry === undefined)
1733
+ fail(earlier ? `${earlier.id} is gone` : "nothing run here yet", 1);
1734
+ words = [...earlier.args, ...given];
1735
+ } else if (named === undefined) {
1736
+ if (!interactive || Bun.which("fzf") === null) {
1737
+ if (emitting)
1738
+ fail("the picker needs a terminal and fzf", 1);
1739
+ if (interactive)
1740
+ console.error("fzf is not installed, listing what can run instead");
1741
+ if (parsed.values.json === true)
1742
+ printJson(found.map((each) => ({ id: id(each), key: key(each), runner: each.tag, dir: each.dir, name: each.name, doc: each.doc, parameters: each.parameters })));
1743
+ else
1744
+ console.log(table4(found));
1745
+ return 0;
1746
+ }
1747
+ entry = pickJob(byRecency(found, previous, id));
1748
+ } else {
1749
+ const matching = resolve(found, named);
1750
+ if (matching.length === 0) {
1751
+ const nearest = closest(named, found.map(key));
1752
+ fail(`nothing named ${named}${nearest === undefined ? "" : `, did you mean ${nearest}?`}`, 1);
1753
+ }
1754
+ if (matching.length > 1 && (!interactive || Bun.which("fzf") === null))
1755
+ fail(`${named} is several: ${matching.map(id).join(", ")}`, 1, "qualify it with its runner");
1756
+ entry = matching.length === 1 ? matching[0] : pickJob(matching, true);
1757
+ }
1758
+ if (entry === undefined)
1759
+ return 1;
1760
+ const typed = shortest(found, entry);
1761
+ const asks = missing(entry, words);
1762
+ if (emitting) {
1763
+ emit("run", typed, id(entry), commandOf(entry, [...words.map((word) => ({ given: word })), ...asks.map((ask) => ({ ask }))]));
1764
+ return 0;
1765
+ }
1766
+ const answers = [];
1767
+ for (const ask of asks) {
1768
+ const answer = await input2(ask);
1769
+ if (answer === undefined)
1770
+ return 1;
1771
+ answers.push(answer);
1772
+ }
1773
+ const all = [...words, ...answers];
1774
+ record("j", { id: id(entry), args: all });
1775
+ return Bun.spawn(commandOf(entry, all), { stdio: ["inherit", "inherit", "inherit"] }).exited;
1776
+ }
1777
+
1778
+ // src/j-cli.ts
1779
+ process15.exitCode = await runMain({ name: "j", version, run: j });