@kaynooo/cli-code 0.8.1 → 0.9.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/cli.js ADDED
@@ -0,0 +1,1888 @@
1
+ #!/usr/bin/env -S bun --no-env-file
2
+ // @bun
3
+
4
+ // src/cli.ts
5
+ import process13 from "process";
6
+ // ../kit/src/args.ts
7
+ import process5 from "process";
8
+ import { parseArgs } from "util";
9
+
10
+ // ../kit/src/format.ts
11
+ import process3 from "process";
12
+
13
+ // ../kit/src/style.ts
14
+ import process2 from "process";
15
+
16
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
17
+ function x(s) {
18
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
19
+ if (!/^[a-f0-9]+$/.test(r))
20
+ return [0, 0, 0];
21
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
22
+ if (t === 3 || t === 4) {
23
+ 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;
24
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
25
+ }
26
+ if (t !== 6 && t !== 8)
27
+ throw Error(`Invalid hex color length: ${t}`);
28
+ 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;
29
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
30
+ throw Error(`Invalid hex color value: ${s}`);
31
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
32
+ }
33
+ function A(s) {
34
+ let [r, t, n, a] = s;
35
+ if (a)
36
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
37
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
38
+ }
39
+ function R(s, r, t) {
40
+ s = (s % 360 + 360) % 360, t /= 100;
41
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
42
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
43
+ return Math.round(255 * y);
44
+ };
45
+ return [a(0), a(8), a(4)];
46
+ }
47
+ function k(s) {
48
+ let [r, t, n] = s;
49
+ r /= 255, t /= 255, n /= 255;
50
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
51
+ if (a !== b) {
52
+ let u = a - b;
53
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
54
+ o = (t - n) / u + (t < n ? 6 : 0);
55
+ else if (a === t)
56
+ o = (n - r) / u + 2;
57
+ else
58
+ o = (r - t) / u + 4;
59
+ o /= 6;
60
+ }
61
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
62
+ }
63
+ function H(s, r, t) {
64
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
65
+ let n = (a) => {
66
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
67
+ return Math.round(255 * o);
68
+ };
69
+ return [n(5), n(3), n(1)];
70
+ }
71
+ function f(s) {
72
+ let [r, t, n] = s;
73
+ r /= 255, t /= 255, n /= 255;
74
+ 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;
75
+ if (o !== 0) {
76
+ if (a === r)
77
+ y = (t - n) / o + (t < n ? 6 : 0);
78
+ else if (a === t)
79
+ y = (n - r) / o + 2;
80
+ else
81
+ y = (r - t) / o + 4;
82
+ y /= 6;
83
+ }
84
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
85
+ }
86
+ function O(s) {
87
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
88
+ if (a === 1)
89
+ return [0, 0, 0, 100];
90
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
91
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
92
+ }
93
+ function v(s, r, t, n) {
94
+ 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))];
95
+ }
96
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
97
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
98
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
99
+ function T(s) {
100
+ 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);
101
+ 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)];
102
+ }
103
+ function M(s, r, t) {
104
+ 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)));
105
+ return [u(o), u(y), u(c)];
106
+ }
107
+ function d(s) {
108
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
109
+ return [i(r, 4), i(a, 4), i(b, 2)];
110
+ }
111
+ function C(s, r, t) {
112
+ let n = t * Math.PI / 180;
113
+ return M(s, r * Math.cos(n), r * Math.sin(n));
114
+ }
115
+ function l(s) {
116
+ let r = s / 255;
117
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
118
+ }
119
+
120
+ class e {
121
+ r;
122
+ g;
123
+ b;
124
+ a;
125
+ constructor(s, r, t, n = 1) {
126
+ this.r = s, this.g = r, this.b = t, this.a = n;
127
+ }
128
+ static from(s, r) {
129
+ if (s === "hex") {
130
+ let [t, n, a, b] = x(r);
131
+ return new e(t, n, a, b);
132
+ }
133
+ if (s === "rgb") {
134
+ if (Array.isArray(r)) {
135
+ let [o, y, c, u] = r;
136
+ return new e(o, y, c, u);
137
+ }
138
+ let { r: t, g: n, b: a, a: b } = r;
139
+ return new e(t, n, a, b);
140
+ }
141
+ if (s === "hsl") {
142
+ let t, n, a, b;
143
+ if (Array.isArray(r))
144
+ [t, n, a, b] = r;
145
+ else
146
+ ({ h: t, s: n, l: a, a: b } = r);
147
+ let [o, y, c] = R(t, n, a);
148
+ return new e(o, y, c, b);
149
+ }
150
+ if (s === "hsv") {
151
+ let t, n, a, b;
152
+ if (Array.isArray(r))
153
+ [t, n, a, b] = r;
154
+ else
155
+ ({ h: t, s: n, v: a, a: b } = r);
156
+ let [o, y, c] = H(t, n, a);
157
+ return new e(o, y, c, b);
158
+ }
159
+ if (s === "cmyk") {
160
+ let t, n, a, b, o;
161
+ if (Array.isArray(r))
162
+ [t, n, a, b, o] = r;
163
+ else
164
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
165
+ let [y, c, u] = v(t, n, a, b);
166
+ return new e(y, c, u, o);
167
+ }
168
+ if (s === "oklch") {
169
+ let t, n, a, b;
170
+ if (Array.isArray(r))
171
+ [t, n, a, b] = r;
172
+ else
173
+ ({ l: t, c: n, h: a, a: b } = r);
174
+ let [o, y, c] = C(t, n, a);
175
+ return new e(o, y, c, b);
176
+ }
177
+ if (s === "oklab") {
178
+ let t, n, a, b;
179
+ if (Array.isArray(r))
180
+ [t, n, a, b] = r;
181
+ else
182
+ ({ l: t, a: n, b: a, alpha: b } = r);
183
+ let [o, y, c] = M(t, n, a);
184
+ return new e(o, y, c, b);
185
+ }
186
+ throw Error("Invalid input");
187
+ }
188
+ to(s) {
189
+ switch (s) {
190
+ case "rgb":
191
+ return [this.r, this.g, this.b];
192
+ case "rgba":
193
+ return [this.r, this.g, this.b, this.a];
194
+ case "hex":
195
+ return A([this.r, this.g, this.b]);
196
+ case "hexa":
197
+ return A([this.r, this.g, this.b, this.a]);
198
+ case "hsl":
199
+ return k([this.r, this.g, this.b]);
200
+ case "hsla":
201
+ return [...k([this.r, this.g, this.b]), this.a];
202
+ case "hsv":
203
+ return f([this.r, this.g, this.b]);
204
+ case "hsva":
205
+ return [...f([this.r, this.g, this.b]), this.a];
206
+ case "cmyk":
207
+ return O([this.r, this.g, this.b]);
208
+ case "cmyka":
209
+ return [...O([this.r, this.g, this.b]), this.a];
210
+ case "oklch":
211
+ return d([this.r, this.g, this.b]);
212
+ case "oklcha":
213
+ return [...d([this.r, this.g, this.b]), this.a];
214
+ case "oklab":
215
+ return T([this.r, this.g, this.b]);
216
+ case "oklaba":
217
+ return [...T([this.r, this.g, this.b]), this.a];
218
+ default:
219
+ return [this.r, this.g, this.b];
220
+ }
221
+ }
222
+ getLuminance() {
223
+ let s = l(this.r), r = l(this.g), t = l(this.b);
224
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
225
+ }
226
+ contrastRatio(s) {
227
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
228
+ return (n + 0.05) / (a + 0.05);
229
+ }
230
+ bestContrastForeground() {
231
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
232
+ return t >= n ? s : r;
233
+ }
234
+ }
235
+
236
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
237
+ var r = 39;
238
+ var o = 49;
239
+ var f2 = "\x1B[";
240
+ 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") => {
241
+ let [a, l, s] = e.from("hex", i).to("rgb");
242
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
243
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
244
+ var b = new Set(["", "1", "2", "3", "true"]);
245
+ function h(i, n = globalThis.process?.env ?? {}) {
246
+ if (n.FORCE_COLOR !== undefined)
247
+ return b.has(n.FORCE_COLOR);
248
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
249
+ return false;
250
+ return i?.isTTY === true;
251
+ }
252
+ function d2(i, n, a) {
253
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
254
+ return n;
255
+ let l = "", s = "";
256
+ for (let g = 0, y = i.length;g < y; g++) {
257
+ let [c, p] = i[g];
258
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
259
+ }
260
+ return l + n + s;
261
+ }
262
+ function u(i, n = []) {
263
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
264
+ let g = C2[s];
265
+ if (Array.isArray(g))
266
+ return u(i, [...n, g]);
267
+ if (typeof g === "function")
268
+ return (...y) => u(i, [...n, g(...y)]);
269
+ throw Error(`Unknown style: ${String(s)}`);
270
+ } });
271
+ }
272
+ function le(i = {}) {
273
+ return u(i);
274
+ }
275
+ var t = le();
276
+
277
+ // ../kit/src/style.ts
278
+ var MARKS = {
279
+ ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
280
+ warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
281
+ problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
282
+ note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
283
+ };
284
+ function takesControlCodes(stream, env = process2.env) {
285
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
286
+ }
287
+ function paint(stream, env = process2.env) {
288
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
289
+ }
290
+ function marked(mark, text, stream, detail, env = process2.env) {
291
+ const colors = paint(stream, env);
292
+ const { symbol, word, paint: tint } = MARKS[mark];
293
+ const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
294
+ return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
295
+ }
296
+ function warn(text, detail) {
297
+ console.error(marked("warn", text, process2.stderr, detail));
298
+ }
299
+ var STATUSES = {
300
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
301
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
302
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
303
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
304
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
305
+ };
306
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
307
+
308
+ // ../kit/src/format.ts
309
+ function upTo(text, separator) {
310
+ const end = text.indexOf(separator);
311
+ return end === -1 ? text : text.slice(0, end);
312
+ }
313
+ function truncate(text, width) {
314
+ return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
315
+ }
316
+ var LINE_BREAKS = /\s*\n\s*/g;
317
+ var ESCAPE = String.fromCharCode(27);
318
+ function textWidth(text) {
319
+ return Bun.stringWidth(text);
320
+ }
321
+ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
322
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
323
+ const widths = [];
324
+ for (const row of cells) {
325
+ for (const [index, cell] of row.entries())
326
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
327
+ }
328
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
329
+ const colors = paint(process3.stdout);
330
+ const lines = shown.map((row) => row.map((cell, index) => {
331
+ const width = widths[index] ?? 0;
332
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
333
+ if (align[index] === "right")
334
+ return `${gap}${cell}`;
335
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
336
+ }).join(" ").trimEnd());
337
+ return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
338
+ `);
339
+ }
340
+ function narrow(rows, widths, limit) {
341
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
342
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
343
+ const floor = 8;
344
+ while (used() > limit) {
345
+ let widest = -1;
346
+ for (const [index, width] of widths.entries()) {
347
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
348
+ widest = index;
349
+ }
350
+ if (widest === -1)
351
+ break;
352
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
353
+ }
354
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
355
+ }
356
+ function printJson(value) {
357
+ console.log(JSON.stringify(value, undefined, 2));
358
+ }
359
+
360
+ // ../kit/src/help.ts
361
+ import process4 from "process";
362
+ var OPTIONAL = /\[[^\]]+\]/g;
363
+ var USAGE_PREFIX = /^usage:\s*/i;
364
+ var FULL_STOP = /\.$/;
365
+ function usageLine(usage, colors = paint(process4.stdout)) {
366
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
367
+ }
368
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
369
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
370
+ `);
371
+ }
372
+ function exitRows(exits, colors = paint(process4.stdout)) {
373
+ if (exits.length === 0)
374
+ return [];
375
+ const width = Math.max(...exits.map(([code]) => String(code).length));
376
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
377
+ }
378
+ function replacesRows(replaces, colors = paint(process4.stdout)) {
379
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
380
+ }
381
+ function wantsHelpJson(env = process4.env) {
382
+ return env.KIT_HELP === "json";
383
+ }
384
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
385
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
386
+ `);
387
+ const first = lines[0];
388
+ const colon = first.indexOf(": ");
389
+ const prose = lines[lines.indexOf("") + 1] ?? "";
390
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
391
+ return {
392
+ synopsis: colon === -1 ? first : first.slice(0, colon),
393
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
394
+ ...replaces === undefined ? {} : { replaces },
395
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
396
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
397
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
398
+ };
399
+ }
400
+ function exampleRows(examples, colors = paint(process4.stdout)) {
401
+ if (examples.length === 0)
402
+ return [];
403
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
404
+ }
405
+ function optionRows(options, colors = paint(process4.stdout)) {
406
+ const rows = Object.entries(options).map(([name, option]) => {
407
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
408
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
409
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
410
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
411
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
412
+ });
413
+ const width = Math.max(0, ...rows.map((row) => row.width));
414
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
415
+ }
416
+
417
+ // ../kit/src/text.ts
418
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
419
+ function distance(a, b) {
420
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
421
+ for (const [i, left] of [...a].entries()) {
422
+ const current = [i + 1];
423
+ for (const [j, right] of [...b].entries())
424
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
425
+ previous = current;
426
+ }
427
+ return previous[b.length] ?? 0;
428
+ }
429
+ function closest(name, names) {
430
+ const started = names.find((known) => known.startsWith(name));
431
+ if (started !== undefined)
432
+ return started;
433
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
434
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
435
+ }
436
+ // ../kit/src/input.ts
437
+ import { fstatSync } from "fs";
438
+ var WHOLE = /^\d+$/;
439
+ function wholeNumber(value, name, fallback, min = 1) {
440
+ if (value === undefined)
441
+ return fallback;
442
+ const number = Number(value);
443
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
444
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
445
+ return number;
446
+ }
447
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
448
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
449
+ function duration(value, name, fallback, unit = "s") {
450
+ if (value === undefined)
451
+ return fallback;
452
+ const match = DURATION.exec(value.trim());
453
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
454
+ if (ms < 1)
455
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
456
+ return ms;
457
+ }
458
+ function isStdinPiped() {
459
+ const stat = fstatSync(0);
460
+ return stat.isFIFO() || stat.isFile();
461
+ }
462
+
463
+ // ../kit/src/args.ts
464
+ var DASHES = /^-+/;
465
+ function jsonOption(holds) {
466
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
467
+ }
468
+
469
+ class Exit extends Error {
470
+ code;
471
+ hint;
472
+ constructor(message, code, hint) {
473
+ super(message);
474
+ this.code = code;
475
+ this.hint = hint;
476
+ }
477
+ }
478
+ function fail(message, code = 2, hint) {
479
+ throw new Exit(message, code, hint);
480
+ }
481
+
482
+ class UsageError extends Exit {
483
+ constructor(message, hint) {
484
+ super(message, 2, hint);
485
+ }
486
+ }
487
+ function badUsage(message) {
488
+ throw new UsageError(message);
489
+ }
490
+
491
+ class HelpShown extends Exit {
492
+ constructor() {
493
+ super("help shown", 0);
494
+ }
495
+ }
496
+
497
+ class Completing {
498
+ options;
499
+ positionals;
500
+ candidates;
501
+ constructor(options, positionals = [], candidates = {}) {
502
+ this.options = options;
503
+ this.positionals = positionals;
504
+ this.candidates = candidates;
505
+ }
506
+ }
507
+ var completion = { active: false };
508
+ var OUTPUT_OPTIONS = {
509
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
510
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
511
+ };
512
+ function applyOutput(color, plain, env = process5.env) {
513
+ const when = plain === true ? "never" : color ?? "auto";
514
+ if (when === "auto")
515
+ return;
516
+ if (when !== "always" && when !== "never")
517
+ badUsage(`--color takes auto, always or never, not ${when}`);
518
+ if (when === "always") {
519
+ env.FORCE_COLOR = "1";
520
+ delete env.NO_COLOR;
521
+ } else {
522
+ env.NO_COLOR = "1";
523
+ delete env.FORCE_COLOR;
524
+ }
525
+ }
526
+ function parse(args, usage, options, settings = {}) {
527
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
528
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
529
+ const listing = listed(all, settings.allowNegative === true);
530
+ if (completion.active)
531
+ throw new Completing(listing, settings.positionals, settings.candidates);
532
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
533
+ let parsed;
534
+ try {
535
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
536
+ } catch (error) {
537
+ const message = parseError(error);
538
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
539
+ }
540
+ const values = parsed.values;
541
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
542
+ if (values.help === true) {
543
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
544
+ throw new HelpShown;
545
+ }
546
+ checkChoices(parsed.values, all);
547
+ checkConflicts(parsed.values, all);
548
+ if (settings.positionals !== undefined)
549
+ checkPositionals(parsed.positionals, settings.positionals);
550
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
551
+ }
552
+ function splitRest(args, passes) {
553
+ const separator = passes ? args.indexOf("--") : -1;
554
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
555
+ }
556
+ function splitTrailing(args, options, count) {
557
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
558
+ let seen = 0;
559
+ if (count === 0)
560
+ return { own: args, rest: undefined };
561
+ for (let at = 0;at < args.length; at++) {
562
+ const word = args[at];
563
+ if (word === "--")
564
+ break;
565
+ if (word.startsWith("-")) {
566
+ if (takesValue(word))
567
+ at++;
568
+ continue;
569
+ }
570
+ seen++;
571
+ if (seen === count)
572
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
573
+ }
574
+ return { own: args, rest: undefined };
575
+ }
576
+ function listed(options, allowNegative) {
577
+ if (!allowNegative)
578
+ return options;
579
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
580
+ if (option.type !== "boolean" || option.negative === undefined)
581
+ return [[name, option]];
582
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
583
+ }));
584
+ }
585
+ function withAliases(args, options) {
586
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
587
+ if (named.size === 0)
588
+ return args;
589
+ const separator = args.indexOf("--");
590
+ const own = separator === -1 ? args : args.slice(0, separator);
591
+ return [...own.map((arg) => {
592
+ const at = arg.indexOf("=");
593
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
594
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
595
+ }), ...separator === -1 ? [] : args.slice(separator)];
596
+ }
597
+ function withBare(args, options) {
598
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
599
+ if (bare.size === 0)
600
+ return args;
601
+ const separator = args.indexOf("--");
602
+ const own = separator === -1 ? args : args.slice(0, separator);
603
+ return [...own.flatMap((arg, index) => {
604
+ const optional = bare.get(arg);
605
+ const next = own[index + 1];
606
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
607
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
608
+ }), ...separator === -1 ? [] : args.slice(separator)];
609
+ }
610
+ function checkConflicts(values, options) {
611
+ const given = (name) => values[name] !== undefined && values[name] !== false;
612
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
613
+ const other = given(name) ? conflicts.find(given) : undefined;
614
+ if (other !== undefined)
615
+ badUsage(`--${name} cannot be used with --${other}`);
616
+ }
617
+ }
618
+ function checkChoices(values, options) {
619
+ for (const [name, option] of Object.entries(options)) {
620
+ if (option.choices === undefined)
621
+ continue;
622
+ const given = values[name];
623
+ for (const value of Array.isArray(given) ? given : [given]) {
624
+ if (typeof value === "string")
625
+ oneOf(value, name, option.choices);
626
+ }
627
+ }
628
+ }
629
+ function oneOf(value, name, choices) {
630
+ if (!choices.includes(value))
631
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
632
+ return value;
633
+ }
634
+ function checkPositionals(given, names) {
635
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
636
+ const required = names.filter((name) => !name.startsWith("[")).length;
637
+ if (given.length < required)
638
+ badUsage(`missing ${names[given.length]}`);
639
+ if (!variadic && given.length > names.length)
640
+ badUsage(`unexpected argument ${given[names.length]}`);
641
+ }
642
+ function joinDashValues(args, options) {
643
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
644
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
645
+ const joined = [];
646
+ for (let i = 0;i < args.length; i++) {
647
+ const arg = args[i] ?? "";
648
+ if (arg === "--")
649
+ return [...joined, ...args.slice(i)];
650
+ const name = longOf.get(arg);
651
+ const next = args[i + 1];
652
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
653
+ joined.push(`--${name}=${next}`);
654
+ i++;
655
+ } else {
656
+ joined.push(arg);
657
+ }
658
+ }
659
+ return joined;
660
+ }
661
+ function parseError(error) {
662
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
663
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
664
+ }
665
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
666
+ function nearestOption(message, options, allowNegative) {
667
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
668
+ if (typed === undefined)
669
+ return;
670
+ const word = typed.replace(DASHES, "");
671
+ if (word.length < 2 && !typed.startsWith("--"))
672
+ return;
673
+ const known = Object.entries(options).flatMap(([name, option]) => [
674
+ ...option.short === undefined ? [] : [`-${option.short}`],
675
+ `--${name}`,
676
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
677
+ ]);
678
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
679
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
680
+ }
681
+ // ../kit/src/process.ts
682
+ import { constants } from "os";
683
+ import process6 from "process";
684
+ var KILL_GRACE_MS = 2000;
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
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
693
+ const chunks = [];
694
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
695
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
696
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
697
+ const timers = [];
698
+ const killGroup = (killing) => {
699
+ if (state.done)
700
+ return;
701
+ try {
702
+ if (grouped)
703
+ process6.kill(-proc.pid, killing);
704
+ else
705
+ proc.kill(killing);
706
+ } catch {}
707
+ };
708
+ const stop = () => {
709
+ killGroup("SIGTERM");
710
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
711
+ };
712
+ const onAbort = () => stop();
713
+ if (timeoutMs !== undefined) {
714
+ timers.push(setTimeout(() => {
715
+ state.timedOut = true;
716
+ stop();
717
+ }, timeoutMs));
718
+ }
719
+ if (signal?.aborted === true)
720
+ onAbort();
721
+ else
722
+ signal?.addEventListener("abort", onAbort, { once: true });
723
+ onStart?.({ kill: (killing) => killGroup(killing) });
724
+ const drain = async (stream, name) => {
725
+ for await (const data of stream) {
726
+ if (state.failure !== undefined)
727
+ continue;
728
+ try {
729
+ onChunk?.({ stream: name, data });
730
+ } catch (error) {
731
+ state.failure = error;
732
+ stop();
733
+ continue;
734
+ }
735
+ if (state.kept + data.length > maxBytes) {
736
+ state.truncated = true;
737
+ continue;
738
+ }
739
+ state.kept += data.length;
740
+ chunks.push({ stream: name, data });
741
+ }
742
+ };
743
+ try {
744
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
745
+ await proc.exited;
746
+ } finally {
747
+ state.done = true;
748
+ for (const timer of timers)
749
+ clearTimeout(timer);
750
+ signal?.removeEventListener("abort", onAbort);
751
+ }
752
+ if (state.failure !== undefined)
753
+ throw state.failure;
754
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
755
+ let output;
756
+ let text;
757
+ return {
758
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
759
+ chunks,
760
+ timedOut: state.timedOut,
761
+ truncated: state.truncated,
762
+ get output() {
763
+ return output ??= joined();
764
+ },
765
+ get text() {
766
+ return text ??= (output ??= joined()).toString();
767
+ }
768
+ };
769
+ }
770
+
771
+ // ../kit/src/progress.ts
772
+ var ESC = String.fromCharCode(27);
773
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
774
+ var RESET_STYLE = `${ESC}[0m`;
775
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
776
+ // ../kit/src/cli.ts
777
+ import { readFileSync, realpathSync } from "fs";
778
+ import { dirname as dirname2, join as join2 } from "path";
779
+ import process8 from "process";
780
+
781
+ // ../kit/src/usage.ts
782
+ import { appendFileSync, mkdirSync } from "fs";
783
+ import { homedir } from "os";
784
+ import { dirname, isAbsolute, join } from "path";
785
+ import process7 from "process";
786
+
787
+ // ../kit/src/logs.ts
788
+ var DAY_MS = 24 * 60 * 60 * 1000;
789
+ var CLI_FOLDER = "kaynooo-cli";
790
+
791
+ // ../kit/src/usage.ts
792
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
793
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
794
+ var LONGEST_NAME = 40;
795
+ var usageError;
796
+ function noteUsageError(message) {
797
+ usageError = message;
798
+ }
799
+ function stateHome(env = process7.env) {
800
+ const dir = env.XDG_STATE_HOME;
801
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
802
+ }
803
+ function usagePath(env = process7.env) {
804
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
805
+ }
806
+ function usageRecorded(env = process7.env) {
807
+ const off = env.KAYNOOO_CLI_NO_USAGE;
808
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
809
+ }
810
+ function flagNames(argv) {
811
+ const end = argv.indexOf("--");
812
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
813
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
814
+ }
815
+ function usageEntry(bin, command, argv, code, now = new Date) {
816
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
817
+ usageError = undefined;
818
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
819
+ }
820
+ function recordUsage(entry, env = process7.env) {
821
+ if (!usageRecorded(env))
822
+ return;
823
+ try {
824
+ const path = usagePath(env);
825
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
826
+ appendFileSync(path, `${JSON.stringify(entry)}
827
+ `, { mode: 384 });
828
+ } catch {}
829
+ }
830
+
831
+ // ../kit/src/cli.ts
832
+ var LEVEL_OPTIONS = {
833
+ ...OUTPUT_OPTIONS,
834
+ help: { type: "boolean", short: "h", description: "show this help" }
835
+ };
836
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
837
+ async function commandRows(all, colors) {
838
+ const commands = shown(all);
839
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
840
+ const groups = new Map([["Commands:", []]]);
841
+ const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
842
+ for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
843
+ const heading = group === undefined ? "Commands:" : `${group}:`;
844
+ const rows = groups.get(heading) ?? [];
845
+ rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
846
+ groups.set(heading, rows);
847
+ }
848
+ return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
849
+ }
850
+ function shown(commands) {
851
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
852
+ }
853
+ function takeOutputFlags(argv) {
854
+ let index = 0;
855
+ for (;index < argv.length; index++) {
856
+ const word = argv[index];
857
+ if (word === "--plain")
858
+ applyOutput(undefined, true);
859
+ else if (word.startsWith("--color="))
860
+ applyOutput(word.slice("--color=".length), undefined);
861
+ else if (word === "--color" && argv[index + 1] !== undefined)
862
+ applyOutput(argv[++index], undefined);
863
+ else
864
+ break;
865
+ }
866
+ return argv.slice(index);
867
+ }
868
+ async function resolveSummary(summary) {
869
+ return typeof summary === "string" ? summary : summary();
870
+ }
871
+ function scopeOf(commands, extra, aliases) {
872
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
873
+ }
874
+ async function expand(scope, words) {
875
+ if (scope.lazy.length === 0)
876
+ return scope;
877
+ const commands = { ...scope.commands };
878
+ for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
879
+ for (const [name, command] of Object.entries(added))
880
+ commands[name] ??= command;
881
+ }
882
+ return { ...scope, commands, lazy: [] };
883
+ }
884
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
885
+ const colors = paint(stream);
886
+ const prefix = path.join(" ");
887
+ const summary = await resolveSummary(lazySummary);
888
+ if (wantsHelpJson())
889
+ return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
890
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
891
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
892
+ const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
893
+ return [
894
+ header(colors, summary),
895
+ "",
896
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
897
+ ...replacesRows(replaces, colors),
898
+ "",
899
+ ...await commandRows(commands, colors),
900
+ ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
901
+ "",
902
+ colors.bold("Options:"),
903
+ ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
904
+ ...exampleRows(examples ?? [], colors),
905
+ "",
906
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
907
+ ].join(`
908
+ `);
909
+ }
910
+ function printError(prefix, message, hint, cause) {
911
+ const colors = paint(process8.stderr);
912
+ const styled = takesControlCodes(process8.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 Exit && error.code === 2)
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
+ async function dispatch(level, typed, { version, redact }) {
938
+ const prefix = level.path.join(" ");
939
+ let argv;
940
+ try {
941
+ argv = takeOutputFlags(typed);
942
+ } catch (error) {
943
+ return reportThrown(prefix, error);
944
+ }
945
+ const [name, ...args] = argv;
946
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
947
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
948
+ try {
949
+ return await fallback.run([]);
950
+ } catch (error) {
951
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
952
+ }
953
+ }
954
+ if (name === undefined && level.path.length > 1) {
955
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
956
+ return 2;
957
+ }
958
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
959
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
960
+ return 0;
961
+ }
962
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
963
+ console.log(version);
964
+ return 0;
965
+ }
966
+ let command = level.commands[level.aliases?.[name] ?? name];
967
+ let rest = args;
968
+ let ran = name;
969
+ if (command === undefined && level.lazy.length > 0) {
970
+ level = await expand(level, [...level.path.slice(1), ...argv]);
971
+ command = level.commands[level.aliases?.[name] ?? name];
972
+ }
973
+ if (command === undefined && level.defaultCommand !== undefined) {
974
+ command = level.commands[level.defaultCommand];
975
+ rest = argv;
976
+ ran = level.defaultCommand;
977
+ }
978
+ if (command === undefined) {
979
+ const meant = closest(name, Object.keys(shown(level.commands)));
980
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
981
+ return 2;
982
+ }
983
+ if ("commands" in command) {
984
+ const { summary } = command;
985
+ return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
986
+ }
987
+ try {
988
+ return await command.run(rest);
989
+ } catch (error) {
990
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
991
+ }
992
+ }
993
+ var COMPLETE = "__complete";
994
+ var FILES = "__files__";
995
+ async function completingOf(run) {
996
+ completion.active = true;
997
+ try {
998
+ await run([]);
999
+ } catch (error) {
1000
+ if (error instanceof Completing)
1001
+ return error;
1002
+ } finally {
1003
+ completion.active = false;
1004
+ }
1005
+ return new Completing({});
1006
+ }
1007
+ async function optionsOf(run) {
1008
+ return (await completingOf(run)).options;
1009
+ }
1010
+ function candidateLine(candidate) {
1011
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
1012
+ }
1013
+ function positionalBeingTyped(before, { options, positionals }) {
1014
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1015
+ let index = 0;
1016
+ let at = 0;
1017
+ while (at < before.length) {
1018
+ const word = before[at];
1019
+ if (word === "--") {
1020
+ index += before.length - at - 1;
1021
+ break;
1022
+ }
1023
+ if (!word.startsWith("-"))
1024
+ index++;
1025
+ else if (takesValue(word))
1026
+ at++;
1027
+ at++;
1028
+ }
1029
+ const last = positionals.at(-1);
1030
+ if (index < positionals.length)
1031
+ return positionals[index];
1032
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1033
+ }
1034
+ async function leafCandidates(run, words) {
1035
+ const completing = await completingOf(run);
1036
+ if ((words.at(-1) ?? "").startsWith("-"))
1037
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1038
+ const flag = words.at(-2);
1039
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1040
+ if (option?.type === "string") {
1041
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1042
+ return values === undefined ? [FILES] : values.map(candidateLine);
1043
+ }
1044
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
1045
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
1046
+ return values === undefined ? [FILES] : values.map(candidateLine);
1047
+ }
1048
+ async function candidates(scope, defaultCommand, words, before = []) {
1049
+ const [word = "", ...rest] = words;
1050
+ const listing = rest.length === 0 && !word.startsWith("-");
1051
+ let { commands, aliases } = scope;
1052
+ let command = commands[aliases?.[word] ?? word];
1053
+ if (listing || command === undefined) {
1054
+ ({ commands, aliases } = await expand(scope, [...before, ...words]));
1055
+ command = commands[aliases?.[word] ?? word];
1056
+ }
1057
+ if (listing) {
1058
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1059
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1060
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1061
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1062
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
1063
+ }
1064
+ if (command === undefined) {
1065
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1066
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
1067
+ }
1068
+ return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1069
+ }
1070
+ async function printCandidates(found) {
1071
+ for (const line of await found)
1072
+ console.log(line);
1073
+ return 0;
1074
+ }
1075
+ function packageVersion(entry = Bun.main) {
1076
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1077
+ try {
1078
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
1079
+ if (typeof version === "string")
1080
+ return version;
1081
+ } catch {}
1082
+ if (dirname2(dir) === dir)
1083
+ return "0.0.0";
1084
+ }
1085
+ }
1086
+ async function runCli(cli, argv = process8.argv.slice(2)) {
1087
+ const version = cli.version ?? packageVersion();
1088
+ if (argv[0] === COMPLETE)
1089
+ return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1090
+ const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1091
+ if (cli.usage !== false) {
1092
+ try {
1093
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1094
+ } catch {}
1095
+ }
1096
+ return code;
1097
+ }
1098
+ function commandPath(scope, argv) {
1099
+ const path = [];
1100
+ let level = scope;
1101
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
1102
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1103
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1104
+ if (command === undefined)
1105
+ break;
1106
+ path.push(word);
1107
+ if (!("commands" in command))
1108
+ break;
1109
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
1110
+ }
1111
+ return path.length === 0 ? undefined : path.join(" ");
1112
+ }
1113
+ async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
1114
+ if (argv[0] === COMPLETE)
1115
+ return printCandidates(leafCandidates(run, argv.slice(1)));
1116
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1117
+ console.log(version ?? packageVersion());
1118
+ return 0;
1119
+ }
1120
+ let code;
1121
+ try {
1122
+ code = await run(argv);
1123
+ } catch (error) {
1124
+ code = reportThrown(name, error, redact, wantsJson(argv));
1125
+ }
1126
+ if (usage !== false) {
1127
+ try {
1128
+ recordUsage(usageEntry(name, undefined, argv, code));
1129
+ } catch {}
1130
+ }
1131
+ return code;
1132
+ }
1133
+ // ../kit/src/limit.ts
1134
+ function limitOptions(fallback) {
1135
+ return {
1136
+ limit: { type: "string", short: "n", description: `show at most this many rows, the rest counted (${fallback})` },
1137
+ full: { type: "boolean", description: "show every row" }
1138
+ };
1139
+ }
1140
+ function limitOf(values, fallback) {
1141
+ if (values.full === true && values.limit !== undefined)
1142
+ badUsage("--limit and --full exclude each other");
1143
+ if (values.full === true || values.json === true && values.limit === undefined)
1144
+ return Number.POSITIVE_INFINITY;
1145
+ return wholeNumber(values.limit, "limit", fallback);
1146
+ }
1147
+ function moreFooter(more) {
1148
+ return `${more} more, rerun with --full`;
1149
+ }
1150
+ function capped(rows, limit) {
1151
+ const more = rows.length - limit;
1152
+ return more > 0 ? { shown: rows.slice(0, limit), footer: moreFooter(more) } : { shown: [...rows], footer: undefined };
1153
+ }
1154
+ // ../kit/src/secrets.ts
1155
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1156
+ // ../kit/src/sessions.ts
1157
+ var {Glob } = globalThis.Bun;
1158
+ var SESSION_FILES = new Glob("*.json");
1159
+ var ACCOUNT_DIRS = new Glob("*/sessions");
1160
+ // src/hotspots.ts
1161
+ import { join as join4 } from "path";
1162
+ import process10 from "process";
1163
+
1164
+ // src/churn.ts
1165
+ var SOURCE = /\.(?:[cm]?[jt]sx?|vue|svelte|astro|kay|py|go|rs|rb|php|java|kt|swift|cs|c|cc|cpp|h|hpp|scala|dart|lua|sh|zsh|fish)$/;
1166
+ var TESTS = /(?:^|\/)(?:tests?|__tests__|spec|e2e|__mocks__|fixtures)\/|\.(?:test|spec|bench)\.[^/]+$|(?:^|\/)test_[^/]+$|_test\.(?:go|py)$/;
1167
+ var GENERATED = /(?:^|\/)(?:dist|build|out|generated|\.nuxt|\.output|\.next)\/|\.min\.[cm]?js$|\.d\.ts$|\.(?:generated|gen)\.[^/]+$|\.pb\.go$|\.snap$/;
1168
+ var LEADING_NEWLINE = /^\n/;
1169
+ var GENERATED_HEADER = /@generated|generated by|do not edit/i;
1170
+ var DECISION = /\b(?:if|elif|elsif|for|foreach|while|until|case|when|catch|except|rescue|match|guard|and|or)\b|&&|\|\||\?\?|\?(?=[^.?:])/g;
1171
+ var COMMENT = /\/\*[\s\S]*?\*\/|\/\/[^\n]*|^[ \t]*#[^\n]*/gm;
1172
+ var STRING = /'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`/g;
1173
+ function isCandidate(path) {
1174
+ return SOURCE.test(path) && !TESTS.test(path) && !GENERATED.test(path);
1175
+ }
1176
+ function isGenerated(text) {
1177
+ return GENERATED_HEADER.test(text.slice(0, 400));
1178
+ }
1179
+ function complexityOf(text) {
1180
+ return 1 + (text.replace(COMMENT, "").replace(STRING, '""').match(DECISION)?.length ?? 0);
1181
+ }
1182
+ async function churnSince(cwd, since, { bulk, halfLifeMs, now = Date.now() }) {
1183
+ const log = await runCommand(["git", "log", `--since=${since}`, "--no-renames", "--relative", "--name-only", "--format=%x01%ct", "-z"], { cwd });
1184
+ if (log.code !== 0)
1185
+ return;
1186
+ const churn = new Map;
1187
+ for (const commit of log.text.split("\x01").slice(1)) {
1188
+ const [stamp = "", ...names] = commit.split("\x00");
1189
+ const paths = names.map((name) => name.replace(LEADING_NEWLINE, "")).filter((name) => name !== "");
1190
+ if (paths.length > bulk)
1191
+ continue;
1192
+ const age = Math.max(0, now - Number(stamp) * 1000);
1193
+ const weight = halfLifeMs === 0 ? 1 : 0.5 ** (age / halfLifeMs);
1194
+ for (const path of paths) {
1195
+ const seen = churn.get(path) ?? { commits: 0, weight: 0 };
1196
+ churn.set(path, { commits: seen.commits + 1, weight: seen.weight + weight });
1197
+ }
1198
+ }
1199
+ return churn;
1200
+ }
1201
+
1202
+ // src/files.ts
1203
+ import { existsSync, readdirSync, statSync } from "fs";
1204
+ import { join as join3, relative } from "path";
1205
+ var MAX_BYTES = 2000000;
1206
+ var SNIFF_BYTES = 8000;
1207
+ var SKIPPED = new Set(["node_modules", "dist", "build", "vendor", "target", "coverage"]);
1208
+ function walk(dir, found) {
1209
+ let entries;
1210
+ try {
1211
+ entries = readdirSync(dir, { withFileTypes: true });
1212
+ } catch {
1213
+ return found;
1214
+ }
1215
+ for (const entry of entries) {
1216
+ if (entry.name.startsWith(".") || SKIPPED.has(entry.name))
1217
+ continue;
1218
+ if (entry.isDirectory())
1219
+ walk(join3(dir, entry.name), found);
1220
+ else if (entry.isFile())
1221
+ found.push(join3(dir, entry.name));
1222
+ }
1223
+ return found;
1224
+ }
1225
+ async function listFiles(paths, cwd) {
1226
+ const listed = await runCommand(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...paths], { cwd });
1227
+ if (listed.code === 0)
1228
+ return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync(join3(cwd, path))).sort();
1229
+ const roots = paths.length === 0 ? [cwd] : paths.map((path) => join3(cwd, path));
1230
+ return roots.flatMap((root) => statSync(root, { throwIfNoEntry: false })?.isFile() === true ? [root] : walk(root, [])).map((path) => relative(cwd, path)).sort();
1231
+ }
1232
+ async function readText(path) {
1233
+ const file = Bun.file(path);
1234
+ try {
1235
+ if (file.size > MAX_BYTES || (await file.slice(0, SNIFF_BYTES).bytes()).includes(0))
1236
+ return;
1237
+ return await file.text();
1238
+ } catch {
1239
+ return;
1240
+ }
1241
+ }
1242
+
1243
+ // src/units.ts
1244
+ var CONTAINER = /^(?:(?:export|default|declare|abstract|final|readonly|public|pub|private|protected|internal|sealed|data|open)\s+)*(?:class|impl|trait|interface|namespace|module|object|mod|struct|enum)\b/;
1245
+ var CLOSER = /^[\s)\]};]*$|^\s*(?:\/\/|\/\*|\*|#)/;
1246
+ var LONGEST_NAME2 = 60;
1247
+ var MARKUP_BLOCK = /^<(template|style)\b[\s\S]*?\n<\/\1>/gm;
1248
+ var KAY_FILE = /^---\n([\s\S]*?\n)---(?:\n|$)([\s\S]*)$/;
1249
+ function blanked(text) {
1250
+ return `
1251
+ `.repeat(text.split(`
1252
+ `).length - 1);
1253
+ }
1254
+ function indentOf(line) {
1255
+ return line.length - line.trimStart().length;
1256
+ }
1257
+ function opens(line, indent) {
1258
+ return line.trim() !== "" && line.trim() !== "{" && indentOf(line) === indent && !CLOSER.test(line);
1259
+ }
1260
+ function unitsAt(lines, from, to, indent) {
1261
+ const starts = [];
1262
+ for (let at = from;at < to; at++) {
1263
+ if (opens(lines[at], indent))
1264
+ starts.push(at);
1265
+ }
1266
+ return starts.flatMap((start, index) => {
1267
+ const end = starts[index + 1] ?? to;
1268
+ const header = lines[start].trim();
1269
+ if (CONTAINER.test(header)) {
1270
+ const inner = lines.slice(start + 1, end).filter((line) => line.trim() !== "").map(indentOf).filter((each) => each > indent);
1271
+ const next = inner.length === 0 ? undefined : Math.min(...inner);
1272
+ if (next !== undefined) {
1273
+ const members = unitsAt(lines, start + 1, end, next);
1274
+ if (members.length > 0)
1275
+ return members;
1276
+ }
1277
+ }
1278
+ return [{ name: header.length > LONGEST_NAME2 ? `${header.slice(0, LONGEST_NAME2 - 1)}\u2026` : header, line: start + 1, complexity: complexityOf(lines.slice(start, end).join(`
1279
+ `)) }];
1280
+ });
1281
+ }
1282
+ function worstUnit(text, path = "") {
1283
+ const code = path.endsWith(".kay") ? text.replace(KAY_FILE, (_, script, template) => `
1284
+ ${script}
1285
+ ${blanked(template)}`) : text.replace(MARKUP_BLOCK, blanked);
1286
+ const lines = code.split(`
1287
+ `);
1288
+ const top = unitsAt(lines, 0, lines.length, 0);
1289
+ return top.reduce((worst, unit) => worst === undefined || unit.complexity > worst.complexity ? unit : worst, undefined);
1290
+ }
1291
+
1292
+ // src/hotspots.ts
1293
+ var DEFAULT_SINCE = "6 months ago";
1294
+ var DEFAULT_BULK = 25;
1295
+ var DAY_MS2 = 86400000;
1296
+ var DEFAULT_HALF_LIFE = "90d";
1297
+ var DEFAULT_COUNT = 20;
1298
+ var USAGE = `hotspots [options] [dir]: ranks the source files under dir (here by default) by complexity times churn, the ones both hard to read and often edited first, honouring .gitignore
1299
+
1300
+ Complexity is the count of decision points in the file (branches, loops, cases, catches, boolean operators, ternaries) plus one, churn the commits touching it since --since (${DEFAULT_SINCE}), score their product. A commit counts for less the older it is (half as much every --half-life, 0 for all alike) and a commit touching more than --bulk files, a format or rename sweep, is left out. Each file also shows its most complex declaration, found by indentation. Test files and generated or built files are left out unless --all.
1301
+
1302
+ Lists at most ${DEFAULT_COUNT} files, the count of the rest after them (--limit <n>, --full for all); --json is never cut unless --limit is given.
1303
+
1304
+ Exits 0 when it ranked the files, 1 when no file has commits in the window, 2 on a usage error or outside a git repository.`;
1305
+ var OPTIONS = {
1306
+ since: { type: "string", short: "s", description: `only count the commits since this date, as git reads it (${DEFAULT_SINCE})` },
1307
+ "half-life": { type: "string", description: `how long until a commit counts half as much (${DEFAULT_HALF_LIFE}), 0 for no decay` },
1308
+ bulk: { type: "string", description: `leave out the commits touching more files than this (${DEFAULT_BULK})` },
1309
+ ...limitOptions(DEFAULT_COUNT),
1310
+ all: { type: "boolean", short: "a", description: "keep test files and generated files" },
1311
+ json: jsonOption("[{rank, path, score, churn, recent, complexity, worst, lines}], never cut unless --limit is given")
1312
+ };
1313
+ async function hotspots(args) {
1314
+ const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["[dir]"], replaces: "guessing which files are worth splitting first", examples: ["hotspots", 'hotspots src --since "3 months ago" --limit 10'] });
1315
+ if (positionals.length > 1)
1316
+ badUsage("give one folder");
1317
+ const count = limitOf(values, DEFAULT_COUNT);
1318
+ const cwd = process10.cwd();
1319
+ const bulk = Number(values.bulk ?? DEFAULT_BULK);
1320
+ if (!Number.isInteger(bulk) || bulk < 1)
1321
+ badUsage(`--bulk takes a number of files, not ${values.bulk}`);
1322
+ const halfLifeMs = values["half-life"] === "0" ? 0 : duration(values["half-life"], "half-life", 90 * DAY_MS2);
1323
+ const churn = await churnSince(cwd, values.since ?? DEFAULT_SINCE, { bulk, halfLifeMs });
1324
+ if (churn === undefined)
1325
+ fail("not a git repository, churn comes from its log");
1326
+ const ranked = [];
1327
+ for (const path of await listFiles(positionals[0] === undefined ? [] : [positionals[0]], cwd)) {
1328
+ const touched = churn.get(path);
1329
+ if (touched === undefined || values.all !== true && !isCandidate(path))
1330
+ continue;
1331
+ const text = await readText(join4(cwd, path));
1332
+ if (text === undefined || values.all !== true && isGenerated(text))
1333
+ continue;
1334
+ const complexity = complexityOf(text);
1335
+ const worst = worstUnit(text, path);
1336
+ ranked.push({ path, score: Math.round(complexity * touched.weight), churn: touched.commits, recent: Math.round(touched.weight * 10) / 10, complexity, worst: worst === undefined ? undefined : { name: worst.name, line: worst.line, complexity: worst.complexity }, lines: text.split(`
1337
+ `).length - (text.endsWith(`
1338
+ `) ? 1 : 0) });
1339
+ }
1340
+ if (ranked.length === 0)
1341
+ fail("no file with commits in that window", 1);
1342
+ ranked.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
1343
+ const { shown: kept, footer } = capped(ranked, count);
1344
+ const shown = kept.map((hotspot, index) => ({ rank: index + 1, ...hotspot }));
1345
+ if (values.json === true) {
1346
+ printJson(shown);
1347
+ return 0;
1348
+ }
1349
+ console.log(table([["rank", "score", "churn", "recent", "complexity", "lines", "file", "most complex declaration"], ...shown.map((row) => [row.rank, row.score, row.churn, row.recent, row.complexity, row.lines, row.path, row.worst === undefined ? "" : `${row.worst.name} (${row.worst.complexity}, line ${row.worst.line})`].map(String))], { header: true, align: ["right", "right", "right", "right", "right", "right", "left", "left"] }));
1350
+ if (footer !== undefined)
1351
+ console.log(footer);
1352
+ return 0;
1353
+ }
1354
+
1355
+ // src/peek.ts
1356
+ import { realpathSync as realpathSync2 } from "fs";
1357
+ import { isAbsolute as isAbsolute2, join as join5, relative as relative2, resolve, sep } from "path";
1358
+ import process11 from "process";
1359
+
1360
+ // src/source.ts
1361
+ var LOCATION = /^(?:\.\/)?([^\s:()]+)(?::(\d+)(?::\d+)?|\((\d+),\d+\))(?=[:\s)]|$)/;
1362
+ var DECLARATION = /^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?(?:function\*?|class|interface|type|enum|const|let|var|namespace|module|def|func|fn|struct|trait|impl)\s/;
1363
+ var MODIFIERS = /^(?:(?:public|private|protected|static|async|override|readonly|abstract|get|set|pub|fn|def|func)\s+)*/;
1364
+ var MEMBER = /^(?:(?:public|private|protected|static|async|override|readonly|abstract|get|set|pub|fn|def|func)\s+)*[#\w$]+\s*(?:<[^>]*>\s*)?\(/;
1365
+ var RECEIVER = /^(?:\([^)]*\)\s*)?/;
1366
+ var STAR = /^\*?\s*/;
1367
+ var HOLDS_MEMBERS = /\b(?:class|interface|trait|impl|struct)\s/;
1368
+ var CALL_KEYWORDS = /^(?:if|for|while|switch|catch|return|await|throw|new|else|do|try|super|typeof)\b/;
1369
+ var LEADING = /^(?:\/\/|\/\*|\*|#(?!!)|@)/;
1370
+ var LOCAL_BINDING = /^(?:const|let|var)\s/;
1371
+ var HEADING = /^#{1,6}\s/;
1372
+ var TRAILING_NEWLINE = /\n$/;
1373
+ var MARKDOWN = /\.(?:md|mdx|markdown)$/i;
1374
+ var INDENTED = /\.(?:py|yml|yaml)$/i;
1375
+ var INDENT = /^\s*/;
1376
+ var CONTINUES = /(?:[=(,[{:?|&+\-*/<>]|=>)$/;
1377
+ var BODY_OPENER = /\s*\{\s*$/;
1378
+ var LONGEST_DEFINITION = 400;
1379
+ var LONGEST_SIGNATURE = 160;
1380
+ function indentOf2(line) {
1381
+ return INDENT.exec(line)?.[0].length ?? 0;
1382
+ }
1383
+ function escaped(name) {
1384
+ return name.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
1385
+ }
1386
+ function declares(line, name) {
1387
+ const text = line.trim();
1388
+ const word = new RegExp(String.raw`^${escaped(name)}\b`);
1389
+ if (DECLARATION.test(text)) {
1390
+ const rest = text.replace(DECLARATION, "").replace(RECEIVER, "");
1391
+ return word.test(rest.replace(STAR, ""));
1392
+ }
1393
+ return line !== text && MEMBER.test(text) && !CALL_KEYWORDS.test(text) && word.test(text.replace(MODIFIERS, "")) && (text.endsWith("{") || text.endsWith(":"));
1394
+ }
1395
+ function depthChange(line, quote) {
1396
+ let braces = 0;
1397
+ let parens = 0;
1398
+ for (let i = 0;i < line.length; i++) {
1399
+ const char = line[i] ?? "";
1400
+ if (quote.open !== "") {
1401
+ if (char === "\\")
1402
+ i++;
1403
+ else if (char === quote.open)
1404
+ quote.open = "";
1405
+ continue;
1406
+ }
1407
+ if (char === "/" && line[i + 1] === "/")
1408
+ break;
1409
+ if (char === '"' || char === "'" || char === "`")
1410
+ quote.open = char;
1411
+ else if (char === "{")
1412
+ braces++;
1413
+ else if (char === "}")
1414
+ braces--;
1415
+ else if (char === "(" || char === "[")
1416
+ parens++;
1417
+ else if (char === ")" || char === "]")
1418
+ parens--;
1419
+ }
1420
+ if (quote.open !== "`")
1421
+ quote.open = "";
1422
+ return { braces, parens };
1423
+ }
1424
+ function endOf(lines, start, path) {
1425
+ const last = Math.min(lines.length - 1, start + LONGEST_DEFINITION - 1);
1426
+ if (INDENTED.test(path)) {
1427
+ const indent = indentOf2(lines[start] ?? "");
1428
+ let end = start;
1429
+ for (let i = start + 1;i <= last; i++) {
1430
+ const line = lines[i] ?? "";
1431
+ if (line.trim() !== "" && indentOf2(line) <= indent)
1432
+ break;
1433
+ if (line.trim() !== "")
1434
+ end = i;
1435
+ }
1436
+ return end;
1437
+ }
1438
+ const quote = { open: "" };
1439
+ let braces = 0;
1440
+ let parens = 0;
1441
+ let opened = false;
1442
+ for (let i = start;i <= last; i++) {
1443
+ const line = lines[i] ?? "";
1444
+ const change = depthChange(line, quote);
1445
+ opened ||= change.braces > 0 || line.includes("{");
1446
+ braces += change.braces;
1447
+ parens += change.parens;
1448
+ if (braces <= 0 && parens <= 0 && quote.open === "" && (opened || !CONTINUES.test(line.trimEnd())))
1449
+ return i;
1450
+ }
1451
+ return last;
1452
+ }
1453
+ function leadingStart(lines, start) {
1454
+ let first = start;
1455
+ while (first > 0 && LEADING.test((lines[first - 1] ?? "").trim()))
1456
+ first--;
1457
+ return first;
1458
+ }
1459
+ function definitions(text, path, name) {
1460
+ const lines = text.split(`
1461
+ `);
1462
+ const spans = [];
1463
+ for (let i = 0;i < lines.length; i++) {
1464
+ if (!declares(lines[i] ?? "", name))
1465
+ continue;
1466
+ const end = endOf(lines, i, path);
1467
+ spans.push({ path, from: leadingStart(lines, i) + 1, to: end + 1 });
1468
+ i = end;
1469
+ }
1470
+ return spans;
1471
+ }
1472
+ function usages(text, name) {
1473
+ const word = new RegExp(String.raw`(?<![\w$])${escaped(name)}(?![\w$])`);
1474
+ return text.split(`
1475
+ `).flatMap((line, i) => word.test(line) ? [i + 1] : []);
1476
+ }
1477
+ function signature(line) {
1478
+ const text = line.trim().replace(BODY_OPENER, "");
1479
+ return text.length > LONGEST_SIGNATURE ? `${text.slice(0, LONGEST_SIGNATURE - 1)}\u2026` : text;
1480
+ }
1481
+ function outline(text, path) {
1482
+ const lines = text.split(`
1483
+ `);
1484
+ if (MARKDOWN.test(path))
1485
+ return lines.flatMap((line, i) => HEADING.test(line) ? [{ line: i + 1, depth: line.indexOf(" ") - 1, text: line.trim() }] : []);
1486
+ const entries = [];
1487
+ let memberIndent;
1488
+ for (const [i, line] of lines.entries()) {
1489
+ const text = line.trim();
1490
+ const indent = indentOf2(line);
1491
+ if (indent === 0 && DECLARATION.test(text) && !LOCAL_BINDING.test(text)) {
1492
+ entries.push({ line: i + 1, depth: 0, text: signature(line) });
1493
+ memberIndent = HOLDS_MEMBERS.test(text) ? -1 : undefined;
1494
+ } else if (indent === 0 && text !== "" && !text.startsWith("}") && !LEADING.test(text)) {
1495
+ memberIndent = undefined;
1496
+ } else if (memberIndent !== undefined && indent > 0 && (memberIndent === -1 || indent === memberIndent) && MEMBER.test(text) && !CALL_KEYWORDS.test(text)) {
1497
+ memberIndent = indent;
1498
+ entries.push({ line: i + 1, depth: 1, text: signature(line) });
1499
+ }
1500
+ }
1501
+ return entries;
1502
+ }
1503
+ function around(text, path, pattern, context) {
1504
+ const lines = text.replace(TRAILING_NEWLINE, "").split(`
1505
+ `);
1506
+ return spansAround(path, lines.length, lines.flatMap((line, i) => pattern.test(line) ? [i + 1] : []), context);
1507
+ }
1508
+ function spansAround(path, count, numbers, context) {
1509
+ const spans = [];
1510
+ for (const number of [...new Set(numbers)].filter((each) => each >= 1 && each <= count).sort((a, b) => a - b)) {
1511
+ const from = Math.max(1, number - context);
1512
+ const to = Math.min(count, number + context);
1513
+ const previous = spans.at(-1);
1514
+ if (previous !== undefined && from <= previous.to + 1)
1515
+ previous.to = to;
1516
+ else
1517
+ spans.push({ path, from, to });
1518
+ }
1519
+ return spans;
1520
+ }
1521
+ function locations(text) {
1522
+ const found = new Map;
1523
+ for (const line of Bun.stripANSI(text).split(`
1524
+ `)) {
1525
+ const match = LOCATION.exec(line.trim());
1526
+ if (match?.[1] !== undefined)
1527
+ found.set(match[1], [...found.get(match[1]) ?? [], Number(match[2] ?? match[3])]);
1528
+ }
1529
+ return found;
1530
+ }
1531
+
1532
+ // src/peek.ts
1533
+ var USAGE2 = `peek [options] <file[:from-to]>...: prints files or line spans with their line numbers, several in one call
1534
+
1535
+ peek src/a.ts:120-140 src/b.ts:1-40 the spans, src/a.ts:120 the one line, src/a.ts the whole file
1536
+ peek --def <symbol> [path...] the whole declaration of the symbol, its comments included, --def again for more symbols
1537
+ peek --refs <symbol> [path...] the lines naming the symbol, grouped by file, --defs-first printing its declarations before
1538
+ peek --outline <file>... the declarations and class members, a Markdown file's headings
1539
+ peek --around <regex> [-C 3] [path...] the lines around each match, overlapping ones merged
1540
+ <output> | peek [-C 3] the lines around each path:line the output opens a line with (errs, rg -n, grep -n, tsc, linters)
1541
+ The paths default to the files git keeps here (.gitignore holds).
1542
+ --refs lists at most 100 lines and --around prints at most 20 spans, the count of the rest after them (--limit <n>, --full for all).
1543
+ --json prints spans as [{path, from, to, lines}], --refs as [{path, line, text}] ({definitions, references} with --defs-first), --outline as [{path, line, depth, text}], the lines never cut and the rows never counted off unless --limit is given.
1544
+
1545
+ Exits 0 when it printed something, 1 when nothing is found, a file cannot be read or a span starts past the end, 2 on a usage error or a path outside the repository.`;
1546
+ var REFS_LIMIT = 100;
1547
+ var AROUND_LIMIT = 20;
1548
+ var PARENT = `..${sep}`;
1549
+ var OPTIONS2 = {
1550
+ def: { type: "string", short: "d", multiple: true, description: "print the declaration of this symbol, repeat for more" },
1551
+ refs: { type: "string", short: "r", description: "list the lines naming this symbol" },
1552
+ outline: { type: "boolean", short: "o", description: "list the declarations of the files given" },
1553
+ around: { type: "string", short: "a", description: "print the lines around the matches of this regular expression" },
1554
+ "defs-first": { type: "boolean", description: "with --refs, print the symbol's declarations before its lines" },
1555
+ context: { type: "string", short: "C", description: "lines on each side of an --around match or a piped location (3)" },
1556
+ ...limitOptions(REFS_LIMIT),
1557
+ json: jsonOption()
1558
+ };
1559
+ var TARGET = /^(.+?):(\d+)(?:-(\d+))?$/;
1560
+ var LONGEST_LINE = 300;
1561
+ var TRAILING_NEWLINE2 = /\n$/;
1562
+ function cut(text) {
1563
+ return text.length > LONGEST_LINE ? `${text.slice(0, LONGEST_LINE - 1)}\u2026` : text;
1564
+ }
1565
+ async function readableRoot() {
1566
+ const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process11.cwd() });
1567
+ return realpathSync2(ran.code === 0 ? ran.text.trim() : process11.cwd());
1568
+ }
1569
+ async function isOutside(path) {
1570
+ let real;
1571
+ try {
1572
+ real = realpathSync2(resolve(process11.cwd(), path));
1573
+ } catch {
1574
+ return false;
1575
+ }
1576
+ const inRoot = relative2(await readableRoot(), real);
1577
+ return inRoot === ".." || inRoot.startsWith(PARENT) || isAbsolute2(inRoot);
1578
+ }
1579
+ async function checkInside(path) {
1580
+ if (await isOutside(path))
1581
+ badUsage(`${path} is outside the repository`);
1582
+ }
1583
+ async function pipedSpans(text, context) {
1584
+ const spans = [];
1585
+ for (const [path, numbers] of locations(text)) {
1586
+ const source = await isOutside(path) ? undefined : await readText(resolve(process11.cwd(), path));
1587
+ if (source !== undefined)
1588
+ spans.push(...spansAround(path, source.replace(TRAILING_NEWLINE2, "").split(`
1589
+ `).length, numbers, context));
1590
+ }
1591
+ return spans;
1592
+ }
1593
+ async function textOf(path) {
1594
+ await checkInside(path);
1595
+ const text = await readText(resolve(process11.cwd(), path));
1596
+ if (text === undefined)
1597
+ fail(`cannot read ${path} (missing, binary or too large)`, 1);
1598
+ return text;
1599
+ }
1600
+ async function readSpans(spans) {
1601
+ const texts = new Map;
1602
+ const read = [];
1603
+ for (const span of spans) {
1604
+ const lines = texts.get(span.path) ?? (await textOf(span.path)).split(`
1605
+ `);
1606
+ texts.set(span.path, lines);
1607
+ read.push({ ...span, lines: lines.slice(span.from - 1, span.to) });
1608
+ }
1609
+ return read;
1610
+ }
1611
+ function formatSpans(read) {
1612
+ return read.map((span) => [`${span.path}:${span.from}-${span.to}`, ...span.lines.map((line, i) => `${String(span.from + i).padStart(String(span.to).length)} ${cut(line)}`)].join(`
1613
+ `)).join(`
1614
+
1615
+ `);
1616
+ }
1617
+ async function printSpans(spans, json, footer) {
1618
+ const read = await readSpans(spans);
1619
+ if (json) {
1620
+ printJson(read);
1621
+ return;
1622
+ }
1623
+ console.log(formatSpans(read));
1624
+ if (footer !== undefined)
1625
+ console.log(footer);
1626
+ }
1627
+ function printByFile(rows) {
1628
+ const blocks = Map.groupBy(rows, (row) => row.path).entries().map(([path, ofPath]) => {
1629
+ const width = String(ofPath.at(-1)?.line ?? 0).length;
1630
+ return [path, ...ofPath.map((row) => `${String(row.line).padStart(width)} ${row.text}`)].join(`
1631
+ `);
1632
+ });
1633
+ console.log([...blocks].join(`
1634
+
1635
+ `));
1636
+ }
1637
+ async function spanOf(target) {
1638
+ const found = TARGET.exec(target);
1639
+ const path = found?.[1] ?? target;
1640
+ const count = (await textOf(path)).replace(TRAILING_NEWLINE2, "").split(`
1641
+ `).length;
1642
+ const from = found === null ? 1 : Number(found[2]);
1643
+ const to = found === null ? count : Number(found[3] ?? found[2]);
1644
+ if (from < 1 || to < from)
1645
+ badUsage(`${target}: a span reads <file>:<from>-<to>, from 1 and from <= to`);
1646
+ if (from > count)
1647
+ fail(`${path} has ${count} line${count === 1 ? "" : "s"}, ${target} starts past the end`, 1);
1648
+ return { path, from, to: Math.min(to, count) };
1649
+ }
1650
+ async function* sources(paths) {
1651
+ for (const path of paths)
1652
+ await checkInside(path);
1653
+ for (const path of await listFiles(paths, process11.cwd())) {
1654
+ const text = await readText(join5(process11.cwd(), path));
1655
+ if (text !== undefined)
1656
+ yield { path, text };
1657
+ }
1658
+ }
1659
+ function regex(source) {
1660
+ try {
1661
+ return new RegExp(source);
1662
+ } catch (error) {
1663
+ return badUsage(`--around is no valid regular expression: ${error instanceof Error ? error.message : String(error)}`);
1664
+ }
1665
+ }
1666
+ async function definitionsOf(symbols, paths) {
1667
+ const found = new Map(symbols.map((symbol) => [symbol, []]));
1668
+ for await (const { path, text } of sources(paths)) {
1669
+ for (const symbol of symbols)
1670
+ found.get(symbol)?.push(...definitions(text, path, symbol));
1671
+ }
1672
+ const missing = symbols.filter((symbol) => found.get(symbol)?.length === 0);
1673
+ if (missing.length > 0)
1674
+ fail(`no declaration of ${missing.join(", ")} found`, 1);
1675
+ return [...found.values()].flat();
1676
+ }
1677
+ async function peek(args) {
1678
+ const { values, positionals } = parse(args, USAGE2, OPTIONS2, { positionals: ["[target...]"], replaces: "sed -n N,Mp, grep -n chains and whole-file reads", examples: [["peek src/a.ts:120-140 src/b.ts:1-40", "two spans in one call"], ["peek --def parseArgs src", "a whole declaration"]] });
1679
+ const modes = [values.def?.length === 0 ? undefined : values.def, values.refs, values.outline, values.around].filter((mode) => mode !== undefined && mode !== false);
1680
+ const json = values.json === true;
1681
+ if (values["defs-first"] === true && values.refs === undefined)
1682
+ badUsage("--defs-first goes with --refs");
1683
+ if (modes.length > 1)
1684
+ badUsage("give one of --def, --refs, --outline and --around");
1685
+ const isPiped = modes.length === 0 && positionals.length === 0 && isStdinPiped();
1686
+ if (values.context !== undefined && values.around === undefined && !isPiped)
1687
+ badUsage("-C goes with --around or with locations piped in");
1688
+ if (isPiped) {
1689
+ const spans = await pipedSpans(await Bun.stdin.text(), wholeNumber(values.context, "context", 3, 0));
1690
+ if (spans.length === 0)
1691
+ fail("no path:line of a readable file in what was piped in", 1);
1692
+ await printSpans(spans, json);
1693
+ return 0;
1694
+ }
1695
+ if (values.def !== undefined && values.def.length > 0) {
1696
+ const spans = await definitionsOf(values.def, positionals);
1697
+ await printSpans(spans, json);
1698
+ return 0;
1699
+ }
1700
+ if (values.refs !== undefined) {
1701
+ const rows = [];
1702
+ for await (const { path, text } of sources(positionals)) {
1703
+ const lines = text.split(`
1704
+ `);
1705
+ rows.push(...usages(text, values.refs).map((line) => ({ path, line, text: (lines[line - 1] ?? "").trim() })));
1706
+ }
1707
+ if (rows.length === 0)
1708
+ fail(`nothing names ${values.refs}`, 1);
1709
+ const { shown, footer } = capped(rows, limitOf({ ...values, json }, REFS_LIMIT));
1710
+ const defs = values["defs-first"] === true ? await readSpans(await definitionsOf([values.refs], positionals)) : [];
1711
+ if (json) {
1712
+ printJson(values["defs-first"] === true ? { definitions: defs, references: shown } : shown);
1713
+ } else {
1714
+ if (defs.length > 0)
1715
+ console.log(`${formatSpans(defs)}
1716
+ `);
1717
+ printByFile(shown.map((row) => ({ ...row, text: cut(row.text) })));
1718
+ if (footer !== undefined)
1719
+ console.log(footer);
1720
+ }
1721
+ return 0;
1722
+ }
1723
+ if (values.outline === true) {
1724
+ if (positionals.length === 0)
1725
+ badUsage("give the files to outline");
1726
+ const rows = [];
1727
+ for (const path of positionals)
1728
+ rows.push(...outline(await textOf(path), path).map((entry) => ({ path, ...entry })));
1729
+ if (json)
1730
+ printJson(rows);
1731
+ else
1732
+ printByFile(rows.map((row) => ({ ...row, text: `${" ".repeat(row.depth)}${row.text}` })));
1733
+ return 0;
1734
+ }
1735
+ if (values.around !== undefined) {
1736
+ const pattern = regex(values.around);
1737
+ const context = wholeNumber(values.context, "context", 3, 0);
1738
+ const spans = [];
1739
+ for await (const { path, text } of sources(positionals))
1740
+ spans.push(...around(text, path, pattern, context));
1741
+ if (spans.length === 0)
1742
+ fail(`no line matches ${values.around}`, 1);
1743
+ const { shown, footer } = capped(spans, limitOf({ ...values, json }, AROUND_LIMIT));
1744
+ await printSpans(shown, json, footer);
1745
+ return 0;
1746
+ }
1747
+ if (positionals.length === 0)
1748
+ badUsage("give the files or spans to print");
1749
+ await printSpans(await Promise.all(positionals.map(spanOf)), json);
1750
+ return 0;
1751
+ }
1752
+
1753
+ // src/todo-scan.ts
1754
+ import { join as join6 } from "path";
1755
+ import process12 from "process";
1756
+
1757
+ // src/todo.ts
1758
+ var COMMENT2 = /(?<![:\w/])\/\/|\/\*|<!--|(?:^|\s)(?:#|--)(?=\s)|^\s*\*(?=\s|$)/;
1759
+ var MARKUP = /\.(?:md|mdx|markdown|html?|xml)$/i;
1760
+ var MARKUP_COMMENT = /<!--/;
1761
+ var CLOSERS = /\s*(?:\*\/|-->)\s*$/;
1762
+ var MARKER = /^(?:@|\[)?(TODO|FIXME)\b/;
1763
+ var QUOTES = ["'", '"', "`"];
1764
+ var ESCAPE2 = /\\./g;
1765
+ var AFTER_FIRST_LINE = /\n[\s\S]*/;
1766
+ var REF = /(?<![\w./-])(\w[\w.-]*\/(?!\.+#)[\w.][\w.-]*)#(\d+)\b/g;
1767
+ function isQuoted(line, index) {
1768
+ const before = line.slice(0, index).replaceAll(ESCAPE2, "");
1769
+ return QUOTES.some((quote) => before.split(quote).length % 2 === 0);
1770
+ }
1771
+ function marksIn(text, path) {
1772
+ const marks = [];
1773
+ const comment = MARKUP.test(path) ? MARKUP_COMMENT : COMMENT2;
1774
+ for (const [i, line] of text.split(`
1775
+ `).entries()) {
1776
+ const opener = comment.exec(line);
1777
+ if (opener === null || isQuoted(line, opener.index))
1778
+ continue;
1779
+ const body = line.slice(opener.index + opener[0].length).replace(CLOSERS, "").trim();
1780
+ const marker = MARKER.exec(body)?.[1];
1781
+ const refs = [...body.matchAll(REF)].map((found) => ({ repo: found[1] ?? "", number: Number(found[2]) }));
1782
+ if (marker !== undefined || refs.length > 0)
1783
+ marks.push({ path, line: i + 1, kind: marker ?? "ref", text: body, refs });
1784
+ }
1785
+ return marks;
1786
+ }
1787
+ function stdoutOf(chunks) {
1788
+ return Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
1789
+ }
1790
+ function refKey(ref) {
1791
+ return `${ref.repo}#${ref.number}`;
1792
+ }
1793
+ async function lookUpOnGitHub(repo, numbers, cwd) {
1794
+ const states = new Map;
1795
+ for (const ran of await Promise.all(numbers.map(async (number) => ({ number, ran: await runCommand(["gh", "api", `repos/${repo}/issues/${number}`, "--jq", ".state"], { cwd }) })))) {
1796
+ if (ran.ran.code !== 0)
1797
+ return ran.ran.text.trim().replace(AFTER_FIRST_LINE, "");
1798
+ states.set(refKey({ repo, number: Number(ran.number) }), stdoutOf(ran.ran.chunks).trim());
1799
+ }
1800
+ return states;
1801
+ }
1802
+ async function lookUp(refs, cwd) {
1803
+ const lookup = { states: new Map, failed: new Map };
1804
+ const byRepo = Map.groupBy(refs, (ref) => ref.repo);
1805
+ for (const [repo, ofRepo] of byRepo) {
1806
+ const numbers = [...new Set(ofRepo.map((ref) => String(ref.number)))];
1807
+ const ran = Bun.which("ft") === null ? undefined : await runCommand(["ft", "issue", ...numbers, "-r", repo, "--json"], { cwd });
1808
+ if (ran === undefined || ran.code !== 0) {
1809
+ const onGitHub = Bun.which("gh") === null ? "gh is not installed" : await lookUpOnGitHub(repo, numbers, cwd);
1810
+ if (typeof onGitHub === "string") {
1811
+ lookup.failed.set(repo, `ft: ${ran === undefined ? "not installed" : ran.text.trim().replace(AFTER_FIRST_LINE, "")}; gh: ${onGitHub}`);
1812
+ } else {
1813
+ for (const [key, state] of onGitHub)
1814
+ lookup.states.set(key, state);
1815
+ }
1816
+ continue;
1817
+ }
1818
+ const parsed = JSON.parse(stdoutOf(ran.chunks));
1819
+ for (const issue of Array.isArray(parsed) ? parsed : [parsed])
1820
+ lookup.states.set(refKey({ repo, number: issue.number }), issue.state);
1821
+ }
1822
+ return lookup;
1823
+ }
1824
+
1825
+ // src/todo-scan.ts
1826
+ var USAGE3 = `todo-scan [options] [path...]: lists the TODO, FIXME and owner/repo#N comments under the paths (here by default), each as <file>:<line>: <comment>, honouring .gitignore
1827
+
1828
+ --stale keeps only the comments naming a closed issue, each issue's state looked up with ft, or gh for a GitHub repository, and exits 1 when it finds one.
1829
+
1830
+ Lists at most 100 comments, the count of the rest after them (--limit <n>, --full for all); --json is never cut unless --limit is given.
1831
+
1832
+ Exits 0 when it listed the comments or found no stale one, 1 when --stale finds one, 2 on a usage error or when --stale could not look a repository up (ft and gh both failed), so a clean exit never hides an unchecked issue.`;
1833
+ var LIST_LIMIT = 100;
1834
+ var OPTIONS3 = {
1835
+ stale: { type: "boolean", description: "only the comments naming a closed issue, looked up with ft or gh" },
1836
+ ...limitOptions(LIST_LIMIT),
1837
+ json: jsonOption("[{path, line, kind, text, refs: [{repo, number, state?}]}]")
1838
+ };
1839
+ function printLines(lines, footer) {
1840
+ const all = [...lines, ...footer === undefined ? [] : [footer]];
1841
+ if (all.length > 0)
1842
+ console.log(all.join(`
1843
+ `));
1844
+ }
1845
+ async function todoScan(args) {
1846
+ const { values, positionals } = parse(args, USAGE3, OPTIONS3, { positionals: ["[path...]"], replaces: "grep -rn TODO, then opening each issue it names", examples: ["todo-scan src", ["todo-scan --stale", "only the comments naming a closed issue"]] });
1847
+ const cwd = process12.cwd();
1848
+ const limit = limitOf(values, LIST_LIMIT);
1849
+ const marks = [];
1850
+ for (const path of await listFiles(positionals, cwd)) {
1851
+ const text = await readText(join6(cwd, path));
1852
+ if (text !== undefined)
1853
+ marks.push(...marksIn(text, path));
1854
+ }
1855
+ if (values.stale !== true) {
1856
+ const { shown, footer } = capped(marks, limit);
1857
+ if (values.json === true)
1858
+ printJson(shown);
1859
+ else
1860
+ printLines(shown.map((mark) => `${mark.path}:${mark.line}: ${mark.text}`), footer);
1861
+ return 0;
1862
+ }
1863
+ const { states, failed } = await lookUp(marks.flatMap((mark) => mark.refs), cwd);
1864
+ for (const [repo, reason] of failed)
1865
+ warn(`could not look ${repo} up`, reason);
1866
+ const stale = marks.filter((mark) => mark.refs.some((ref) => states.get(refKey(ref)) === "closed"));
1867
+ const { shown, footer } = capped(stale, limit);
1868
+ if (values.json === true)
1869
+ printJson(shown.map((mark) => ({ ...mark, refs: mark.refs.map((ref) => ({ ...ref, state: states.get(refKey(ref)) })) })));
1870
+ else
1871
+ printLines(shown.map((mark) => `${mark.path}:${mark.line}: ${mark.refs.filter((ref) => states.get(refKey(ref)) === "closed").map(refKey).join(", ")} closed: ${mark.text}`), footer);
1872
+ if (stale.length > 0)
1873
+ return 1;
1874
+ return failed.size > 0 ? 2 : 0;
1875
+ }
1876
+
1877
+ // src/cli.ts
1878
+ process13.exitCode = await runCli({
1879
+ name: "src",
1880
+ about: "reads and ranks the source of a folder: line spans, TODO comments and the files worth splitting",
1881
+ replaces: "sed -n N,Mp, grep -n chains and grep -rn TODO",
1882
+ examples: ["src peek src/cli.ts:10-40", "src todo-scan", ["src hotspots -n 10", "the ten files both complex and often edited"]],
1883
+ commands: {
1884
+ peek: { summary: "files or line spans with their line numbers, several in one call", run: peek },
1885
+ "todo-scan": { summary: "the TODO, FIXME and owner/repo#N comments under the paths", run: todoScan },
1886
+ hotspots: { summary: "the source files ranked by complexity times git churn", run: hotspots }
1887
+ }
1888
+ });