@kaynooo/cli-code 0.0.0-stage → 0.6.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/peek.js ADDED
@@ -0,0 +1,1286 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/peek.ts
5
+ import { realpathSync } from "fs";
6
+ import { isAbsolute, join as join2, relative as relative2, resolve, sep } from "path";
7
+ import process7 from "process";
8
+
9
+ // ../kit/src/args.ts
10
+ import { fstatSync } from "fs";
11
+ import process3 from "process";
12
+ import { parseArgs } from "util";
13
+
14
+ // ../kit/src/format.ts
15
+ import process2 from "process";
16
+
17
+ // ../kit/src/style.ts
18
+ import process from "process";
19
+
20
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
21
+ function x(s) {
22
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
23
+ if (!/^[a-f0-9]+$/.test(r))
24
+ return [0, 0, 0];
25
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
26
+ if (t === 3 || t === 4) {
27
+ 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;
28
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
29
+ }
30
+ if (t !== 6 && t !== 8)
31
+ throw Error(`Invalid hex color length: ${t}`);
32
+ 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;
33
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
34
+ throw Error(`Invalid hex color value: ${s}`);
35
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
36
+ }
37
+ function A(s) {
38
+ let [r, t, n, a] = s;
39
+ if (a)
40
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
41
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
42
+ }
43
+ function R(s, r, t) {
44
+ s = (s % 360 + 360) % 360, t /= 100;
45
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
46
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
47
+ return Math.round(255 * y);
48
+ };
49
+ return [a(0), a(8), a(4)];
50
+ }
51
+ function k(s) {
52
+ let [r, t, n] = s;
53
+ r /= 255, t /= 255, n /= 255;
54
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
55
+ if (a !== b) {
56
+ let u = a - b;
57
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
58
+ o = (t - n) / u + (t < n ? 6 : 0);
59
+ else if (a === t)
60
+ o = (n - r) / u + 2;
61
+ else
62
+ o = (r - t) / u + 4;
63
+ o /= 6;
64
+ }
65
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
66
+ }
67
+ function H(s, r, t) {
68
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
69
+ let n = (a) => {
70
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
71
+ return Math.round(255 * o);
72
+ };
73
+ return [n(5), n(3), n(1)];
74
+ }
75
+ function f(s) {
76
+ let [r, t, n] = s;
77
+ r /= 255, t /= 255, n /= 255;
78
+ 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;
79
+ if (o !== 0) {
80
+ if (a === r)
81
+ y = (t - n) / o + (t < n ? 6 : 0);
82
+ else if (a === t)
83
+ y = (n - r) / o + 2;
84
+ else
85
+ y = (r - t) / o + 4;
86
+ y /= 6;
87
+ }
88
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
89
+ }
90
+ function O(s) {
91
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
92
+ if (a === 1)
93
+ return [0, 0, 0, 100];
94
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
95
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
96
+ }
97
+ function v(s, r, t, n) {
98
+ 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))];
99
+ }
100
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
101
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
102
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
103
+ function T(s) {
104
+ 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);
105
+ 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)];
106
+ }
107
+ function M(s, r, t) {
108
+ 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)));
109
+ return [u(o), u(y), u(c)];
110
+ }
111
+ function d(s) {
112
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
113
+ return [i(r, 4), i(a, 4), i(b, 2)];
114
+ }
115
+ function C(s, r, t) {
116
+ let n = t * Math.PI / 180;
117
+ return M(s, r * Math.cos(n), r * Math.sin(n));
118
+ }
119
+ function l(s) {
120
+ let r = s / 255;
121
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
122
+ }
123
+
124
+ class e {
125
+ r;
126
+ g;
127
+ b;
128
+ a;
129
+ constructor(s, r, t, n = 1) {
130
+ this.r = s, this.g = r, this.b = t, this.a = n;
131
+ }
132
+ static from(s, r) {
133
+ if (s === "hex") {
134
+ let [t, n, a, b] = x(r);
135
+ return new e(t, n, a, b);
136
+ }
137
+ if (s === "rgb") {
138
+ if (Array.isArray(r)) {
139
+ let [o, y, c, u] = r;
140
+ return new e(o, y, c, u);
141
+ }
142
+ let { r: t, g: n, b: a, a: b } = r;
143
+ return new e(t, n, a, b);
144
+ }
145
+ if (s === "hsl") {
146
+ let t, n, a, b;
147
+ if (Array.isArray(r))
148
+ [t, n, a, b] = r;
149
+ else
150
+ ({ h: t, s: n, l: a, a: b } = r);
151
+ let [o, y, c] = R(t, n, a);
152
+ return new e(o, y, c, b);
153
+ }
154
+ if (s === "hsv") {
155
+ let t, n, a, b;
156
+ if (Array.isArray(r))
157
+ [t, n, a, b] = r;
158
+ else
159
+ ({ h: t, s: n, v: a, a: b } = r);
160
+ let [o, y, c] = H(t, n, a);
161
+ return new e(o, y, c, b);
162
+ }
163
+ if (s === "cmyk") {
164
+ let t, n, a, b, o;
165
+ if (Array.isArray(r))
166
+ [t, n, a, b, o] = r;
167
+ else
168
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
169
+ let [y, c, u] = v(t, n, a, b);
170
+ return new e(y, c, u, o);
171
+ }
172
+ if (s === "oklch") {
173
+ let t, n, a, b;
174
+ if (Array.isArray(r))
175
+ [t, n, a, b] = r;
176
+ else
177
+ ({ l: t, c: n, h: a, a: b } = r);
178
+ let [o, y, c] = C(t, n, a);
179
+ return new e(o, y, c, b);
180
+ }
181
+ if (s === "oklab") {
182
+ let t, n, a, b;
183
+ if (Array.isArray(r))
184
+ [t, n, a, b] = r;
185
+ else
186
+ ({ l: t, a: n, b: a, alpha: b } = r);
187
+ let [o, y, c] = M(t, n, a);
188
+ return new e(o, y, c, b);
189
+ }
190
+ throw Error("Invalid input");
191
+ }
192
+ to(s) {
193
+ switch (s) {
194
+ case "rgb":
195
+ return [this.r, this.g, this.b];
196
+ case "rgba":
197
+ return [this.r, this.g, this.b, this.a];
198
+ case "hex":
199
+ return A([this.r, this.g, this.b]);
200
+ case "hexa":
201
+ return A([this.r, this.g, this.b, this.a]);
202
+ case "hsl":
203
+ return k([this.r, this.g, this.b]);
204
+ case "hsla":
205
+ return [...k([this.r, this.g, this.b]), this.a];
206
+ case "hsv":
207
+ return f([this.r, this.g, this.b]);
208
+ case "hsva":
209
+ return [...f([this.r, this.g, this.b]), this.a];
210
+ case "cmyk":
211
+ return O([this.r, this.g, this.b]);
212
+ case "cmyka":
213
+ return [...O([this.r, this.g, this.b]), this.a];
214
+ case "oklch":
215
+ return d([this.r, this.g, this.b]);
216
+ case "oklcha":
217
+ return [...d([this.r, this.g, this.b]), this.a];
218
+ case "oklab":
219
+ return T([this.r, this.g, this.b]);
220
+ case "oklaba":
221
+ return [...T([this.r, this.g, this.b]), this.a];
222
+ default:
223
+ return [this.r, this.g, this.b];
224
+ }
225
+ }
226
+ getLuminance() {
227
+ let s = l(this.r), r = l(this.g), t = l(this.b);
228
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
229
+ }
230
+ contrastRatio(s) {
231
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
232
+ return (n + 0.05) / (a + 0.05);
233
+ }
234
+ bestContrastForeground() {
235
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
236
+ return t >= n ? s : r;
237
+ }
238
+ }
239
+
240
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
241
+ var r = 39;
242
+ var o = 49;
243
+ var f2 = "\x1B[";
244
+ 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") => {
245
+ let [a, l, s] = e.from("hex", i).to("rgb");
246
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
247
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
248
+ var b = new Set(["", "1", "2", "3", "true"]);
249
+ function h(i, n = globalThis.process?.env ?? {}) {
250
+ if (n.FORCE_COLOR !== undefined)
251
+ return b.has(n.FORCE_COLOR);
252
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
253
+ return false;
254
+ return i?.isTTY === true;
255
+ }
256
+ function d2(i, n, a) {
257
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
258
+ return n;
259
+ let l = "", s = "";
260
+ for (let g = 0, y = i.length;g < y; g++) {
261
+ let [c, p] = i[g];
262
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
263
+ }
264
+ return l + n + s;
265
+ }
266
+ function u(i, n = []) {
267
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
268
+ let g = C2[s];
269
+ if (Array.isArray(g))
270
+ return u(i, [...n, g]);
271
+ if (typeof g === "function")
272
+ return (...y) => u(i, [...n, g(...y)]);
273
+ throw Error(`Unknown style: ${String(s)}`);
274
+ } });
275
+ }
276
+ function le(i = {}) {
277
+ return u(i);
278
+ }
279
+ var t = le();
280
+
281
+ // ../kit/src/style.ts
282
+ var MARKS = {
283
+ ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
284
+ warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
285
+ problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
286
+ note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
287
+ };
288
+ function takesControlCodes(stream, env = process.env) {
289
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
290
+ }
291
+ function paint(stream, env = process.env) {
292
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
293
+ }
294
+ function marked(mark, text, stream, detail, env = process.env) {
295
+ const colors = paint(stream, env);
296
+ const { symbol, word, paint: tint } = MARKS[mark];
297
+ const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
298
+ return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
299
+ }
300
+ function warn(text, detail) {
301
+ console.error(marked("warn", text, process.stderr, detail));
302
+ }
303
+ var STATUSES = {
304
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
305
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
306
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
307
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
308
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
309
+ };
310
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
311
+
312
+ // ../kit/src/format.ts
313
+ function upTo(text, separator) {
314
+ const end = text.indexOf(separator);
315
+ return end === -1 ? text : text.slice(0, end);
316
+ }
317
+ function truncate(text, width) {
318
+ return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
319
+ }
320
+ var LINE_BREAKS = /\s*\n\s*/g;
321
+ var ESCAPE = String.fromCharCode(27);
322
+ function textWidth(text) {
323
+ return Bun.stringWidth(text);
324
+ }
325
+ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
326
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
327
+ const widths = [];
328
+ for (const row of cells) {
329
+ for (const [index, cell] of row.entries())
330
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
331
+ }
332
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
333
+ const colors = paint(process2.stdout);
334
+ const lines = shown.map((row) => row.map((cell, index) => {
335
+ const width = widths[index] ?? 0;
336
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
337
+ if (align[index] === "right")
338
+ return `${gap}${cell}`;
339
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
340
+ }).join(" ").trimEnd());
341
+ return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
342
+ `);
343
+ }
344
+ function narrow(rows, widths, limit) {
345
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
346
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
347
+ const floor = 8;
348
+ while (used() > limit) {
349
+ let widest = -1;
350
+ for (const [index, width] of widths.entries()) {
351
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
352
+ widest = index;
353
+ }
354
+ if (widest === -1)
355
+ break;
356
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
357
+ }
358
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
359
+ }
360
+ function printJson(value) {
361
+ console.log(JSON.stringify(value, undefined, 2));
362
+ }
363
+
364
+ // ../kit/src/text.ts
365
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
366
+ function distance(a, b) {
367
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
368
+ for (const [i, left] of [...a].entries()) {
369
+ const current = [i + 1];
370
+ for (const [j, right] of [...b].entries())
371
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
372
+ previous = current;
373
+ }
374
+ return previous[b.length] ?? 0;
375
+ }
376
+ function closest(name, names) {
377
+ const started = names.find((known) => known.startsWith(name));
378
+ if (started !== undefined)
379
+ return started;
380
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
381
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
382
+ }
383
+
384
+ // ../kit/src/args.ts
385
+ function jsonOption(holds) {
386
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
387
+ }
388
+
389
+ class Exit extends Error {
390
+ code;
391
+ hint;
392
+ constructor(message, code, hint) {
393
+ super(message);
394
+ this.code = code;
395
+ this.hint = hint;
396
+ }
397
+ }
398
+ function fail(message, code = 2, hint) {
399
+ throw new Exit(message, code, hint);
400
+ }
401
+
402
+ class UsageError extends Exit {
403
+ constructor(message, hint) {
404
+ super(message, 2, hint);
405
+ }
406
+ }
407
+ function badUsage(message) {
408
+ throw new UsageError(message);
409
+ }
410
+
411
+ class HelpShown extends Exit {
412
+ constructor() {
413
+ super("help shown", 0);
414
+ }
415
+ }
416
+
417
+ class Completing {
418
+ options;
419
+ positionals;
420
+ candidates;
421
+ constructor(options, positionals = [], candidates = {}) {
422
+ this.options = options;
423
+ this.positionals = positionals;
424
+ this.candidates = candidates;
425
+ }
426
+ }
427
+ var completion = { active: false };
428
+ var OPTIONAL = /\[[^\]]+\]/g;
429
+ var USAGE_PREFIX = /^usage:\s*/i;
430
+ var FULL_STOP = /\.$/;
431
+ var DASHES = /^-+/;
432
+ function usageLine(usage, colors = paint(process3.stdout)) {
433
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
434
+ }
435
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
436
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
437
+ `);
438
+ }
439
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
440
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
441
+ }
442
+ function wantsHelpJson(env = process3.env) {
443
+ return env.KIT_HELP === "json";
444
+ }
445
+ function description(usage, { examples = [], replaces } = {}) {
446
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
447
+ `);
448
+ const first = lines[0];
449
+ const colon = first.indexOf(": ");
450
+ const prose = lines[lines.indexOf("") + 1] ?? "";
451
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
452
+ return {
453
+ synopsis: colon === -1 ? first : first.slice(0, colon),
454
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
455
+ ...replaces === undefined ? {} : { replaces },
456
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
457
+ };
458
+ }
459
+ function exampleRows(examples, colors = paint(process3.stdout)) {
460
+ if (examples.length === 0)
461
+ return [];
462
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
463
+ }
464
+ function optionRows(options, colors = paint(process3.stdout)) {
465
+ const rows = Object.entries(options).map(([name, option]) => {
466
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
467
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
468
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
469
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
470
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
471
+ });
472
+ const width = Math.max(0, ...rows.map((row) => row.width));
473
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
474
+ }
475
+ var OUTPUT_OPTIONS = {
476
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
477
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
478
+ };
479
+ function applyOutput(color, plain, env = process3.env) {
480
+ const when = plain === true ? "never" : color ?? "auto";
481
+ if (when === "auto")
482
+ return;
483
+ if (when !== "always" && when !== "never")
484
+ badUsage(`--color takes auto, always or never, not ${when}`);
485
+ if (when === "always") {
486
+ env.FORCE_COLOR = "1";
487
+ delete env.NO_COLOR;
488
+ } else {
489
+ env.NO_COLOR = "1";
490
+ delete env.FORCE_COLOR;
491
+ }
492
+ }
493
+ function parse(args, usage, options, settings = {}) {
494
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
495
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
496
+ const listing = listed(all, settings.allowNegative === true);
497
+ if (completion.active)
498
+ throw new Completing(listing, settings.positionals, settings.candidates);
499
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
500
+ let parsed;
501
+ try {
502
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
503
+ } catch (error) {
504
+ const message = parseError(error);
505
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
506
+ }
507
+ const values = parsed.values;
508
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
509
+ if (values.help === true) {
510
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
511
+ throw new HelpShown;
512
+ }
513
+ checkChoices(parsed.values, all);
514
+ checkConflicts(parsed.values, all);
515
+ if (settings.positionals !== undefined)
516
+ checkPositionals(parsed.positionals, settings.positionals);
517
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
518
+ }
519
+ function splitRest(args, passes) {
520
+ const separator = passes ? args.indexOf("--") : -1;
521
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
522
+ }
523
+ function splitTrailing(args, options, count) {
524
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
525
+ let seen = 0;
526
+ if (count === 0)
527
+ return { own: args, rest: undefined };
528
+ for (let at = 0;at < args.length; at++) {
529
+ const word = args[at];
530
+ if (word === "--")
531
+ break;
532
+ if (word.startsWith("-")) {
533
+ if (takesValue(word))
534
+ at++;
535
+ continue;
536
+ }
537
+ seen++;
538
+ if (seen === count)
539
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
540
+ }
541
+ return { own: args, rest: undefined };
542
+ }
543
+ function listed(options, allowNegative) {
544
+ if (!allowNegative)
545
+ return options;
546
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
547
+ if (option.type !== "boolean" || option.negative === undefined)
548
+ return [[name, option]];
549
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
550
+ }));
551
+ }
552
+ function withBare(args, options) {
553
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
554
+ if (bare.size === 0)
555
+ return args;
556
+ const separator = args.indexOf("--");
557
+ const own = separator === -1 ? args : args.slice(0, separator);
558
+ return [...own.flatMap((arg, index) => {
559
+ const optional = bare.get(arg);
560
+ const next = own[index + 1];
561
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
562
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
563
+ }), ...separator === -1 ? [] : args.slice(separator)];
564
+ }
565
+ function checkConflicts(values, options) {
566
+ const given = (name) => values[name] !== undefined && values[name] !== false;
567
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
568
+ const other = given(name) ? conflicts.find(given) : undefined;
569
+ if (other !== undefined)
570
+ badUsage(`--${name} cannot be used with --${other}`);
571
+ }
572
+ }
573
+ function checkChoices(values, options) {
574
+ for (const [name, option] of Object.entries(options)) {
575
+ if (option.choices === undefined)
576
+ continue;
577
+ const given = values[name];
578
+ for (const value of Array.isArray(given) ? given : [given]) {
579
+ if (typeof value === "string")
580
+ oneOf(value, name, option.choices);
581
+ }
582
+ }
583
+ }
584
+ function oneOf(value, name, choices) {
585
+ if (!choices.includes(value))
586
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
587
+ return value;
588
+ }
589
+ function checkPositionals(given, names) {
590
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
591
+ const required = names.filter((name) => !name.startsWith("[")).length;
592
+ if (given.length < required)
593
+ badUsage(`missing ${names[given.length]}`);
594
+ if (!variadic && given.length > names.length)
595
+ badUsage(`unexpected argument ${given[names.length]}`);
596
+ }
597
+ function joinDashValues(args, options) {
598
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
599
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
600
+ const joined = [];
601
+ for (let i = 0;i < args.length; i++) {
602
+ const arg = args[i] ?? "";
603
+ if (arg === "--")
604
+ return [...joined, ...args.slice(i)];
605
+ const name = longOf.get(arg);
606
+ const next = args[i + 1];
607
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
608
+ joined.push(`--${name}=${next}`);
609
+ i++;
610
+ } else {
611
+ joined.push(arg);
612
+ }
613
+ }
614
+ return joined;
615
+ }
616
+ function parseError(error) {
617
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
618
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
619
+ }
620
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
621
+ function nearestOption(message, options, allowNegative) {
622
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
623
+ if (typed === undefined)
624
+ return;
625
+ const word = typed.replace(DASHES, "");
626
+ if (word.length < 2 && !typed.startsWith("--"))
627
+ return;
628
+ const known = Object.entries(options).flatMap(([name, option]) => [
629
+ ...option.short === undefined ? [] : [`-${option.short}`],
630
+ `--${name}`,
631
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
632
+ ]);
633
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
634
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
635
+ }
636
+ var WHOLE = /^\d+$/;
637
+ function wholeNumber(value, name, fallback, min = 1) {
638
+ if (value === undefined)
639
+ return fallback;
640
+ const number = Number(value);
641
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
642
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
643
+ return number;
644
+ }
645
+ function isStdinPiped() {
646
+ const stat = fstatSync(0);
647
+ return stat.isFIFO() || stat.isFile();
648
+ }
649
+ // ../kit/src/process.ts
650
+ import { constants } from "os";
651
+ import process4 from "process";
652
+ var KILL_GRACE_MS = 2000;
653
+ function exitCodeOf(code, signal) {
654
+ if (code !== null)
655
+ return code;
656
+ if (typeof signal === "number")
657
+ return 128 + signal;
658
+ return signal === null ? 129 : 128 + constants.signals[signal];
659
+ }
660
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
661
+ const chunks = [];
662
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
663
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
664
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
665
+ const timers = [];
666
+ const killGroup = (killing) => {
667
+ if (state.done)
668
+ return;
669
+ try {
670
+ if (grouped)
671
+ process4.kill(-proc.pid, killing);
672
+ else
673
+ proc.kill(killing);
674
+ } catch {}
675
+ };
676
+ const stop = () => {
677
+ killGroup("SIGTERM");
678
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
679
+ };
680
+ const onAbort = () => stop();
681
+ if (timeoutMs !== undefined) {
682
+ timers.push(setTimeout(() => {
683
+ state.timedOut = true;
684
+ stop();
685
+ }, timeoutMs));
686
+ }
687
+ if (signal?.aborted === true)
688
+ onAbort();
689
+ else
690
+ signal?.addEventListener("abort", onAbort, { once: true });
691
+ onStart?.({ kill: (killing) => killGroup(killing) });
692
+ const drain = async (stream, name) => {
693
+ for await (const data of stream) {
694
+ if (state.failure !== undefined)
695
+ continue;
696
+ try {
697
+ onChunk?.({ stream: name, data });
698
+ } catch (error) {
699
+ state.failure = error;
700
+ stop();
701
+ continue;
702
+ }
703
+ if (state.kept + data.length > maxBytes) {
704
+ state.truncated = true;
705
+ continue;
706
+ }
707
+ state.kept += data.length;
708
+ chunks.push({ stream: name, data });
709
+ }
710
+ };
711
+ try {
712
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
713
+ await proc.exited;
714
+ } finally {
715
+ state.done = true;
716
+ for (const timer of timers)
717
+ clearTimeout(timer);
718
+ signal?.removeEventListener("abort", onAbort);
719
+ }
720
+ if (state.failure !== undefined)
721
+ throw state.failure;
722
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
723
+ let output;
724
+ let text;
725
+ return {
726
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
727
+ chunks,
728
+ timedOut: state.timedOut,
729
+ truncated: state.truncated,
730
+ get output() {
731
+ return output ??= joined();
732
+ },
733
+ get text() {
734
+ return text ??= (output ??= joined()).toString();
735
+ }
736
+ };
737
+ }
738
+
739
+ // ../kit/src/progress.ts
740
+ var ESC = String.fromCharCode(27);
741
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
742
+ var RESET_STYLE = `${ESC}[0m`;
743
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
744
+ // ../kit/src/cli.ts
745
+ import process5 from "process";
746
+ var LEVEL_OPTIONS = {
747
+ ...OUTPUT_OPTIONS,
748
+ help: { type: "boolean", short: "h", description: "show this help" }
749
+ };
750
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
751
+ function printError(prefix, message, hint, cause) {
752
+ const colors = paint(process5.stderr);
753
+ const styled = takesControlCodes(process5.stderr);
754
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
755
+ const under = (label, text, tint) => text === undefined ? "" : `
756
+ ${styled ? tint(label) : `${label}:`} ${text}`;
757
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
758
+ }
759
+ function printJsonError(message, hint, cause) {
760
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
761
+ }
762
+ function wantsJson(argv) {
763
+ const end = argv.indexOf("--");
764
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
765
+ }
766
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
767
+ if (error instanceof HelpShown)
768
+ return 0;
769
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
770
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
771
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
772
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
773
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
774
+ return error instanceof Exit ? error.code : 1;
775
+ }
776
+ var COMPLETE = "__complete";
777
+ var FILES = "__files__";
778
+ async function completingOf(run) {
779
+ completion.active = true;
780
+ try {
781
+ await run([]);
782
+ } catch (error) {
783
+ if (error instanceof Completing)
784
+ return error;
785
+ } finally {
786
+ completion.active = false;
787
+ }
788
+ return new Completing({});
789
+ }
790
+ function candidateLine(candidate) {
791
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
792
+ }
793
+ function positionalBeingTyped(before, { options, positionals }) {
794
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
795
+ let index = 0;
796
+ let at = 0;
797
+ while (at < before.length) {
798
+ const word = before[at];
799
+ if (word === "--") {
800
+ index += before.length - at - 1;
801
+ break;
802
+ }
803
+ if (!word.startsWith("-"))
804
+ index++;
805
+ else if (takesValue(word))
806
+ at++;
807
+ at++;
808
+ }
809
+ const last = positionals.at(-1);
810
+ if (index < positionals.length)
811
+ return positionals[index];
812
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
813
+ }
814
+ async function leafCandidates(run, words) {
815
+ const completing = await completingOf(run);
816
+ if ((words.at(-1) ?? "").startsWith("-"))
817
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
818
+ const flag = words.at(-2);
819
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
820
+ if (option?.type === "string") {
821
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
822
+ return values === undefined ? [FILES] : values.map(candidateLine);
823
+ }
824
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
825
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
826
+ return values === undefined ? [FILES] : values.map(candidateLine);
827
+ }
828
+ async function printCandidates(found) {
829
+ for (const line of await found)
830
+ console.log(line);
831
+ return 0;
832
+ }
833
+ async function runMain({ name, version, run, redact }, argv = process5.argv.slice(2)) {
834
+ if (argv[0] === COMPLETE)
835
+ return printCandidates(leafCandidates(run, argv.slice(1)));
836
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
837
+ console.log(version);
838
+ return 0;
839
+ }
840
+ try {
841
+ return await run(argv);
842
+ } catch (error) {
843
+ return reportThrown(name, error, redact, wantsJson(argv));
844
+ }
845
+ }
846
+ // ../kit/src/limit.ts
847
+ function limitOptions(fallback) {
848
+ return {
849
+ limit: { type: "string", short: "n", description: `show at most this many rows, the rest counted (${fallback})` },
850
+ full: { type: "boolean", description: "show every row" }
851
+ };
852
+ }
853
+ function limitOf(values, fallback) {
854
+ if (values.full === true && values.limit !== undefined)
855
+ badUsage("--limit and --full exclude each other");
856
+ if (values.full === true || values.json === true && values.limit === undefined)
857
+ return Number.POSITIVE_INFINITY;
858
+ return wholeNumber(values.limit, "limit", fallback);
859
+ }
860
+ function moreFooter(more) {
861
+ return `${more} more, rerun with --full`;
862
+ }
863
+ function capped(rows, limit) {
864
+ const more = rows.length - limit;
865
+ return more > 0 ? { shown: rows.slice(0, limit), footer: moreFooter(more) } : { shown: [...rows], footer: undefined };
866
+ }
867
+ // ../kit/src/logs.ts
868
+ var DAY_MS = 24 * 60 * 60 * 1000;
869
+ // ../kit/src/secrets.ts
870
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
871
+ // ../kit/src/sessions.ts
872
+ var {Glob } = globalThis.Bun;
873
+ var SESSION_FILES = new Glob("*.json");
874
+ var ACCOUNT_DIRS = new Glob("*/sessions");
875
+ // package.json
876
+ var version = "0.6.0";
877
+
878
+ // src/files.ts
879
+ import { existsSync, readdirSync, statSync } from "fs";
880
+ import { join, relative } from "path";
881
+ var MAX_BYTES = 2000000;
882
+ var SNIFF_BYTES = 8000;
883
+ var SKIPPED = new Set(["node_modules", "dist", "build", "vendor", "target", "coverage"]);
884
+ function walk(dir, found) {
885
+ let entries;
886
+ try {
887
+ entries = readdirSync(dir, { withFileTypes: true });
888
+ } catch {
889
+ return found;
890
+ }
891
+ for (const entry of entries) {
892
+ if (entry.name.startsWith(".") || SKIPPED.has(entry.name))
893
+ continue;
894
+ if (entry.isDirectory())
895
+ walk(join(dir, entry.name), found);
896
+ else if (entry.isFile())
897
+ found.push(join(dir, entry.name));
898
+ }
899
+ return found;
900
+ }
901
+ async function listFiles(paths, cwd) {
902
+ const listed = await runCommand(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...paths], { cwd });
903
+ if (listed.code === 0)
904
+ return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync(join(cwd, path))).sort();
905
+ const roots = paths.length === 0 ? [cwd] : paths.map((path) => join(cwd, path));
906
+ return roots.flatMap((root) => statSync(root, { throwIfNoEntry: false })?.isFile() === true ? [root] : walk(root, [])).map((path) => relative(cwd, path)).sort();
907
+ }
908
+ async function readText(path) {
909
+ const file = Bun.file(path);
910
+ try {
911
+ if (file.size > MAX_BYTES || (await file.slice(0, SNIFF_BYTES).bytes()).includes(0))
912
+ return;
913
+ return await file.text();
914
+ } catch {
915
+ return;
916
+ }
917
+ }
918
+
919
+ // src/source.ts
920
+ var LOCATION = /^(?:\.\/)?([^\s:()]+)(?::(\d+)(?::\d+)?|\((\d+),\d+\))(?=[:\s)]|$)/;
921
+ 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/;
922
+ var MODIFIERS = /^(?:(?:public|private|protected|static|async|override|readonly|abstract|get|set|pub|fn|def|func)\s+)*/;
923
+ var MEMBER = /^(?:(?:public|private|protected|static|async|override|readonly|abstract|get|set|pub|fn|def|func)\s+)*[#\w$]+\s*(?:<[^>]*>\s*)?\(/;
924
+ var RECEIVER = /^(?:\([^)]*\)\s*)?/;
925
+ var STAR = /^\*?\s*/;
926
+ var HOLDS_MEMBERS = /\b(?:class|interface|trait|impl|struct)\s/;
927
+ var CALL_KEYWORDS = /^(?:if|for|while|switch|catch|return|await|throw|new|else|do|try|super|typeof)\b/;
928
+ var LEADING = /^(?:\/\/|\/\*|\*|#(?!!)|@)/;
929
+ var LOCAL_BINDING = /^(?:const|let|var)\s/;
930
+ var HEADING = /^#{1,6}\s/;
931
+ var TRAILING_NEWLINE = /\n$/;
932
+ var MARKDOWN = /\.(?:md|mdx|markdown)$/i;
933
+ var INDENTED = /\.(?:py|yml|yaml)$/i;
934
+ var INDENT = /^\s*/;
935
+ var CONTINUES = /(?:[=(,[{:?|&+\-*/<>]|=>)$/;
936
+ var BODY_OPENER = /\s*\{\s*$/;
937
+ var LONGEST_DEFINITION = 400;
938
+ var LONGEST_SIGNATURE = 160;
939
+ function indentOf(line) {
940
+ return INDENT.exec(line)?.[0].length ?? 0;
941
+ }
942
+ function escaped(name) {
943
+ return name.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
944
+ }
945
+ function declares(line, name) {
946
+ const text = line.trim();
947
+ const word = new RegExp(String.raw`^${escaped(name)}\b`);
948
+ if (DECLARATION.test(text)) {
949
+ const rest = text.replace(DECLARATION, "").replace(RECEIVER, "");
950
+ return word.test(rest.replace(STAR, ""));
951
+ }
952
+ return line !== text && MEMBER.test(text) && !CALL_KEYWORDS.test(text) && word.test(text.replace(MODIFIERS, "")) && (text.endsWith("{") || text.endsWith(":"));
953
+ }
954
+ function depthChange(line, quote) {
955
+ let braces = 0;
956
+ let parens = 0;
957
+ for (let i = 0;i < line.length; i++) {
958
+ const char = line[i] ?? "";
959
+ if (quote.open !== "") {
960
+ if (char === "\\")
961
+ i++;
962
+ else if (char === quote.open)
963
+ quote.open = "";
964
+ continue;
965
+ }
966
+ if (char === "/" && line[i + 1] === "/")
967
+ break;
968
+ if (char === '"' || char === "'" || char === "`")
969
+ quote.open = char;
970
+ else if (char === "{")
971
+ braces++;
972
+ else if (char === "}")
973
+ braces--;
974
+ else if (char === "(" || char === "[")
975
+ parens++;
976
+ else if (char === ")" || char === "]")
977
+ parens--;
978
+ }
979
+ if (quote.open !== "`")
980
+ quote.open = "";
981
+ return { braces, parens };
982
+ }
983
+ function endOf(lines, start, path) {
984
+ const last = Math.min(lines.length - 1, start + LONGEST_DEFINITION - 1);
985
+ if (INDENTED.test(path)) {
986
+ const indent = indentOf(lines[start] ?? "");
987
+ let end = start;
988
+ for (let i = start + 1;i <= last; i++) {
989
+ const line = lines[i] ?? "";
990
+ if (line.trim() !== "" && indentOf(line) <= indent)
991
+ break;
992
+ if (line.trim() !== "")
993
+ end = i;
994
+ }
995
+ return end;
996
+ }
997
+ const quote = { open: "" };
998
+ let braces = 0;
999
+ let parens = 0;
1000
+ let opened = false;
1001
+ for (let i = start;i <= last; i++) {
1002
+ const line = lines[i] ?? "";
1003
+ const change = depthChange(line, quote);
1004
+ opened ||= change.braces > 0 || line.includes("{");
1005
+ braces += change.braces;
1006
+ parens += change.parens;
1007
+ if (braces <= 0 && parens <= 0 && quote.open === "" && (opened || !CONTINUES.test(line.trimEnd())))
1008
+ return i;
1009
+ }
1010
+ return last;
1011
+ }
1012
+ function leadingStart(lines, start) {
1013
+ let first = start;
1014
+ while (first > 0 && LEADING.test((lines[first - 1] ?? "").trim()))
1015
+ first--;
1016
+ return first;
1017
+ }
1018
+ function definitions(text, path, name) {
1019
+ const lines = text.split(`
1020
+ `);
1021
+ const spans = [];
1022
+ for (let i = 0;i < lines.length; i++) {
1023
+ if (!declares(lines[i] ?? "", name))
1024
+ continue;
1025
+ const end = endOf(lines, i, path);
1026
+ spans.push({ path, from: leadingStart(lines, i) + 1, to: end + 1 });
1027
+ i = end;
1028
+ }
1029
+ return spans;
1030
+ }
1031
+ function usages(text, name) {
1032
+ const word = new RegExp(String.raw`(?<![\w$])${escaped(name)}(?![\w$])`);
1033
+ return text.split(`
1034
+ `).flatMap((line, i) => word.test(line) ? [i + 1] : []);
1035
+ }
1036
+ function signature(line) {
1037
+ const text = line.trim().replace(BODY_OPENER, "");
1038
+ return text.length > LONGEST_SIGNATURE ? `${text.slice(0, LONGEST_SIGNATURE - 1)}\u2026` : text;
1039
+ }
1040
+ function outline(text, path) {
1041
+ const lines = text.split(`
1042
+ `);
1043
+ if (MARKDOWN.test(path))
1044
+ return lines.flatMap((line, i) => HEADING.test(line) ? [{ line: i + 1, depth: line.indexOf(" ") - 1, text: line.trim() }] : []);
1045
+ const entries = [];
1046
+ let memberIndent;
1047
+ for (const [i, line] of lines.entries()) {
1048
+ const text = line.trim();
1049
+ const indent = indentOf(line);
1050
+ if (indent === 0 && DECLARATION.test(text) && !LOCAL_BINDING.test(text)) {
1051
+ entries.push({ line: i + 1, depth: 0, text: signature(line) });
1052
+ memberIndent = HOLDS_MEMBERS.test(text) ? -1 : undefined;
1053
+ } else if (indent === 0 && text !== "" && !text.startsWith("}") && !LEADING.test(text)) {
1054
+ memberIndent = undefined;
1055
+ } else if (memberIndent !== undefined && indent > 0 && (memberIndent === -1 || indent === memberIndent) && MEMBER.test(text) && !CALL_KEYWORDS.test(text)) {
1056
+ memberIndent = indent;
1057
+ entries.push({ line: i + 1, depth: 1, text: signature(line) });
1058
+ }
1059
+ }
1060
+ return entries;
1061
+ }
1062
+ function around(text, path, pattern, context) {
1063
+ const lines = text.replace(TRAILING_NEWLINE, "").split(`
1064
+ `);
1065
+ return spansAround(path, lines.length, lines.flatMap((line, i) => pattern.test(line) ? [i + 1] : []), context);
1066
+ }
1067
+ function spansAround(path, count, numbers, context) {
1068
+ const spans = [];
1069
+ for (const number of [...new Set(numbers)].filter((each) => each >= 1 && each <= count).sort((a, b) => a - b)) {
1070
+ const from = Math.max(1, number - context);
1071
+ const to = Math.min(count, number + context);
1072
+ const previous = spans.at(-1);
1073
+ if (previous !== undefined && from <= previous.to + 1)
1074
+ previous.to = to;
1075
+ else
1076
+ spans.push({ path, from, to });
1077
+ }
1078
+ return spans;
1079
+ }
1080
+ function locations(text) {
1081
+ const found = new Map;
1082
+ for (const line of Bun.stripANSI(text).split(`
1083
+ `)) {
1084
+ const match = LOCATION.exec(line.trim());
1085
+ if (match?.[1] !== undefined)
1086
+ found.set(match[1], [...found.get(match[1]) ?? [], Number(match[2] ?? match[3])]);
1087
+ }
1088
+ return found;
1089
+ }
1090
+
1091
+ // src/peek.ts
1092
+ var USAGE = `peek [options] <file[:from-to]>...: prints files or line spans with their line numbers, several in one call
1093
+
1094
+ 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
1095
+ peek --def <symbol> [path...] the whole declaration of the symbol, its comments included
1096
+ peek --refs <symbol> [path...] the lines naming the symbol, grouped by file
1097
+ peek --outline <file>... the declarations and class members, a Markdown file's headings
1098
+ peek --around <regex> [-C 3] [path...] the lines around each match, overlapping ones merged
1099
+ <output> | peek [-C 3] the lines around each path:line the output opens a line with (errs, rg -n, grep -n, tsc, linters)
1100
+ The paths default to the files git keeps here (.gitignore holds).
1101
+ --refs lists at most 100 lines, the count of the rest after them (--limit <n>, --full for all).
1102
+ --json prints spans as [{path, from, to, lines}], --refs as [{path, line, text}], --outline as [{path, line, depth, text}], the lines never cut and the rows never counted off unless --limit is given.
1103
+
1104
+ 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.`;
1105
+ var REFS_LIMIT = 100;
1106
+ var PARENT = `..${sep}`;
1107
+ var OPTIONS = {
1108
+ def: { type: "string", short: "d", description: "print the declaration of this symbol" },
1109
+ refs: { type: "string", short: "r", description: "list the lines naming this symbol" },
1110
+ outline: { type: "boolean", short: "o", description: "list the declarations of the files given" },
1111
+ around: { type: "string", short: "a", description: "print the lines around the matches of this regular expression" },
1112
+ context: { type: "string", short: "C", description: "lines on each side of an --around match or a piped location (3)" },
1113
+ ...limitOptions(REFS_LIMIT),
1114
+ json: jsonOption()
1115
+ };
1116
+ var TARGET = /^(.+?):(\d+)(?:-(\d+))?$/;
1117
+ var LONGEST_LINE = 300;
1118
+ var TRAILING_NEWLINE2 = /\n$/;
1119
+ function cut(text) {
1120
+ return text.length > LONGEST_LINE ? `${text.slice(0, LONGEST_LINE - 1)}\u2026` : text;
1121
+ }
1122
+ async function readableRoot() {
1123
+ const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process7.cwd() });
1124
+ return realpathSync(ran.code === 0 ? ran.text.trim() : process7.cwd());
1125
+ }
1126
+ async function isOutside(path) {
1127
+ let real;
1128
+ try {
1129
+ real = realpathSync(resolve(process7.cwd(), path));
1130
+ } catch {
1131
+ return false;
1132
+ }
1133
+ const inRoot = relative2(await readableRoot(), real);
1134
+ return inRoot === ".." || inRoot.startsWith(PARENT) || isAbsolute(inRoot);
1135
+ }
1136
+ async function checkInside(path) {
1137
+ if (await isOutside(path))
1138
+ badUsage(`${path} is outside the repository`);
1139
+ }
1140
+ async function pipedSpans(text, context) {
1141
+ const spans = [];
1142
+ for (const [path, numbers] of locations(text)) {
1143
+ const source = await isOutside(path) ? undefined : await readText(resolve(process7.cwd(), path));
1144
+ if (source !== undefined)
1145
+ spans.push(...spansAround(path, source.replace(TRAILING_NEWLINE2, "").split(`
1146
+ `).length, numbers, context));
1147
+ }
1148
+ return spans;
1149
+ }
1150
+ async function textOf(path) {
1151
+ await checkInside(path);
1152
+ const text = await readText(resolve(process7.cwd(), path));
1153
+ if (text === undefined)
1154
+ fail(`cannot read ${path} (missing, binary or too large)`, 1);
1155
+ return text;
1156
+ }
1157
+ async function printSpans(spans, json) {
1158
+ const texts = new Map;
1159
+ const read = [];
1160
+ for (const span of spans) {
1161
+ const lines = texts.get(span.path) ?? (await textOf(span.path)).split(`
1162
+ `);
1163
+ texts.set(span.path, lines);
1164
+ read.push({ ...span, lines: lines.slice(span.from - 1, span.to) });
1165
+ }
1166
+ if (json) {
1167
+ printJson(read);
1168
+ return;
1169
+ }
1170
+ console.log(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(`
1171
+ `)).join(`
1172
+
1173
+ `));
1174
+ }
1175
+ function printByFile(rows) {
1176
+ const blocks = Map.groupBy(rows, (row) => row.path).entries().map(([path, ofPath]) => {
1177
+ const width = String(ofPath.at(-1)?.line ?? 0).length;
1178
+ return [path, ...ofPath.map((row) => `${String(row.line).padStart(width)} ${row.text}`)].join(`
1179
+ `);
1180
+ });
1181
+ console.log([...blocks].join(`
1182
+
1183
+ `));
1184
+ }
1185
+ async function spanOf(target) {
1186
+ const found = TARGET.exec(target);
1187
+ const path = found?.[1] ?? target;
1188
+ const count = (await textOf(path)).replace(TRAILING_NEWLINE2, "").split(`
1189
+ `).length;
1190
+ const from = found === null ? 1 : Number(found[2]);
1191
+ const to = found === null ? count : Number(found[3] ?? found[2]);
1192
+ if (from < 1 || to < from)
1193
+ badUsage(`${target}: a span reads <file>:<from>-<to>, from 1 and from <= to`);
1194
+ if (from > count)
1195
+ fail(`${path} has ${count} line${count === 1 ? "" : "s"}, ${target} starts past the end`, 1);
1196
+ return { path, from, to: Math.min(to, count) };
1197
+ }
1198
+ async function* sources(paths) {
1199
+ for (const path of paths)
1200
+ await checkInside(path);
1201
+ for (const path of await listFiles(paths, process7.cwd())) {
1202
+ const text = await readText(join2(process7.cwd(), path));
1203
+ if (text !== undefined)
1204
+ yield { path, text };
1205
+ }
1206
+ }
1207
+ function regex(source) {
1208
+ try {
1209
+ return new RegExp(source);
1210
+ } catch (error) {
1211
+ return badUsage(`--around is no valid regular expression: ${error instanceof Error ? error.message : String(error)}`);
1212
+ }
1213
+ }
1214
+ async function main(args) {
1215
+ const { values, positionals } = parse(args, USAGE, OPTIONS, { 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"]] });
1216
+ const modes = [values.def, values.refs, values.outline, values.around].filter((mode) => mode !== undefined && mode !== false);
1217
+ const json = values.json === true;
1218
+ if (modes.length > 1)
1219
+ badUsage("give one of --def, --refs, --outline and --around");
1220
+ const isPiped = modes.length === 0 && positionals.length === 0 && isStdinPiped();
1221
+ if (values.context !== undefined && values.around === undefined && !isPiped)
1222
+ badUsage("-C goes with --around or with locations piped in");
1223
+ if (isPiped) {
1224
+ const spans = await pipedSpans(await Bun.stdin.text(), wholeNumber(values.context, "context", 3, 0));
1225
+ if (spans.length === 0)
1226
+ fail("no path:line of a readable file in what was piped in", 1);
1227
+ await printSpans(spans, json);
1228
+ return 0;
1229
+ }
1230
+ if (values.def !== undefined) {
1231
+ const spans = [];
1232
+ for await (const { path, text } of sources(positionals))
1233
+ spans.push(...definitions(text, path, values.def));
1234
+ if (spans.length === 0)
1235
+ fail(`no declaration of ${values.def} found`, 1);
1236
+ await printSpans(spans, json);
1237
+ return 0;
1238
+ }
1239
+ if (values.refs !== undefined) {
1240
+ const rows = [];
1241
+ for await (const { path, text } of sources(positionals)) {
1242
+ const lines = text.split(`
1243
+ `);
1244
+ rows.push(...usages(text, values.refs).map((line) => ({ path, line, text: (lines[line - 1] ?? "").trim() })));
1245
+ }
1246
+ if (rows.length === 0)
1247
+ fail(`nothing names ${values.refs}`, 1);
1248
+ const { shown, footer } = capped(rows, limitOf({ ...values, json }, REFS_LIMIT));
1249
+ if (json) {
1250
+ printJson(shown);
1251
+ } else {
1252
+ printByFile(shown.map((row) => ({ ...row, text: cut(row.text) })));
1253
+ if (footer !== undefined)
1254
+ console.log(footer);
1255
+ }
1256
+ return 0;
1257
+ }
1258
+ if (values.outline === true) {
1259
+ if (positionals.length === 0)
1260
+ badUsage("give the files to outline");
1261
+ const rows = [];
1262
+ for (const path of positionals)
1263
+ rows.push(...outline(await textOf(path), path).map((entry) => ({ path, ...entry })));
1264
+ if (json)
1265
+ printJson(rows);
1266
+ else
1267
+ printByFile(rows.map((row) => ({ ...row, text: `${" ".repeat(row.depth)}${row.text}` })));
1268
+ return 0;
1269
+ }
1270
+ if (values.around !== undefined) {
1271
+ const pattern = regex(values.around);
1272
+ const context = wholeNumber(values.context, "context", 3, 0);
1273
+ const spans = [];
1274
+ for await (const { path, text } of sources(positionals))
1275
+ spans.push(...around(text, path, pattern, context));
1276
+ if (spans.length === 0)
1277
+ fail(`no line matches ${values.around}`, 1);
1278
+ await printSpans(spans, json);
1279
+ return 0;
1280
+ }
1281
+ if (positionals.length === 0)
1282
+ badUsage("give the files or spans to print");
1283
+ await printSpans(await Promise.all(positionals.map(spanOf)), json);
1284
+ return 0;
1285
+ }
1286
+ process7.exitCode = await runMain({ name: "peek", version, run: main });