@kaynooo/cli-pick 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +20 -2
- package/dist/pick.js +1294 -0
- package/package.json +38 -4
package/dist/pick.js
ADDED
|
@@ -0,0 +1,1294 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
|
|
4
|
+
// src/pick.ts
|
|
5
|
+
import process10 from "process";
|
|
6
|
+
// ../kit/src/args.ts
|
|
7
|
+
import process4 from "process";
|
|
8
|
+
import { parseArgs } from "util";
|
|
9
|
+
|
|
10
|
+
// ../kit/src/style.ts
|
|
11
|
+
import process2 from "process";
|
|
12
|
+
|
|
13
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
14
|
+
function x(s) {
|
|
15
|
+
let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
|
|
16
|
+
if (!/^[a-f0-9]+$/.test(r))
|
|
17
|
+
return [0, 0, 0];
|
|
18
|
+
let t = r.length, n = (c) => Number.parseInt(c, 16);
|
|
19
|
+
if (t === 3 || t === 4) {
|
|
20
|
+
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;
|
|
21
|
+
return g !== undefined ? [c, u, h, g] : [c, u, h];
|
|
22
|
+
}
|
|
23
|
+
if (t !== 6 && t !== 8)
|
|
24
|
+
throw Error(`Invalid hex color length: ${t}`);
|
|
25
|
+
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;
|
|
26
|
+
if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
|
|
27
|
+
throw Error(`Invalid hex color value: ${s}`);
|
|
28
|
+
return y !== undefined ? [a, b, o, y] : [a, b, o];
|
|
29
|
+
}
|
|
30
|
+
function A(s) {
|
|
31
|
+
let [r, t, n, a] = s;
|
|
32
|
+
if (a)
|
|
33
|
+
return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
|
|
34
|
+
return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
|
|
35
|
+
}
|
|
36
|
+
function R(s, r, t) {
|
|
37
|
+
s = (s % 360 + 360) % 360, t /= 100;
|
|
38
|
+
let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
|
|
39
|
+
let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
|
|
40
|
+
return Math.round(255 * y);
|
|
41
|
+
};
|
|
42
|
+
return [a(0), a(8), a(4)];
|
|
43
|
+
}
|
|
44
|
+
function k(s) {
|
|
45
|
+
let [r, t, n] = s;
|
|
46
|
+
r /= 255, t /= 255, n /= 255;
|
|
47
|
+
let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
|
|
48
|
+
if (a !== b) {
|
|
49
|
+
let u = a - b;
|
|
50
|
+
if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
|
|
51
|
+
o = (t - n) / u + (t < n ? 6 : 0);
|
|
52
|
+
else if (a === t)
|
|
53
|
+
o = (n - r) / u + 2;
|
|
54
|
+
else
|
|
55
|
+
o = (r - t) / u + 4;
|
|
56
|
+
o /= 6;
|
|
57
|
+
}
|
|
58
|
+
return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
|
|
59
|
+
}
|
|
60
|
+
function H(s, r, t) {
|
|
61
|
+
s = (s % 360 + 360) % 360, r /= 100, t /= 100;
|
|
62
|
+
let n = (a) => {
|
|
63
|
+
let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
|
|
64
|
+
return Math.round(255 * o);
|
|
65
|
+
};
|
|
66
|
+
return [n(5), n(3), n(1)];
|
|
67
|
+
}
|
|
68
|
+
function f(s) {
|
|
69
|
+
let [r, t, n] = s;
|
|
70
|
+
r /= 255, t /= 255, n /= 255;
|
|
71
|
+
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;
|
|
72
|
+
if (o !== 0) {
|
|
73
|
+
if (a === r)
|
|
74
|
+
y = (t - n) / o + (t < n ? 6 : 0);
|
|
75
|
+
else if (a === t)
|
|
76
|
+
y = (n - r) / o + 2;
|
|
77
|
+
else
|
|
78
|
+
y = (r - t) / o + 4;
|
|
79
|
+
y /= 6;
|
|
80
|
+
}
|
|
81
|
+
return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
|
|
82
|
+
}
|
|
83
|
+
function O(s) {
|
|
84
|
+
let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
|
|
85
|
+
if (a === 1)
|
|
86
|
+
return [0, 0, 0, 100];
|
|
87
|
+
let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
|
|
88
|
+
return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
|
|
89
|
+
}
|
|
90
|
+
function v(s, r, t, n) {
|
|
91
|
+
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))];
|
|
92
|
+
}
|
|
93
|
+
var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
|
94
|
+
var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
|
|
95
|
+
var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
|
|
96
|
+
function T(s) {
|
|
97
|
+
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);
|
|
98
|
+
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)];
|
|
99
|
+
}
|
|
100
|
+
function M(s, r, t) {
|
|
101
|
+
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)));
|
|
102
|
+
return [u(o), u(y), u(c)];
|
|
103
|
+
}
|
|
104
|
+
function d(s) {
|
|
105
|
+
let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
|
|
106
|
+
return [i(r, 4), i(a, 4), i(b, 2)];
|
|
107
|
+
}
|
|
108
|
+
function C(s, r, t) {
|
|
109
|
+
let n = t * Math.PI / 180;
|
|
110
|
+
return M(s, r * Math.cos(n), r * Math.sin(n));
|
|
111
|
+
}
|
|
112
|
+
function l(s) {
|
|
113
|
+
let r = s / 255;
|
|
114
|
+
return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
class e {
|
|
118
|
+
r;
|
|
119
|
+
g;
|
|
120
|
+
b;
|
|
121
|
+
a;
|
|
122
|
+
constructor(s, r, t, n = 1) {
|
|
123
|
+
this.r = s, this.g = r, this.b = t, this.a = n;
|
|
124
|
+
}
|
|
125
|
+
static from(s, r) {
|
|
126
|
+
if (s === "hex") {
|
|
127
|
+
let [t, n, a, b] = x(r);
|
|
128
|
+
return new e(t, n, a, b);
|
|
129
|
+
}
|
|
130
|
+
if (s === "rgb") {
|
|
131
|
+
if (Array.isArray(r)) {
|
|
132
|
+
let [o, y, c, u] = r;
|
|
133
|
+
return new e(o, y, c, u);
|
|
134
|
+
}
|
|
135
|
+
let { r: t, g: n, b: a, a: b } = r;
|
|
136
|
+
return new e(t, n, a, b);
|
|
137
|
+
}
|
|
138
|
+
if (s === "hsl") {
|
|
139
|
+
let t, n, a, b;
|
|
140
|
+
if (Array.isArray(r))
|
|
141
|
+
[t, n, a, b] = r;
|
|
142
|
+
else
|
|
143
|
+
({ h: t, s: n, l: a, a: b } = r);
|
|
144
|
+
let [o, y, c] = R(t, n, a);
|
|
145
|
+
return new e(o, y, c, b);
|
|
146
|
+
}
|
|
147
|
+
if (s === "hsv") {
|
|
148
|
+
let t, n, a, b;
|
|
149
|
+
if (Array.isArray(r))
|
|
150
|
+
[t, n, a, b] = r;
|
|
151
|
+
else
|
|
152
|
+
({ h: t, s: n, v: a, a: b } = r);
|
|
153
|
+
let [o, y, c] = H(t, n, a);
|
|
154
|
+
return new e(o, y, c, b);
|
|
155
|
+
}
|
|
156
|
+
if (s === "cmyk") {
|
|
157
|
+
let t, n, a, b, o;
|
|
158
|
+
if (Array.isArray(r))
|
|
159
|
+
[t, n, a, b, o] = r;
|
|
160
|
+
else
|
|
161
|
+
({ c: t, m: n, y: a, k: b, a: o } = r);
|
|
162
|
+
let [y, c, u] = v(t, n, a, b);
|
|
163
|
+
return new e(y, c, u, o);
|
|
164
|
+
}
|
|
165
|
+
if (s === "oklch") {
|
|
166
|
+
let t, n, a, b;
|
|
167
|
+
if (Array.isArray(r))
|
|
168
|
+
[t, n, a, b] = r;
|
|
169
|
+
else
|
|
170
|
+
({ l: t, c: n, h: a, a: b } = r);
|
|
171
|
+
let [o, y, c] = C(t, n, a);
|
|
172
|
+
return new e(o, y, c, b);
|
|
173
|
+
}
|
|
174
|
+
if (s === "oklab") {
|
|
175
|
+
let t, n, a, b;
|
|
176
|
+
if (Array.isArray(r))
|
|
177
|
+
[t, n, a, b] = r;
|
|
178
|
+
else
|
|
179
|
+
({ l: t, a: n, b: a, alpha: b } = r);
|
|
180
|
+
let [o, y, c] = M(t, n, a);
|
|
181
|
+
return new e(o, y, c, b);
|
|
182
|
+
}
|
|
183
|
+
throw Error("Invalid input");
|
|
184
|
+
}
|
|
185
|
+
to(s) {
|
|
186
|
+
switch (s) {
|
|
187
|
+
case "rgb":
|
|
188
|
+
return [this.r, this.g, this.b];
|
|
189
|
+
case "rgba":
|
|
190
|
+
return [this.r, this.g, this.b, this.a];
|
|
191
|
+
case "hex":
|
|
192
|
+
return A([this.r, this.g, this.b]);
|
|
193
|
+
case "hexa":
|
|
194
|
+
return A([this.r, this.g, this.b, this.a]);
|
|
195
|
+
case "hsl":
|
|
196
|
+
return k([this.r, this.g, this.b]);
|
|
197
|
+
case "hsla":
|
|
198
|
+
return [...k([this.r, this.g, this.b]), this.a];
|
|
199
|
+
case "hsv":
|
|
200
|
+
return f([this.r, this.g, this.b]);
|
|
201
|
+
case "hsva":
|
|
202
|
+
return [...f([this.r, this.g, this.b]), this.a];
|
|
203
|
+
case "cmyk":
|
|
204
|
+
return O([this.r, this.g, this.b]);
|
|
205
|
+
case "cmyka":
|
|
206
|
+
return [...O([this.r, this.g, this.b]), this.a];
|
|
207
|
+
case "oklch":
|
|
208
|
+
return d([this.r, this.g, this.b]);
|
|
209
|
+
case "oklcha":
|
|
210
|
+
return [...d([this.r, this.g, this.b]), this.a];
|
|
211
|
+
case "oklab":
|
|
212
|
+
return T([this.r, this.g, this.b]);
|
|
213
|
+
case "oklaba":
|
|
214
|
+
return [...T([this.r, this.g, this.b]), this.a];
|
|
215
|
+
default:
|
|
216
|
+
return [this.r, this.g, this.b];
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
getLuminance() {
|
|
220
|
+
let s = l(this.r), r = l(this.g), t = l(this.b);
|
|
221
|
+
return 0.2126 * s + 0.7152 * r + 0.0722 * t;
|
|
222
|
+
}
|
|
223
|
+
contrastRatio(s) {
|
|
224
|
+
let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
|
|
225
|
+
return (n + 0.05) / (a + 0.05);
|
|
226
|
+
}
|
|
227
|
+
bestContrastForeground() {
|
|
228
|
+
let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
|
|
229
|
+
return t >= n ? s : r;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
|
|
234
|
+
var r = 39;
|
|
235
|
+
var o = 49;
|
|
236
|
+
var f2 = "\x1B[";
|
|
237
|
+
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") => {
|
|
238
|
+
let [a, l, s] = e.from("hex", i).to("rgb");
|
|
239
|
+
return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
|
|
240
|
+
}, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
|
|
241
|
+
var b = new Set(["", "1", "2", "3", "true"]);
|
|
242
|
+
function h(i, n = globalThis.process?.env ?? {}) {
|
|
243
|
+
if (n.FORCE_COLOR !== undefined)
|
|
244
|
+
return b.has(n.FORCE_COLOR);
|
|
245
|
+
if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
|
|
246
|
+
return false;
|
|
247
|
+
return i?.isTTY === true;
|
|
248
|
+
}
|
|
249
|
+
function d2(i, n, a) {
|
|
250
|
+
if (!h(a.stream ?? globalThis.process?.stdout, a.env))
|
|
251
|
+
return n;
|
|
252
|
+
let l = "", s = "";
|
|
253
|
+
for (let g = 0, y = i.length;g < y; g++) {
|
|
254
|
+
let [c, p] = i[g];
|
|
255
|
+
l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
|
|
256
|
+
}
|
|
257
|
+
return l + n + s;
|
|
258
|
+
}
|
|
259
|
+
function u(i, n = []) {
|
|
260
|
+
return new Proxy((l) => d2(n, l, i), { get(l, s) {
|
|
261
|
+
let g = C2[s];
|
|
262
|
+
if (Array.isArray(g))
|
|
263
|
+
return u(i, [...n, g]);
|
|
264
|
+
if (typeof g === "function")
|
|
265
|
+
return (...y) => u(i, [...n, g(...y)]);
|
|
266
|
+
throw Error(`Unknown style: ${String(s)}`);
|
|
267
|
+
} });
|
|
268
|
+
}
|
|
269
|
+
function le(i = {}) {
|
|
270
|
+
return u(i);
|
|
271
|
+
}
|
|
272
|
+
var t = le();
|
|
273
|
+
|
|
274
|
+
// ../kit/src/style.ts
|
|
275
|
+
function takesControlCodes(stream, env = process2.env) {
|
|
276
|
+
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
|
|
277
|
+
}
|
|
278
|
+
function paint(stream, env = process2.env) {
|
|
279
|
+
return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
280
|
+
}
|
|
281
|
+
var ROLES = {
|
|
282
|
+
accent: (colors) => colors.cyan,
|
|
283
|
+
id: (colors) => colors.yellow,
|
|
284
|
+
path: (colors) => colors.blue,
|
|
285
|
+
label: (colors) => colors.dim,
|
|
286
|
+
value: (colors) => colors.bold
|
|
287
|
+
};
|
|
288
|
+
function role(name, stream, env = process2.env) {
|
|
289
|
+
return ROLES[name](paint(stream, env));
|
|
290
|
+
}
|
|
291
|
+
var STATUSES = {
|
|
292
|
+
passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
|
|
293
|
+
failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
|
|
294
|
+
running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
|
|
295
|
+
queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
|
|
296
|
+
skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
|
|
297
|
+
};
|
|
298
|
+
var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
|
|
299
|
+
|
|
300
|
+
// ../kit/src/format.ts
|
|
301
|
+
function upTo(text, separator) {
|
|
302
|
+
const end = text.indexOf(separator);
|
|
303
|
+
return end === -1 ? text : text.slice(0, end);
|
|
304
|
+
}
|
|
305
|
+
var ESCAPE = String.fromCharCode(27);
|
|
306
|
+
|
|
307
|
+
// ../kit/src/help.ts
|
|
308
|
+
import process3 from "process";
|
|
309
|
+
var OPTIONAL = /\[[^\]]+\]/g;
|
|
310
|
+
var USAGE_PREFIX = /^usage:\s*/i;
|
|
311
|
+
var FULL_STOP = /\.$/;
|
|
312
|
+
function usageLine(usage, colors = paint(process3.stdout)) {
|
|
313
|
+
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
314
|
+
}
|
|
315
|
+
function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces, exits = [] } = {}) {
|
|
316
|
+
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
317
|
+
`);
|
|
318
|
+
}
|
|
319
|
+
function exitRows(exits, colors = paint(process3.stdout)) {
|
|
320
|
+
if (exits.length === 0)
|
|
321
|
+
return [];
|
|
322
|
+
const width = Math.max(...exits.map(([code]) => String(code).length));
|
|
323
|
+
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
324
|
+
}
|
|
325
|
+
function replacesRows(replaces, colors = paint(process3.stdout)) {
|
|
326
|
+
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
327
|
+
}
|
|
328
|
+
function wantsHelpJson(env = process3.env) {
|
|
329
|
+
return env.KIT_HELP === "json";
|
|
330
|
+
}
|
|
331
|
+
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
332
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
333
|
+
`);
|
|
334
|
+
const first = lines[0];
|
|
335
|
+
const colon = first.indexOf(": ");
|
|
336
|
+
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
337
|
+
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
338
|
+
return {
|
|
339
|
+
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
340
|
+
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
341
|
+
...replaces === undefined ? {} : { replaces },
|
|
342
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
343
|
+
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
344
|
+
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
function exampleRows(examples, colors = paint(process3.stdout)) {
|
|
348
|
+
if (examples.length === 0)
|
|
349
|
+
return [];
|
|
350
|
+
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
351
|
+
}
|
|
352
|
+
function optionRows(options, colors = paint(process3.stdout)) {
|
|
353
|
+
const rows = Object.entries(options).map(([name, option]) => {
|
|
354
|
+
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
355
|
+
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
356
|
+
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
357
|
+
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
358
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
|
|
359
|
+
});
|
|
360
|
+
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
361
|
+
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
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
|
+
var DASHES = /^-+/;
|
|
386
|
+
class Exit extends Error {
|
|
387
|
+
code;
|
|
388
|
+
hint;
|
|
389
|
+
constructor(message, code, hint) {
|
|
390
|
+
super(message);
|
|
391
|
+
this.code = code;
|
|
392
|
+
this.hint = hint;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
function fail(message, code = 2, hint) {
|
|
396
|
+
throw new Exit(message, code, hint);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
class UsageError extends Exit {
|
|
400
|
+
constructor(message, hint) {
|
|
401
|
+
super(message, 2, hint);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
function badUsage(message) {
|
|
405
|
+
throw new UsageError(message);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
class HelpShown extends Exit {
|
|
409
|
+
constructor() {
|
|
410
|
+
super("help shown", 0);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
class Completing {
|
|
415
|
+
options;
|
|
416
|
+
positionals;
|
|
417
|
+
candidates;
|
|
418
|
+
constructor(options, positionals = [], candidates = {}) {
|
|
419
|
+
this.options = options;
|
|
420
|
+
this.positionals = positionals;
|
|
421
|
+
this.candidates = candidates;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
var completion = { active: false };
|
|
425
|
+
var OUTPUT_OPTIONS = {
|
|
426
|
+
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
427
|
+
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
428
|
+
};
|
|
429
|
+
function applyOutput(color, plain, env = process4.env) {
|
|
430
|
+
const when = plain === true ? "never" : color ?? "auto";
|
|
431
|
+
if (when === "auto")
|
|
432
|
+
return;
|
|
433
|
+
if (when !== "always" && when !== "never")
|
|
434
|
+
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
435
|
+
if (when === "always") {
|
|
436
|
+
env.FORCE_COLOR = "1";
|
|
437
|
+
delete env.NO_COLOR;
|
|
438
|
+
} else {
|
|
439
|
+
env.NO_COLOR = "1";
|
|
440
|
+
delete env.FORCE_COLOR;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
function parse(args, usage, options, settings = {}) {
|
|
444
|
+
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
445
|
+
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
446
|
+
const listing = listed(all, settings.allowNegative === true);
|
|
447
|
+
if (completion.active)
|
|
448
|
+
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
449
|
+
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
450
|
+
let parsed;
|
|
451
|
+
try {
|
|
452
|
+
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
453
|
+
} catch (error) {
|
|
454
|
+
const message = parseError(error);
|
|
455
|
+
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
456
|
+
}
|
|
457
|
+
const values = parsed.values;
|
|
458
|
+
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
459
|
+
if (values.help === true) {
|
|
460
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
461
|
+
throw new HelpShown;
|
|
462
|
+
}
|
|
463
|
+
checkChoices(parsed.values, all);
|
|
464
|
+
checkConflicts(parsed.values, all);
|
|
465
|
+
if (settings.positionals !== undefined)
|
|
466
|
+
checkPositionals(parsed.positionals, settings.positionals);
|
|
467
|
+
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
468
|
+
}
|
|
469
|
+
function splitRest(args, passes) {
|
|
470
|
+
const separator = passes ? args.indexOf("--") : -1;
|
|
471
|
+
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
472
|
+
}
|
|
473
|
+
function splitTrailing(args, options, count) {
|
|
474
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
475
|
+
let seen = 0;
|
|
476
|
+
if (count === 0)
|
|
477
|
+
return { own: args, rest: undefined };
|
|
478
|
+
for (let at = 0;at < args.length; at++) {
|
|
479
|
+
const word = args[at];
|
|
480
|
+
if (word === "--")
|
|
481
|
+
break;
|
|
482
|
+
if (word.startsWith("-")) {
|
|
483
|
+
if (takesValue(word))
|
|
484
|
+
at++;
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
seen++;
|
|
488
|
+
if (seen === count)
|
|
489
|
+
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
490
|
+
}
|
|
491
|
+
return { own: args, rest: undefined };
|
|
492
|
+
}
|
|
493
|
+
function listed(options, allowNegative) {
|
|
494
|
+
if (!allowNegative)
|
|
495
|
+
return options;
|
|
496
|
+
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
497
|
+
if (option.type !== "boolean" || option.negative === undefined)
|
|
498
|
+
return [[name, option]];
|
|
499
|
+
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
500
|
+
}));
|
|
501
|
+
}
|
|
502
|
+
function withAliases(args, options) {
|
|
503
|
+
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
504
|
+
if (named.size === 0)
|
|
505
|
+
return args;
|
|
506
|
+
const separator = args.indexOf("--");
|
|
507
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
508
|
+
return [...own.map((arg) => {
|
|
509
|
+
const at = arg.indexOf("=");
|
|
510
|
+
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
511
|
+
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
512
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
513
|
+
}
|
|
514
|
+
function withBare(args, options) {
|
|
515
|
+
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
516
|
+
if (bare.size === 0)
|
|
517
|
+
return args;
|
|
518
|
+
const separator = args.indexOf("--");
|
|
519
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
520
|
+
return [...own.flatMap((arg, index) => {
|
|
521
|
+
const optional = bare.get(arg);
|
|
522
|
+
const next = own[index + 1];
|
|
523
|
+
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
524
|
+
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
525
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
526
|
+
}
|
|
527
|
+
function checkConflicts(values, options) {
|
|
528
|
+
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
529
|
+
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
530
|
+
const other = given(name) ? conflicts.find(given) : undefined;
|
|
531
|
+
if (other !== undefined)
|
|
532
|
+
badUsage(`--${name} cannot be used with --${other}`);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
function checkChoices(values, options) {
|
|
536
|
+
for (const [name, option] of Object.entries(options)) {
|
|
537
|
+
if (option.choices === undefined)
|
|
538
|
+
continue;
|
|
539
|
+
const given = values[name];
|
|
540
|
+
for (const value of Array.isArray(given) ? given : [given]) {
|
|
541
|
+
if (typeof value === "string")
|
|
542
|
+
oneOf(value, name, option.choices);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
function oneOf(value, name, choices) {
|
|
547
|
+
if (!choices.includes(value))
|
|
548
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
549
|
+
return value;
|
|
550
|
+
}
|
|
551
|
+
function checkPositionals(given, names) {
|
|
552
|
+
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
553
|
+
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
554
|
+
if (given.length < required)
|
|
555
|
+
badUsage(`missing ${names[given.length]}`);
|
|
556
|
+
if (!variadic && given.length > names.length)
|
|
557
|
+
badUsage(`unexpected argument ${given[names.length]}`);
|
|
558
|
+
}
|
|
559
|
+
function joinDashValues(args, options) {
|
|
560
|
+
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
561
|
+
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
562
|
+
const joined = [];
|
|
563
|
+
for (let i = 0;i < args.length; i++) {
|
|
564
|
+
const arg = args[i] ?? "";
|
|
565
|
+
if (arg === "--")
|
|
566
|
+
return [...joined, ...args.slice(i)];
|
|
567
|
+
const name = longOf.get(arg);
|
|
568
|
+
const next = args[i + 1];
|
|
569
|
+
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
570
|
+
joined.push(`--${name}=${next}`);
|
|
571
|
+
i++;
|
|
572
|
+
} else {
|
|
573
|
+
joined.push(arg);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
return joined;
|
|
577
|
+
}
|
|
578
|
+
function parseError(error) {
|
|
579
|
+
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
580
|
+
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
581
|
+
}
|
|
582
|
+
var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
583
|
+
function nearestOption(message, options, allowNegative) {
|
|
584
|
+
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
585
|
+
if (typed === undefined)
|
|
586
|
+
return;
|
|
587
|
+
const word = typed.replace(DASHES, "");
|
|
588
|
+
if (word.length < 2 && !typed.startsWith("--"))
|
|
589
|
+
return;
|
|
590
|
+
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
591
|
+
...option.short === undefined ? [] : [`-${option.short}`],
|
|
592
|
+
`--${name}`,
|
|
593
|
+
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
594
|
+
]);
|
|
595
|
+
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
596
|
+
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
597
|
+
}
|
|
598
|
+
// ../kit/src/progress.ts
|
|
599
|
+
var ESC = String.fromCharCode(27);
|
|
600
|
+
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
601
|
+
var RESET_STYLE = `${ESC}[0m`;
|
|
602
|
+
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
603
|
+
// ../kit/src/cli.ts
|
|
604
|
+
import { readFileSync, realpathSync } from "fs";
|
|
605
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
606
|
+
import process6 from "process";
|
|
607
|
+
|
|
608
|
+
// ../kit/src/usage.ts
|
|
609
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
610
|
+
import { homedir } from "os";
|
|
611
|
+
import { dirname, isAbsolute, join } from "path";
|
|
612
|
+
import process5 from "process";
|
|
613
|
+
|
|
614
|
+
// ../kit/src/logs.ts
|
|
615
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
616
|
+
var CLI_FOLDER = "kaynooo-cli";
|
|
617
|
+
|
|
618
|
+
// ../kit/src/usage.ts
|
|
619
|
+
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
620
|
+
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
621
|
+
var LONGEST_NAME = 40;
|
|
622
|
+
var usageError;
|
|
623
|
+
function noteUsageError(message) {
|
|
624
|
+
usageError = message;
|
|
625
|
+
}
|
|
626
|
+
function stateHome(env = process5.env) {
|
|
627
|
+
const dir = env.XDG_STATE_HOME;
|
|
628
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
|
|
629
|
+
}
|
|
630
|
+
function usagePath(env = process5.env) {
|
|
631
|
+
return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
632
|
+
}
|
|
633
|
+
function usageRecorded(env = process5.env) {
|
|
634
|
+
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
635
|
+
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
636
|
+
}
|
|
637
|
+
function flagNames(argv) {
|
|
638
|
+
const end = argv.indexOf("--");
|
|
639
|
+
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
640
|
+
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
641
|
+
}
|
|
642
|
+
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
643
|
+
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
644
|
+
usageError = undefined;
|
|
645
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
646
|
+
}
|
|
647
|
+
function recordUsage(entry, env = process5.env) {
|
|
648
|
+
if (!usageRecorded(env))
|
|
649
|
+
return;
|
|
650
|
+
try {
|
|
651
|
+
const path = usagePath(env);
|
|
652
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
653
|
+
appendFileSync(path, `${JSON.stringify(entry)}
|
|
654
|
+
`, { mode: 384 });
|
|
655
|
+
} catch {}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// ../kit/src/cli.ts
|
|
659
|
+
var LEVEL_OPTIONS = {
|
|
660
|
+
...OUTPUT_OPTIONS,
|
|
661
|
+
help: { type: "boolean", short: "h", description: "show this help" }
|
|
662
|
+
};
|
|
663
|
+
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
664
|
+
function printError(prefix, message, hint, cause) {
|
|
665
|
+
const colors = paint(process6.stderr);
|
|
666
|
+
const styled = takesControlCodes(process6.stderr);
|
|
667
|
+
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
668
|
+
const under = (label, text, tint) => text === undefined ? "" : `
|
|
669
|
+
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
670
|
+
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
671
|
+
}
|
|
672
|
+
function printJsonError(message, hint, cause) {
|
|
673
|
+
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
674
|
+
}
|
|
675
|
+
function wantsJson(argv) {
|
|
676
|
+
const end = argv.indexOf("--");
|
|
677
|
+
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
678
|
+
}
|
|
679
|
+
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
680
|
+
if (error instanceof HelpShown)
|
|
681
|
+
return 0;
|
|
682
|
+
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
683
|
+
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
684
|
+
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
685
|
+
if (error instanceof UsageError)
|
|
686
|
+
noteUsageError(error.message);
|
|
687
|
+
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
688
|
+
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
689
|
+
return error instanceof Exit ? error.code : 1;
|
|
690
|
+
}
|
|
691
|
+
var COMPLETE = "__complete";
|
|
692
|
+
var FILES = "__files__";
|
|
693
|
+
async function completingOf(run) {
|
|
694
|
+
completion.active = true;
|
|
695
|
+
try {
|
|
696
|
+
await run([]);
|
|
697
|
+
} catch (error) {
|
|
698
|
+
if (error instanceof Completing)
|
|
699
|
+
return error;
|
|
700
|
+
} finally {
|
|
701
|
+
completion.active = false;
|
|
702
|
+
}
|
|
703
|
+
return new Completing({});
|
|
704
|
+
}
|
|
705
|
+
function candidateLine(candidate) {
|
|
706
|
+
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
707
|
+
}
|
|
708
|
+
function positionalBeingTyped(before, { options, positionals }) {
|
|
709
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
710
|
+
let index = 0;
|
|
711
|
+
let at = 0;
|
|
712
|
+
while (at < before.length) {
|
|
713
|
+
const word = before[at];
|
|
714
|
+
if (word === "--") {
|
|
715
|
+
index += before.length - at - 1;
|
|
716
|
+
break;
|
|
717
|
+
}
|
|
718
|
+
if (!word.startsWith("-"))
|
|
719
|
+
index++;
|
|
720
|
+
else if (takesValue(word))
|
|
721
|
+
at++;
|
|
722
|
+
at++;
|
|
723
|
+
}
|
|
724
|
+
const last = positionals.at(-1);
|
|
725
|
+
if (index < positionals.length)
|
|
726
|
+
return positionals[index];
|
|
727
|
+
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
728
|
+
}
|
|
729
|
+
async function leafCandidates(run, words) {
|
|
730
|
+
const completing = await completingOf(run);
|
|
731
|
+
if ((words.at(-1) ?? "").startsWith("-"))
|
|
732
|
+
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
733
|
+
const flag = words.at(-2);
|
|
734
|
+
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
735
|
+
if (option?.type === "string") {
|
|
736
|
+
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
737
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
738
|
+
}
|
|
739
|
+
const name = positionalBeingTyped(words.slice(0, -1), completing);
|
|
740
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
741
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
742
|
+
}
|
|
743
|
+
async function printCandidates(found) {
|
|
744
|
+
for (const line of await found)
|
|
745
|
+
console.log(line);
|
|
746
|
+
return 0;
|
|
747
|
+
}
|
|
748
|
+
function packageVersion(entry = Bun.main) {
|
|
749
|
+
for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
|
|
750
|
+
try {
|
|
751
|
+
const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
|
|
752
|
+
if (typeof version === "string")
|
|
753
|
+
return version;
|
|
754
|
+
} catch {}
|
|
755
|
+
if (dirname2(dir) === dir)
|
|
756
|
+
return "0.0.0";
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
async function runMain({ name, version, run, redact, usage }, argv = process6.argv.slice(2)) {
|
|
760
|
+
if (argv[0] === COMPLETE)
|
|
761
|
+
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
762
|
+
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
763
|
+
console.log(version ?? packageVersion());
|
|
764
|
+
return 0;
|
|
765
|
+
}
|
|
766
|
+
let code;
|
|
767
|
+
try {
|
|
768
|
+
code = await run(argv);
|
|
769
|
+
} catch (error) {
|
|
770
|
+
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
771
|
+
}
|
|
772
|
+
if (usage !== false) {
|
|
773
|
+
try {
|
|
774
|
+
recordUsage(usageEntry(name, undefined, argv, code));
|
|
775
|
+
} catch {}
|
|
776
|
+
}
|
|
777
|
+
return code;
|
|
778
|
+
}
|
|
779
|
+
// ../kit/src/secrets.ts
|
|
780
|
+
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
781
|
+
// ../kit/src/sessions.ts
|
|
782
|
+
var {Glob } = globalThis.Bun;
|
|
783
|
+
var SESSION_FILES = new Glob("*.json");
|
|
784
|
+
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
785
|
+
// src/terminal.ts
|
|
786
|
+
import { openSync } from "fs";
|
|
787
|
+
import process9 from "process";
|
|
788
|
+
import tty from "tty";
|
|
789
|
+
|
|
790
|
+
// src/preview.ts
|
|
791
|
+
import process8 from "process";
|
|
792
|
+
|
|
793
|
+
// ../kit/src/shell.ts
|
|
794
|
+
var SEPARATORS = new Set([`
|
|
795
|
+
`, ";", "|"]);
|
|
796
|
+
var PLAIN_BREAKERS = new Set(["<", ">", "(", ")", "&", "|"]);
|
|
797
|
+
var GLOB_CHARS = new Set(["*", "?", "["]);
|
|
798
|
+
var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
|
|
799
|
+
var SAFE_WORD = /^[\w@%+=:,./-]+$/;
|
|
800
|
+
var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
|
|
801
|
+
var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
|
|
802
|
+
var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
|
|
803
|
+
var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
|
|
804
|
+
var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
|
|
805
|
+
var POWERSHELL = new Set(["pwsh", "powershell"]);
|
|
806
|
+
var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
|
|
807
|
+
var FISH_VALUE_OPTIONS = new Set(["-C", "--init-command"]);
|
|
808
|
+
var PRINTERS = new Set(["echo", "printf"]);
|
|
809
|
+
var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
|
|
810
|
+
function wrapper(short = "", long = [], operands = 0, runsString = false) {
|
|
811
|
+
return { short, long, operands, runsString };
|
|
812
|
+
}
|
|
813
|
+
var WRAPPERS = new Map([
|
|
814
|
+
["command", wrapper()],
|
|
815
|
+
["builtin", wrapper()],
|
|
816
|
+
["nohup", wrapper()],
|
|
817
|
+
["setsid", wrapper()],
|
|
818
|
+
["busybox", wrapper()],
|
|
819
|
+
["exec", wrapper("a")],
|
|
820
|
+
["time", wrapper("fo", ["--format", "--output"])],
|
|
821
|
+
["env", wrapper("uCS", ["--unset", "--chdir", "--split-string", "--argv0"])],
|
|
822
|
+
["sudo", wrapper("ughpCTrtUDR", ["--user", "--group", "--host", "--prompt", "--close-from", "--command-timeout", "--role", "--type", "--other-user", "--chdir", "--chroot"])],
|
|
823
|
+
["doas", wrapper("uC")],
|
|
824
|
+
["timeout", wrapper("sk", ["--signal", "--kill-after"], 1)],
|
|
825
|
+
["nice", wrapper("n", ["--adjustment"])],
|
|
826
|
+
["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
|
|
827
|
+
["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
|
|
828
|
+
["chroot", wrapper("", ["--userspec", "--groups"], 1)],
|
|
829
|
+
["watch", wrapper("n", ["--interval"], 0, true)],
|
|
830
|
+
["flock", wrapper("wE", ["--timeout", "--conflict-exit-code"], 1)],
|
|
831
|
+
["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
|
|
832
|
+
["unbuffer", wrapper()],
|
|
833
|
+
["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
|
|
834
|
+
["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
|
|
835
|
+
]);
|
|
836
|
+
function shellQuote(word) {
|
|
837
|
+
return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
// src/score.ts
|
|
841
|
+
var MATCH = 16;
|
|
842
|
+
var CONSECUTIVE = 12;
|
|
843
|
+
var BOUNDARY = 10;
|
|
844
|
+
var PREFIX = 8;
|
|
845
|
+
var GAP = 1;
|
|
846
|
+
var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
|
|
847
|
+
var UPPER = /\p{Lu}/u;
|
|
848
|
+
var LOWER = /\p{Ll}/u;
|
|
849
|
+
var NONE = Number.NEGATIVE_INFINITY;
|
|
850
|
+
function startsWord(text, index) {
|
|
851
|
+
if (index === 0)
|
|
852
|
+
return true;
|
|
853
|
+
const before = text[index - 1];
|
|
854
|
+
return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
|
|
855
|
+
}
|
|
856
|
+
function fuzzy(query, text) {
|
|
857
|
+
if (query === "")
|
|
858
|
+
return { score: 0, positions: [] };
|
|
859
|
+
const exact = query !== query.toLowerCase();
|
|
860
|
+
const needle = exact ? query : query.toLowerCase();
|
|
861
|
+
const haystack = exact ? text : text.toLowerCase();
|
|
862
|
+
if (haystack.length !== text.length || needle.length > haystack.length)
|
|
863
|
+
return;
|
|
864
|
+
const width = haystack.length;
|
|
865
|
+
const best = Array.from({ length: needle.length }, () => new Array(width).fill(NONE));
|
|
866
|
+
const from = Array.from({ length: needle.length }, () => new Array(width).fill(-1));
|
|
867
|
+
for (let j = 0;j < needle.length; j++) {
|
|
868
|
+
let run = NONE;
|
|
869
|
+
let runAt = -1;
|
|
870
|
+
for (let i = j;i < width; i++) {
|
|
871
|
+
if (j > 0 && i - 2 >= j - 1) {
|
|
872
|
+
const candidate = best[j - 1][i - 2] + (i - 2) * GAP;
|
|
873
|
+
if (candidate > run) {
|
|
874
|
+
run = candidate;
|
|
875
|
+
runAt = i - 2;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
if (haystack[i] !== needle[j])
|
|
879
|
+
continue;
|
|
880
|
+
const here = MATCH + (startsWord(text, i) ? BOUNDARY : 0) + (i === 0 ? PREFIX : 0);
|
|
881
|
+
if (j === 0) {
|
|
882
|
+
best[0][i] = here - i * GAP;
|
|
883
|
+
continue;
|
|
884
|
+
}
|
|
885
|
+
const joined = best[j - 1][i - 1] + CONSECUTIVE;
|
|
886
|
+
const skipped = run - (i - 1) * GAP;
|
|
887
|
+
if (joined > NONE && joined >= skipped) {
|
|
888
|
+
best[j][i] = joined + here;
|
|
889
|
+
from[j][i] = i - 1;
|
|
890
|
+
} else if (skipped > NONE) {
|
|
891
|
+
best[j][i] = skipped + here;
|
|
892
|
+
from[j][i] = runAt;
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
const last = best[needle.length - 1];
|
|
897
|
+
let end = -1;
|
|
898
|
+
for (let i = 0;i < width; i++) {
|
|
899
|
+
if (last[i] > NONE && (end === -1 || last[i] > last[end]))
|
|
900
|
+
end = i;
|
|
901
|
+
}
|
|
902
|
+
if (end === -1)
|
|
903
|
+
return;
|
|
904
|
+
const positions = [];
|
|
905
|
+
for (let j = needle.length - 1, i = end;j >= 0; j--) {
|
|
906
|
+
positions.unshift(i);
|
|
907
|
+
i = from[j][i];
|
|
908
|
+
}
|
|
909
|
+
return { score: last[end], positions };
|
|
910
|
+
}
|
|
911
|
+
function rank(query, lines) {
|
|
912
|
+
if (query === "")
|
|
913
|
+
return lines.map((_, index) => ({ index, positions: [] }));
|
|
914
|
+
const found = [];
|
|
915
|
+
for (const [index, line] of lines.entries()) {
|
|
916
|
+
const match = fuzzy(query, line);
|
|
917
|
+
if (match !== undefined)
|
|
918
|
+
found.push({ index, positions: match.positions, score: match.score });
|
|
919
|
+
}
|
|
920
|
+
return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
// src/state.ts
|
|
924
|
+
var ANSI2 = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
|
|
925
|
+
var CONTROL = /[\x00-\x1F\x7F-\x9F]/g;
|
|
926
|
+
var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
|
|
927
|
+
var PASTE_START = "\x1B[200~";
|
|
928
|
+
var PASTE_END = "\x1B[201~";
|
|
929
|
+
var LAST_WORD = /\S*\s*$/;
|
|
930
|
+
var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
|
|
931
|
+
var KEYS = {
|
|
932
|
+
"\x1B[A": "up",
|
|
933
|
+
"\x1BOA": "up",
|
|
934
|
+
"\x10": "up",
|
|
935
|
+
"\x1B[B": "down",
|
|
936
|
+
"\x1BOB": "down",
|
|
937
|
+
"\x0E": "down",
|
|
938
|
+
"\r": "enter",
|
|
939
|
+
"\n": "enter",
|
|
940
|
+
"\x03": "cancel",
|
|
941
|
+
"\x1B": "cancel",
|
|
942
|
+
"\x7F": "erase",
|
|
943
|
+
"\b": "erase",
|
|
944
|
+
"\x15": "clear",
|
|
945
|
+
"\x17": "word",
|
|
946
|
+
"\t": "tab"
|
|
947
|
+
};
|
|
948
|
+
function displayed(line) {
|
|
949
|
+
return line.replace(ANSI2, "").replace(CONTROL, " ");
|
|
950
|
+
}
|
|
951
|
+
function parseKeys(input, paste = { active: false }) {
|
|
952
|
+
return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
|
|
953
|
+
const key = KEYS[sequence];
|
|
954
|
+
if (sequence === PASTE_START || sequence === PASTE_END) {
|
|
955
|
+
paste.active = sequence === PASTE_START;
|
|
956
|
+
return [];
|
|
957
|
+
}
|
|
958
|
+
if (paste.active && (sequence === "\r" || sequence === `
|
|
959
|
+
`))
|
|
960
|
+
return [];
|
|
961
|
+
if (key !== undefined)
|
|
962
|
+
return [key];
|
|
963
|
+
return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
function createState(lines, { multi = false, prompt = "> ", query = "" } = {}) {
|
|
967
|
+
const items = lines.map(displayed);
|
|
968
|
+
return { lines, items, query, matches: rank(query, items), cursor: 0, marked: new Set, multi, prompt, done: undefined };
|
|
969
|
+
}
|
|
970
|
+
function withQuery(state, query) {
|
|
971
|
+
return { ...state, query, matches: rank(query, state.items), cursor: 0 };
|
|
972
|
+
}
|
|
973
|
+
function move(state, by) {
|
|
974
|
+
return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
|
|
975
|
+
}
|
|
976
|
+
function highlighted(state) {
|
|
977
|
+
return state.matches[state.cursor]?.index;
|
|
978
|
+
}
|
|
979
|
+
function press(state, key) {
|
|
980
|
+
if (state.done !== undefined)
|
|
981
|
+
return state;
|
|
982
|
+
if (typeof key === "object")
|
|
983
|
+
return withQuery(state, state.query + key.text);
|
|
984
|
+
switch (key) {
|
|
985
|
+
case "up":
|
|
986
|
+
return move(state, -1);
|
|
987
|
+
case "down":
|
|
988
|
+
return move(state, 1);
|
|
989
|
+
case "cancel":
|
|
990
|
+
return { ...state, done: "cancel" };
|
|
991
|
+
case "erase":
|
|
992
|
+
return withQuery(state, [...state.query].slice(0, -1).join(""));
|
|
993
|
+
case "clear":
|
|
994
|
+
return withQuery(state, "");
|
|
995
|
+
case "word":
|
|
996
|
+
return withQuery(state, state.query.replace(LAST_WORD, ""));
|
|
997
|
+
case "enter":
|
|
998
|
+
return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
|
|
999
|
+
case "tab": {
|
|
1000
|
+
const at = highlighted(state);
|
|
1001
|
+
if (!state.multi || at === undefined)
|
|
1002
|
+
return state;
|
|
1003
|
+
const marked = new Set(state.marked);
|
|
1004
|
+
if (!marked.delete(at))
|
|
1005
|
+
marked.add(at);
|
|
1006
|
+
return move({ ...state, marked }, 1);
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
function chosen(state) {
|
|
1011
|
+
if (state.marked.size > 0)
|
|
1012
|
+
return state.lines.filter((_, index) => state.marked.has(index));
|
|
1013
|
+
const at = highlighted(state);
|
|
1014
|
+
return at === undefined ? [] : [state.lines[at]];
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
// src/preview.ts
|
|
1018
|
+
var PREVIEW_BYTES = 64 * 1024;
|
|
1019
|
+
var PREVIEW_LINES = 200;
|
|
1020
|
+
var PREVIEW_TIMEOUT_MS = 3000;
|
|
1021
|
+
function previewCommand(template, line) {
|
|
1022
|
+
return template.split("{}").join(shellQuote(line));
|
|
1023
|
+
}
|
|
1024
|
+
function previewLines(output) {
|
|
1025
|
+
const lines = output.split(`
|
|
1026
|
+
`);
|
|
1027
|
+
if (lines.at(-1) === "")
|
|
1028
|
+
lines.pop();
|
|
1029
|
+
return lines.slice(0, PREVIEW_LINES).map(displayed);
|
|
1030
|
+
}
|
|
1031
|
+
async function runPreview(template, line, signal) {
|
|
1032
|
+
const proc = Bun.spawn(["sh", "-c", `exec 2>&1
|
|
1033
|
+
${previewCommand(template, line)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
|
|
1034
|
+
const stop = () => {
|
|
1035
|
+
try {
|
|
1036
|
+
process8.kill(-proc.pid, "SIGKILL");
|
|
1037
|
+
} catch {
|
|
1038
|
+
proc.kill();
|
|
1039
|
+
}
|
|
1040
|
+
};
|
|
1041
|
+
const timer = setTimeout(stop, PREVIEW_TIMEOUT_MS);
|
|
1042
|
+
const chunks = [];
|
|
1043
|
+
let size = 0;
|
|
1044
|
+
signal.addEventListener("abort", stop);
|
|
1045
|
+
try {
|
|
1046
|
+
for await (const chunk of proc.stdout) {
|
|
1047
|
+
chunks.push(chunk);
|
|
1048
|
+
size += chunk.length;
|
|
1049
|
+
if (size >= PREVIEW_BYTES) {
|
|
1050
|
+
stop();
|
|
1051
|
+
break;
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
} finally {
|
|
1055
|
+
clearTimeout(timer);
|
|
1056
|
+
signal.removeEventListener("abort", stop);
|
|
1057
|
+
}
|
|
1058
|
+
return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
// src/view.ts
|
|
1062
|
+
var MIN_HEIGHT = 4;
|
|
1063
|
+
var PREVIEW_MIN_COLUMNS = 80;
|
|
1064
|
+
var SEPARATOR = " \u2502 ";
|
|
1065
|
+
var HEIGHT = /^(\d+)(%?)$/;
|
|
1066
|
+
var DEFAULT_HEIGHT = { percent: 40 };
|
|
1067
|
+
function parseHeight(text) {
|
|
1068
|
+
const found = HEIGHT.exec(text);
|
|
1069
|
+
if (found === null || Number(found[1]) < 1)
|
|
1070
|
+
return;
|
|
1071
|
+
return found[2] === "%" ? { percent: Math.min(100, Number(found[1])) } : { lines: Number(found[1]) };
|
|
1072
|
+
}
|
|
1073
|
+
function layoutFor(size, height, previewing) {
|
|
1074
|
+
const wanted = "lines" in height ? height.lines : Math.round(size.rows * height.percent / 100);
|
|
1075
|
+
const rows = Math.min(size.rows, Math.max(MIN_HEIGHT, wanted));
|
|
1076
|
+
const split = previewing && size.columns >= PREVIEW_MIN_COLUMNS;
|
|
1077
|
+
const listWidth = split ? Math.floor(size.columns / 2) : size.columns;
|
|
1078
|
+
return { height: rows, listWidth, previewWidth: split ? size.columns - listWidth - SEPARATOR.length : 0 };
|
|
1079
|
+
}
|
|
1080
|
+
function fit(text, width, plain, mark = plain, marked = new Set) {
|
|
1081
|
+
const room = Bun.stringWidth(text) > width ? width - 1 : width;
|
|
1082
|
+
let out = "";
|
|
1083
|
+
let used = 0;
|
|
1084
|
+
let at = 0;
|
|
1085
|
+
for (const char of text) {
|
|
1086
|
+
const size = Bun.stringWidth(char);
|
|
1087
|
+
if (used + size > room)
|
|
1088
|
+
break;
|
|
1089
|
+
out += (marked.has(at) ? mark : plain)(char);
|
|
1090
|
+
used += size;
|
|
1091
|
+
at += char.length;
|
|
1092
|
+
}
|
|
1093
|
+
if (room < width) {
|
|
1094
|
+
out += plain("\u2026");
|
|
1095
|
+
used += 1;
|
|
1096
|
+
}
|
|
1097
|
+
return { text: out, width: used };
|
|
1098
|
+
}
|
|
1099
|
+
var identity = (text) => text;
|
|
1100
|
+
function caretColumn(state, layout) {
|
|
1101
|
+
return Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + Bun.stringWidth(state.query) + 1);
|
|
1102
|
+
}
|
|
1103
|
+
function listLines(state, layout, theme) {
|
|
1104
|
+
const rows = layout.height - 2;
|
|
1105
|
+
const prefixWidth = state.multi ? 4 : 2;
|
|
1106
|
+
const top = Math.max(0, Math.min(state.cursor - Math.floor(rows / 2), state.matches.length - rows));
|
|
1107
|
+
const marks = state.marked.size > 0 ? ` (${state.marked.size} marked)` : "";
|
|
1108
|
+
const promptWidth = Bun.stringWidth(state.prompt);
|
|
1109
|
+
const query = fit(state.query, Math.max(1, layout.listWidth - promptWidth), identity);
|
|
1110
|
+
const count = fit(` ${state.matches.length}/${state.items.length}${marks}`, layout.listWidth, theme.label);
|
|
1111
|
+
const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count];
|
|
1112
|
+
if (state.matches.length === 0)
|
|
1113
|
+
lines.push(fit(" no match", layout.listWidth, theme.label));
|
|
1114
|
+
for (const [offset, match] of state.matches.slice(top, top + rows).entries()) {
|
|
1115
|
+
const current = top + offset === state.cursor;
|
|
1116
|
+
const pointer = current ? theme.accent("\u276F") : " ";
|
|
1117
|
+
const mark = state.multi ? `${state.marked.has(match.index) ? theme.id("\u25CF") : " "} ` : "";
|
|
1118
|
+
const text = fit(state.items[match.index], layout.listWidth - prefixWidth, current ? theme.value : identity, theme.accent, new Set(match.positions));
|
|
1119
|
+
lines.push({ text: `${pointer} ${mark}${text.text}`, width: prefixWidth + text.width });
|
|
1120
|
+
}
|
|
1121
|
+
return lines;
|
|
1122
|
+
}
|
|
1123
|
+
function render(state, layout, theme, preview = []) {
|
|
1124
|
+
const left = listLines(state, layout, theme);
|
|
1125
|
+
return Array.from({ length: layout.height }, (_, row) => {
|
|
1126
|
+
const list = left[row] ?? { text: "", width: 0 };
|
|
1127
|
+
if (layout.previewWidth === 0)
|
|
1128
|
+
return list.text;
|
|
1129
|
+
return `${list.text}${" ".repeat(Math.max(0, layout.listWidth - list.width))}${theme.label(SEPARATOR)}${fit(preview[row] ?? "", layout.previewWidth, identity).text}`;
|
|
1130
|
+
});
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
// src/terminal.ts
|
|
1134
|
+
var PREVIEW_DELAY_MS = 120;
|
|
1135
|
+
var HIDE_CURSOR = "\x1B[?25l";
|
|
1136
|
+
var SHOW_CURSOR = "\x1B[?25h";
|
|
1137
|
+
var PASTE_ON = "\x1B[?2004h";
|
|
1138
|
+
var PASTE_OFF = "\x1B[?2004l";
|
|
1139
|
+
var CLEAR_BELOW = "\r\x1B[J";
|
|
1140
|
+
var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
1141
|
+
function themeFor(stream) {
|
|
1142
|
+
return { accent: role("accent", stream), label: role("label", stream), value: role("value", stream), id: role("id", stream) };
|
|
1143
|
+
}
|
|
1144
|
+
function up(lines) {
|
|
1145
|
+
return lines > 0 ? `\x1B[${lines}A` : "";
|
|
1146
|
+
}
|
|
1147
|
+
async function choose(lines, settings) {
|
|
1148
|
+
let input;
|
|
1149
|
+
try {
|
|
1150
|
+
input = new tty.ReadStream(openSync("/dev/tty", "r"));
|
|
1151
|
+
} catch {
|
|
1152
|
+
return fail("no terminal to read keys from (/dev/tty)");
|
|
1153
|
+
}
|
|
1154
|
+
const out = process9.stderr;
|
|
1155
|
+
const theme = themeFor(out);
|
|
1156
|
+
let state = createState(lines, settings);
|
|
1157
|
+
let preview = [];
|
|
1158
|
+
let reserved = 0;
|
|
1159
|
+
let previewTimer;
|
|
1160
|
+
let previewing = new AbortController;
|
|
1161
|
+
let shownLine;
|
|
1162
|
+
let finish;
|
|
1163
|
+
let restored = false;
|
|
1164
|
+
function draw(clear = false) {
|
|
1165
|
+
const layout = layoutFor({ columns: out.columns || 80, rows: out.rows || 24 }, settings.height, settings.preview !== undefined);
|
|
1166
|
+
let frame = HIDE_CURSOR;
|
|
1167
|
+
if (reserved !== layout.height || clear) {
|
|
1168
|
+
frame += CLEAR_BELOW + `
|
|
1169
|
+
`.repeat(layout.height - 1) + up(layout.height - 1);
|
|
1170
|
+
reserved = layout.height;
|
|
1171
|
+
}
|
|
1172
|
+
frame += `\r${render(state, layout, theme, preview).map((line) => `\x1B[2K${line}`).join(`
|
|
1173
|
+
`)}${up(layout.height - 1)}\r\x1B[${caretColumn(state, layout)}G${SHOW_CURSOR}`;
|
|
1174
|
+
out.write(frame);
|
|
1175
|
+
}
|
|
1176
|
+
function refreshPreview() {
|
|
1177
|
+
const at = highlighted(state);
|
|
1178
|
+
if (settings.preview === undefined || at === shownLine)
|
|
1179
|
+
return;
|
|
1180
|
+
shownLine = at;
|
|
1181
|
+
clearTimeout(previewTimer);
|
|
1182
|
+
previewing.abort();
|
|
1183
|
+
previewing = new AbortController;
|
|
1184
|
+
if (at === undefined) {
|
|
1185
|
+
preview = [];
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
const { signal } = previewing;
|
|
1189
|
+
const template = settings.preview;
|
|
1190
|
+
const line = state.lines[at];
|
|
1191
|
+
async function show() {
|
|
1192
|
+
const shown = await runPreview(template, line, signal);
|
|
1193
|
+
if (!signal.aborted) {
|
|
1194
|
+
preview = shown;
|
|
1195
|
+
draw();
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
previewTimer = setTimeout(() => void show(), PREVIEW_DELAY_MS);
|
|
1199
|
+
}
|
|
1200
|
+
function restore() {
|
|
1201
|
+
if (restored)
|
|
1202
|
+
return;
|
|
1203
|
+
restored = true;
|
|
1204
|
+
clearTimeout(previewTimer);
|
|
1205
|
+
previewing.abort();
|
|
1206
|
+
out.write(`${CLEAR_BELOW}${PASTE_OFF}${SHOW_CURSOR}`);
|
|
1207
|
+
out.off("resize", onResize);
|
|
1208
|
+
try {
|
|
1209
|
+
input.setRawMode(false);
|
|
1210
|
+
} finally {
|
|
1211
|
+
input.destroy();
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
const paste = { active: false };
|
|
1215
|
+
function onResize() {
|
|
1216
|
+
draw(true);
|
|
1217
|
+
}
|
|
1218
|
+
function onData(chunk) {
|
|
1219
|
+
for (const key of parseKeys(chunk.toString(), paste)) {
|
|
1220
|
+
state = press(state, key);
|
|
1221
|
+
if (state.done !== undefined) {
|
|
1222
|
+
finish?.();
|
|
1223
|
+
return;
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
refreshPreview();
|
|
1227
|
+
draw();
|
|
1228
|
+
}
|
|
1229
|
+
const stop = () => {
|
|
1230
|
+
state = { ...state, done: "cancel" };
|
|
1231
|
+
finish?.();
|
|
1232
|
+
};
|
|
1233
|
+
const ended = new Promise((resolve) => {
|
|
1234
|
+
finish = resolve;
|
|
1235
|
+
});
|
|
1236
|
+
process9.once("exit", restore);
|
|
1237
|
+
for (const signal of SIGNALS)
|
|
1238
|
+
process9.once(signal, stop);
|
|
1239
|
+
try {
|
|
1240
|
+
input.setRawMode(true);
|
|
1241
|
+
out.write(PASTE_ON);
|
|
1242
|
+
out.on("resize", onResize);
|
|
1243
|
+
input.on("data", onData);
|
|
1244
|
+
refreshPreview();
|
|
1245
|
+
draw(true);
|
|
1246
|
+
await ended;
|
|
1247
|
+
} finally {
|
|
1248
|
+
for (const signal of SIGNALS)
|
|
1249
|
+
process9.off(signal, stop);
|
|
1250
|
+
process9.off("exit", restore);
|
|
1251
|
+
restore();
|
|
1252
|
+
}
|
|
1253
|
+
return state.done === "accept" ? chosen(state) : undefined;
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
// src/pick.ts
|
|
1257
|
+
var USAGE = `pick [options]: a fuzzy selector, the lines on stdin in, the chosen one on stdout out
|
|
1258
|
+
|
|
1259
|
+
Type to filter: the query matches as a subsequence, best matches first (a word start, a run of characters or a prefix scores higher; a lowercase query ignores case, an uppercase letter makes it exact). Up and down or ctrl-p and ctrl-n move, enter picks, esc and ctrl-c cancel, ctrl-u clears the query.
|
|
1260
|
+
The keys are read from the terminal and the selector is drawn on stderr, so \`pick\` in a pipe or a command substitution prints only the choice. With --multi, tab marks the highlighted line and enter prints the marked lines in input order (the highlighted one when none is marked).
|
|
1261
|
+
--preview runs a command for the highlighted line, \`{}\` standing for it shell-quoted, in a pane on the right when the terminal is at least 80 columns wide; its output is cut at 64 KiB and 200 lines.
|
|
1262
|
+
|
|
1263
|
+
Exits 0 when it printed a choice, 1 when cancelled or there are no lines, 2 on a usage error or without a terminal.`;
|
|
1264
|
+
var OPTIONS = {
|
|
1265
|
+
multi: { type: "boolean", short: "m", description: "tab marks several lines, enter prints them" },
|
|
1266
|
+
prompt: { type: "string", short: "p", description: "the prompt before the query (> )" },
|
|
1267
|
+
query: { type: "string", short: "q", description: "the query to start with" },
|
|
1268
|
+
preview: { type: "string", description: "a command shown for the highlighted line, {} standing for it" },
|
|
1269
|
+
height: { type: "string", description: "lines or a percentage of the terminal to draw in (40%)" }
|
|
1270
|
+
};
|
|
1271
|
+
async function main(args) {
|
|
1272
|
+
const { values, positionals } = parse(args, USAGE, OPTIONS, { replaces: "fzf for a quick choice in a pipe, select in a shell script", examples: ["git branch --format='%(refname:short)' | pick", "ls | pick --multi --preview 'head -20 {}'"] });
|
|
1273
|
+
if (positionals.length > 0)
|
|
1274
|
+
badUsage("pick takes its lines on stdin, not as arguments");
|
|
1275
|
+
const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
|
|
1276
|
+
if (height === undefined)
|
|
1277
|
+
badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
|
|
1278
|
+
if (!process10.stderr.isTTY)
|
|
1279
|
+
fail("pick draws on stderr and it is not a terminal");
|
|
1280
|
+
if (process10.stdin.isTTY)
|
|
1281
|
+
badUsage("pipe the lines to pick on stdin");
|
|
1282
|
+
const lines = (await Bun.stdin.text()).split(`
|
|
1283
|
+
`).filter((line) => line !== "");
|
|
1284
|
+
if (lines.length === 0)
|
|
1285
|
+
fail("nothing to pick from", 1);
|
|
1286
|
+
const picked = await choose(lines, { multi: values.multi === true, prompt: values.prompt ?? "> ", query: values.query ?? "", height, preview: values.preview });
|
|
1287
|
+
if (picked === undefined)
|
|
1288
|
+
return 1;
|
|
1289
|
+
process10.stdout.write(`${picked.join(`
|
|
1290
|
+
`)}
|
|
1291
|
+
`);
|
|
1292
|
+
return 0;
|
|
1293
|
+
}
|
|
1294
|
+
process10.exitCode = await runMain({ name: "pick", run: main });
|