@kaynooo/cli-check 0.22.2 → 0.22.4
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/chunk-6wcnr992.js +5 -0
- package/dist/chunk-98tbscp4.js +8 -0
- package/dist/chunk-ef4tt9f7.js +10 -0
- package/dist/chunk-m3r6m4gc.js +76 -0
- package/dist/chunk-x48y9p19.js +2 -0
- package/dist/chunk-ykfkfr0c.js +3 -0
- package/dist/cli.js +5 -2675
- package/dist/errs-cli.js +4 -2728
- package/dist/j-cli.js +17 -3453
- package/package.json +15 -8
package/dist/j-cli.js
CHANGED
|
@@ -1,3455 +1,19 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
var
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
function
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
|
|
21
|
-
if (o && !Y.test(t[c.length] ?? " "))
|
|
22
|
-
c = c.replace(Nt, "") || c;
|
|
23
|
-
if (o)
|
|
24
|
-
c = c.trimEnd();
|
|
25
|
-
return s ? (c + n).slice(0, l) : c + n;
|
|
26
|
-
}
|
|
27
|
-
var N, Nt, Y, be, W;
|
|
28
|
-
var init_chunk_rkhsft4a = __esm(() => {
|
|
29
|
-
N = new Map;
|
|
30
|
-
Nt = /\s+\S*$/;
|
|
31
|
-
Y = /\s/;
|
|
32
|
-
be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
|
|
33
|
-
W = new Map;
|
|
34
|
-
});
|
|
35
|
-
|
|
36
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
|
|
37
|
-
var init_text = __esm(() => {
|
|
38
|
-
init_chunk_rkhsft4a();
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
// ../kit/src/mode.ts
|
|
42
|
-
import process2 from "process";
|
|
43
|
-
function isSet(value) {
|
|
44
|
-
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
45
|
-
}
|
|
46
|
-
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
47
|
-
const chosen = env.KIT_MODE;
|
|
48
|
-
if (chosen !== undefined && MODES.has(chosen))
|
|
49
|
-
return chosen;
|
|
50
|
-
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
51
|
-
return "agent";
|
|
52
|
-
if (stream.isTTY === true)
|
|
53
|
-
return "terminal";
|
|
54
|
-
return isSet(env.CI) ? "ci" : "pipe";
|
|
55
|
-
}
|
|
56
|
-
function isInteractive(streams = process2) {
|
|
57
|
-
return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
|
|
58
|
-
}
|
|
59
|
-
var MODES, AGENT_VARIABLES;
|
|
60
|
-
var init_mode = __esm(() => {
|
|
61
|
-
MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
62
|
-
AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
66
|
-
function b(r) {
|
|
67
|
-
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
68
|
-
if (!G2.test(e))
|
|
69
|
-
return [0, 0, 0];
|
|
70
|
-
if (e.length === 3 || e.length === 4)
|
|
71
|
-
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
72
|
-
if (e.length !== 6 && e.length !== 8)
|
|
73
|
-
throw Error(`Invalid hex color length: ${e.length}`);
|
|
74
|
-
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
75
|
-
}
|
|
76
|
-
function C(r, e = globalThis.process?.env ?? {}) {
|
|
77
|
-
if (e.FORCE_COLOR !== undefined)
|
|
78
|
-
return h.has(e.FORCE_COLOR);
|
|
79
|
-
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
80
|
-
return false;
|
|
81
|
-
return r?.isTTY === true;
|
|
82
|
-
}
|
|
83
|
-
function f(r, e = []) {
|
|
84
|
-
let l = "", n = "";
|
|
85
|
-
for (let t = 0, i = e.length;t < i; t++)
|
|
86
|
-
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
87
|
-
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
88
|
-
return new Proxy(c, { get(t, i) {
|
|
89
|
-
let a = B[i];
|
|
90
|
-
if (Array.isArray(a)) {
|
|
91
|
-
let s = g.get(i);
|
|
92
|
-
if (s === undefined)
|
|
93
|
-
s = f(r, [...e, a]), g.set(i, s);
|
|
94
|
-
return s;
|
|
95
|
-
}
|
|
96
|
-
if (typeof a === "function")
|
|
97
|
-
return (...s) => {
|
|
98
|
-
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
99
|
-
if (u === undefined) {
|
|
100
|
-
if (g.size >= 64)
|
|
101
|
-
g.clear();
|
|
102
|
-
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
103
|
-
}
|
|
104
|
-
return u;
|
|
105
|
-
};
|
|
106
|
-
throw Error(`Unknown style: ${String(i)}`);
|
|
107
|
-
} });
|
|
108
|
-
}
|
|
109
|
-
function Fe(r = {}) {
|
|
110
|
-
return f(r);
|
|
111
|
-
}
|
|
112
|
-
var G2, B, h, o;
|
|
113
|
-
var init_chunk_x450vn3m = __esm(() => {
|
|
114
|
-
G2 = /^[a-f0-9]+$/i;
|
|
115
|
-
B = { 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, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
|
|
116
|
-
let [l, n, c] = b(r);
|
|
117
|
-
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
118
|
-
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
119
|
-
h = new Set(["", "1", "2", "3", "true"]);
|
|
120
|
-
o = Fe();
|
|
121
|
-
});
|
|
122
|
-
|
|
123
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
|
|
124
|
-
var init_colors = __esm(() => {
|
|
125
|
-
init_chunk_x450vn3m();
|
|
126
|
-
});
|
|
127
|
-
|
|
128
|
-
// ../kit/src/config.ts
|
|
129
|
-
import { existsSync } from "fs";
|
|
130
|
-
import { dirname, join, resolve } from "path";
|
|
131
|
-
import process3 from "process";
|
|
132
|
-
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
133
|
-
const wanted = typeof names === "string" ? [names] : names;
|
|
134
|
-
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
135
|
-
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
136
|
-
if (found !== undefined)
|
|
137
|
-
return found;
|
|
138
|
-
if (stop(dir) || dirname(dir) === dir)
|
|
139
|
-
return;
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
var init_config = __esm(() => {
|
|
143
|
-
init_args();
|
|
144
|
-
});
|
|
145
|
-
|
|
146
|
-
// ../kit/src/user-config.ts
|
|
147
|
-
import { existsSync as existsSync2, readFileSync } from "fs";
|
|
148
|
-
import { homedir } from "os";
|
|
149
|
-
import { isAbsolute, join as join2 } from "path";
|
|
150
|
-
import process4 from "process";
|
|
151
|
-
function xdgFolder(value, fallback) {
|
|
152
|
-
return value !== undefined && isAbsolute(value) ? value : fallback;
|
|
153
|
-
}
|
|
154
|
-
function configBase(where = {}) {
|
|
155
|
-
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
156
|
-
return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
|
|
157
|
-
}
|
|
158
|
-
function userConfigPath(bin, where = {}) {
|
|
159
|
-
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
160
|
-
}
|
|
161
|
-
function userConfigReadPath(bin, legacy = [], where = {}) {
|
|
162
|
-
const current = userConfigPath(bin, where);
|
|
163
|
-
if (existsSync2(current))
|
|
164
|
-
return current;
|
|
165
|
-
const base = configBase(where);
|
|
166
|
-
return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
|
|
167
|
-
}
|
|
168
|
-
function readUserConfig(bin, where = {}, legacy = []) {
|
|
169
|
-
const path = userConfigReadPath(bin, legacy, where);
|
|
170
|
-
if (!existsSync2(path))
|
|
171
|
-
return {};
|
|
172
|
-
try {
|
|
173
|
-
const parsed = Bun.JSONC.parse(readFileSync(path, "utf8"));
|
|
174
|
-
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
|
|
175
|
-
} catch {
|
|
176
|
-
return {};
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
var init_user_config = () => {};
|
|
180
|
-
|
|
181
|
-
// ../kit/src/theme.ts
|
|
182
|
-
import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
|
|
183
|
-
import { homedir as homedir2 } from "os";
|
|
184
|
-
import { join as join3, resolve as resolve2 } from "path";
|
|
185
|
-
import process5 from "process";
|
|
186
|
-
function isColorSpec(spec) {
|
|
187
|
-
if (typeof spec === "number")
|
|
188
|
-
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
189
|
-
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
190
|
-
}
|
|
191
|
-
function cubeLevel(channel) {
|
|
192
|
-
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
193
|
-
}
|
|
194
|
-
function nearest256(hex) {
|
|
195
|
-
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
196
|
-
const levels = rgb.map(cubeLevel);
|
|
197
|
-
const cube = levels.map((level) => CUBE[level]);
|
|
198
|
-
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
199
|
-
const greyValue = 8 + grey * 10;
|
|
200
|
-
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
201
|
-
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
202
|
-
}
|
|
203
|
-
function hasTrueColor(env) {
|
|
204
|
-
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
205
|
-
}
|
|
206
|
-
function tinted(colors, spec, env = process5.env) {
|
|
207
|
-
if (typeof spec === "number")
|
|
208
|
-
return colors.ansi256(spec);
|
|
209
|
-
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
210
|
-
if (HEX.test(token))
|
|
211
|
-
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
212
|
-
return chain[token] ?? chain;
|
|
213
|
-
}, colors);
|
|
214
|
-
}
|
|
215
|
-
function isRecord(value) {
|
|
216
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
217
|
-
}
|
|
218
|
-
function readThemeFile(path, warn) {
|
|
219
|
-
try {
|
|
220
|
-
const stat = statSync(path, { throwIfNoEntry: false });
|
|
221
|
-
if (stat === undefined)
|
|
222
|
-
return;
|
|
223
|
-
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
224
|
-
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
225
|
-
return;
|
|
226
|
-
}
|
|
227
|
-
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
228
|
-
if (isRecord(parsed))
|
|
229
|
-
return parsed;
|
|
230
|
-
warn(`${path} is not a JSON object, theme ignored`);
|
|
231
|
-
} catch (error) {
|
|
232
|
-
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
233
|
-
}
|
|
234
|
-
return;
|
|
235
|
-
}
|
|
236
|
-
function applyPreset(theme, name, warn, where) {
|
|
237
|
-
if (name === undefined)
|
|
238
|
-
return;
|
|
239
|
-
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
240
|
-
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
241
|
-
return;
|
|
242
|
-
}
|
|
243
|
-
const preset = PRESETS[name];
|
|
244
|
-
Object.assign(theme.colors, preset.colors);
|
|
245
|
-
Object.assign(theme.glyphs, preset.glyphs);
|
|
246
|
-
if (preset.accents !== undefined)
|
|
247
|
-
theme.accents = [...preset.accents];
|
|
248
|
-
if (Object.hasOwn(preset, "gradient"))
|
|
249
|
-
theme.gradient = preset.gradient;
|
|
250
|
-
return name;
|
|
251
|
-
}
|
|
252
|
-
function applyFile(theme, file, where, warn) {
|
|
253
|
-
if (isRecord(file.colors)) {
|
|
254
|
-
for (const [key, value] of Object.entries(file.colors)) {
|
|
255
|
-
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
256
|
-
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
257
|
-
else if (!isColorSpec(value))
|
|
258
|
-
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
259
|
-
else
|
|
260
|
-
theme.colors[key] = value;
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
if (isRecord(file.glyphs)) {
|
|
264
|
-
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
265
|
-
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
266
|
-
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
267
|
-
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
268
|
-
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
269
|
-
else
|
|
270
|
-
theme.glyphs[key] = value;
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
274
|
-
theme.accents = [...file.accents];
|
|
275
|
-
else if (file.accents !== undefined)
|
|
276
|
-
warn(`${where}: accents must be a non-empty list of colours`);
|
|
277
|
-
if (file.gradient === null)
|
|
278
|
-
theme.gradient = undefined;
|
|
279
|
-
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
280
|
-
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
281
|
-
else if (file.gradient !== undefined)
|
|
282
|
-
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
283
|
-
if (isRecord(file.bins)) {
|
|
284
|
-
for (const [bin, value] of Object.entries(file.bins)) {
|
|
285
|
-
if (isColorSpec(value))
|
|
286
|
-
theme.bins[bin] = value;
|
|
287
|
-
else
|
|
288
|
-
warn(`${where}: bin ${bin} has no valid colour`);
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
function endsWalk(home) {
|
|
293
|
-
return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
|
|
294
|
-
}
|
|
295
|
-
function warnOnce(message) {
|
|
296
|
-
if (warned.has(message))
|
|
297
|
-
return;
|
|
298
|
-
warned.add(message);
|
|
299
|
-
console.error(`warning: theme ${message}`);
|
|
300
|
-
}
|
|
301
|
-
function isPath(chosen) {
|
|
302
|
-
return chosen.includes("/") || chosen.endsWith(".json");
|
|
303
|
-
}
|
|
304
|
-
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
305
|
-
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
306
|
-
const sources = [];
|
|
307
|
-
const chosen = env.KIT_THEME ?? "";
|
|
308
|
-
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
309
|
-
if (isPath(chosen))
|
|
310
|
-
wanted.push(resolve2(from, chosen));
|
|
311
|
-
const files = [];
|
|
312
|
-
for (const path of wanted) {
|
|
313
|
-
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
314
|
-
if (path !== undefined && file !== undefined)
|
|
315
|
-
files.push({ path, file });
|
|
316
|
-
}
|
|
317
|
-
let preset = "default";
|
|
318
|
-
if (chosen !== "" && !isPath(chosen)) {
|
|
319
|
-
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
320
|
-
} else {
|
|
321
|
-
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
322
|
-
if (named !== undefined)
|
|
323
|
-
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
324
|
-
}
|
|
325
|
-
for (const { path, file } of files) {
|
|
326
|
-
applyFile(theme, file, path, warn);
|
|
327
|
-
sources.push(path);
|
|
328
|
-
}
|
|
329
|
-
return { theme, sources, preset };
|
|
330
|
-
}
|
|
331
|
-
function activeTheme() {
|
|
332
|
-
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
333
|
-
if (current === undefined || key !== currentKey) {
|
|
334
|
-
current = loadTheme();
|
|
335
|
-
currentKey = key;
|
|
336
|
-
}
|
|
337
|
-
return current;
|
|
338
|
-
}
|
|
339
|
-
var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
|
|
340
|
-
var init_theme = __esm(() => {
|
|
341
|
-
init_config();
|
|
342
|
-
init_user_config();
|
|
343
|
-
ENDS = new Map;
|
|
344
|
-
DEFAULT = {
|
|
345
|
-
colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
|
|
346
|
-
glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
|
|
347
|
-
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
348
|
-
bins: {},
|
|
349
|
-
gradient: ["#c084fc", "#67e8f9"]
|
|
350
|
-
};
|
|
351
|
-
BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
|
|
352
|
-
MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
|
|
353
|
-
ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
354
|
-
PRESETS = {
|
|
355
|
-
default: {},
|
|
356
|
-
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
357
|
-
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
358
|
-
ascii: { glyphs: ASCII }
|
|
359
|
-
};
|
|
360
|
-
STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
|
|
361
|
-
HEX = /^#[0-9a-f]{6}$/i;
|
|
362
|
-
CONTROL = /\p{Cc}/u;
|
|
363
|
-
MAX_FILE_BYTES = 64 * 1024;
|
|
364
|
-
SPACES = /\s+/;
|
|
365
|
-
CUBE = [0, 95, 135, 175, 215, 255];
|
|
366
|
-
warned = new Set;
|
|
367
|
-
});
|
|
368
|
-
|
|
369
|
-
// ../kit/src/style.ts
|
|
370
|
-
import process6 from "process";
|
|
371
|
-
function takesControlCodes(stream, env = process6.env) {
|
|
372
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
373
|
-
}
|
|
374
|
-
function paint(stream, env = process6.env) {
|
|
375
|
-
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
376
|
-
}
|
|
377
|
-
function marked(mark, text, stream, detail, env = process6.env) {
|
|
378
|
-
const colors = paint(stream, env);
|
|
379
|
-
let head = MARK_WORDS[mark];
|
|
380
|
-
if (takesControlCodes(stream, env)) {
|
|
381
|
-
const { theme } = activeTheme();
|
|
382
|
-
head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
|
|
383
|
-
}
|
|
384
|
-
return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
|
|
385
|
-
}
|
|
386
|
-
function warn(text, detail) {
|
|
387
|
-
console.error(marked("warn", text, process6.stderr, detail));
|
|
388
|
-
}
|
|
389
|
-
function role(name, stream, env = process6.env) {
|
|
390
|
-
const colors = paint(stream, env);
|
|
391
|
-
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
392
|
-
}
|
|
393
|
-
function header(bin, context, stream, env = process6.env) {
|
|
394
|
-
if (!takesControlCodes(stream, env))
|
|
395
|
-
return "";
|
|
396
|
-
const colors = paint(stream, env);
|
|
397
|
-
const hash = [...bin].reduce((sum, char) => sum + char.charCodeAt(0), 0);
|
|
398
|
-
const { theme } = activeTheme();
|
|
399
|
-
const spec = theme.bins[bin] ?? theme.accents[hash % theme.accents.length];
|
|
400
|
-
const accent = tinted(typeof spec === "string" && spec.split(" ").includes("bold") ? colors : colors.bold, spec, env);
|
|
401
|
-
return `${accent(bin)}${context === undefined ? "" : colors.dim(` \u203A ${context}`)}`;
|
|
402
|
-
}
|
|
403
|
-
var MARK_WORDS, STATUS_WORDS, STATUS_OF;
|
|
404
|
-
var init_style = __esm(() => {
|
|
405
|
-
init_colors();
|
|
406
|
-
init_mode();
|
|
407
|
-
init_theme();
|
|
408
|
-
MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
|
|
409
|
-
STATUS_WORDS = {
|
|
410
|
-
passed: ["passed", "success", "succeeded", "ok"],
|
|
411
|
-
failed: ["failed", "failure", "error", "errored"],
|
|
412
|
-
running: ["running", "in_progress", "started", "holding"],
|
|
413
|
-
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
414
|
-
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
415
|
-
};
|
|
416
|
-
STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
417
|
-
});
|
|
418
|
-
|
|
419
|
-
// ../kit/src/format.ts
|
|
420
|
-
import process7 from "process";
|
|
421
|
-
function formatSeconds(total) {
|
|
422
|
-
let rest = Math.max(0, Math.round(total));
|
|
423
|
-
const amounts = UNITS.map(([unit, size]) => {
|
|
424
|
-
const amount = Math.floor(rest / size);
|
|
425
|
-
rest -= amount * size;
|
|
426
|
-
return `${amount}${unit}`;
|
|
427
|
-
});
|
|
428
|
-
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
429
|
-
if (first === -1)
|
|
430
|
-
return "0s";
|
|
431
|
-
const next = amounts[first + 1];
|
|
432
|
-
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
433
|
-
}
|
|
434
|
-
function formatDuration(ms) {
|
|
435
|
-
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
436
|
-
}
|
|
437
|
-
function upTo(text, separator) {
|
|
438
|
-
const end = text.indexOf(separator);
|
|
439
|
-
return end === -1 ? text : text.slice(0, end);
|
|
440
|
-
}
|
|
441
|
-
function truncate(text, width) {
|
|
442
|
-
return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
|
|
443
|
-
}
|
|
444
|
-
function textWidth(text) {
|
|
445
|
-
return Bun.stringWidth(text);
|
|
446
|
-
}
|
|
447
|
-
function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
|
|
448
|
-
const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
|
|
449
|
-
if (outputMode(stream, env) === "agent")
|
|
450
|
-
return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
|
|
451
|
-
`);
|
|
452
|
-
const widths = [];
|
|
453
|
-
for (const row of cells) {
|
|
454
|
-
for (const [index, cell] of row.entries())
|
|
455
|
-
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
456
|
-
}
|
|
457
|
-
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
458
|
-
const colors = paint(stream);
|
|
459
|
-
const lines = shown.map((row) => row.map((cell, index) => {
|
|
460
|
-
const width = widths[index] ?? 0;
|
|
461
|
-
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
462
|
-
if (align[index] === "right")
|
|
463
|
-
return `${gap}${cell}`;
|
|
464
|
-
return index === row.length - 1 ? cell : `${cell}${gap}`;
|
|
465
|
-
}).join(" ").trimEnd());
|
|
466
|
-
const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
|
|
467
|
-
return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
|
|
468
|
-
`);
|
|
469
|
-
}
|
|
470
|
-
function narrow(rows, widths, limit) {
|
|
471
|
-
const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
|
|
472
|
-
const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
|
|
473
|
-
const floor = 8;
|
|
474
|
-
while (used() > limit) {
|
|
475
|
-
let widest = -1;
|
|
476
|
-
for (const [index, width] of widths.entries()) {
|
|
477
|
-
if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
|
|
478
|
-
widest = index;
|
|
479
|
-
}
|
|
480
|
-
if (widest === -1)
|
|
481
|
-
break;
|
|
482
|
-
widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
|
|
483
|
-
}
|
|
484
|
-
return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
|
|
485
|
-
}
|
|
486
|
-
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
487
|
-
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
488
|
-
}
|
|
489
|
-
function printJson(value) {
|
|
490
|
-
console.log(jsonText(value));
|
|
491
|
-
}
|
|
492
|
-
var UNITS, LINE_BREAKS, ESCAPE;
|
|
493
|
-
var init_format = __esm(() => {
|
|
494
|
-
init_text();
|
|
495
|
-
init_mode();
|
|
496
|
-
init_style();
|
|
497
|
-
UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
498
|
-
LINE_BREAKS = /\s*\n\s*/g;
|
|
499
|
-
ESCAPE = String.fromCharCode(27);
|
|
500
|
-
});
|
|
501
|
-
|
|
502
|
-
// ../kit/src/help.ts
|
|
503
|
-
import process8 from "process";
|
|
504
|
-
function usageLine(usage, colors = paint(process8.stdout), { summary: withSummary = true } = {}) {
|
|
505
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
506
|
-
`);
|
|
507
|
-
const blank = lines.indexOf("");
|
|
508
|
-
const synopses = blank === -1 ? lines : lines.slice(0, blank);
|
|
509
|
-
const details = blank === -1 ? [] : lines.slice(blank + 1);
|
|
510
|
-
const colon = synopses[0].indexOf(": ");
|
|
511
|
-
const inline = synopses[0].slice(colon + 2);
|
|
512
|
-
const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
|
|
513
|
-
if (colon !== -1)
|
|
514
|
-
synopses[0] = synopses[0].slice(0, colon);
|
|
515
|
-
const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
|
|
516
|
-
`)}`;
|
|
517
|
-
const lead = summary === undefined || !withSummary ? [] : ["", colors.bold(prose(summary, colors))];
|
|
518
|
-
const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
|
|
519
|
-
return [head, ...lead, ...rest].join(`
|
|
520
|
-
`);
|
|
521
|
-
}
|
|
522
|
-
function prose(line, colors) {
|
|
523
|
-
if (colors.cyan("x") === "x")
|
|
524
|
-
return line;
|
|
525
|
-
return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
|
|
526
|
-
}
|
|
527
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [], bin } = {}) {
|
|
528
|
-
const { summary } = description(usage);
|
|
529
|
-
const head = bin === undefined ? [usageLine(usage, colors)] : [`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary === "" ? "" : ` ${summary}`}`, "", usageLine(usage, colors, { summary: false })];
|
|
530
|
-
return [...head, "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
531
|
-
`);
|
|
532
|
-
}
|
|
533
|
-
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
534
|
-
if (exits.length === 0)
|
|
535
|
-
return [];
|
|
536
|
-
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
537
|
-
}
|
|
538
|
-
function wantsHelpJson(env = process8.env) {
|
|
539
|
-
return env.KIT_HELP === "json";
|
|
540
|
-
}
|
|
541
|
-
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
542
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
543
|
-
`);
|
|
544
|
-
const first = lines[0];
|
|
545
|
-
const colon = first.indexOf(": ");
|
|
546
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
547
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
548
|
-
return {
|
|
549
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
550
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
551
|
-
...replaces === undefined ? {} : { replaces },
|
|
552
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
553
|
-
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
554
|
-
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
555
|
-
};
|
|
556
|
-
}
|
|
557
|
-
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
558
|
-
if (examples.length === 0 || outputMode() === "agent")
|
|
559
|
-
return [];
|
|
560
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
561
|
-
}
|
|
562
|
-
function optionRows(options, colors = paint(process8.stdout)) {
|
|
563
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
564
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
565
|
-
const choices = option.choices?.join("|");
|
|
566
|
-
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
567
|
-
const named = inline ? `<${choices}>` : "<value>";
|
|
568
|
-
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
569
|
-
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
570
|
-
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
571
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
572
|
-
});
|
|
573
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
574
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
575
|
-
}
|
|
576
|
-
var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
|
|
577
|
-
var init_help = __esm(() => {
|
|
578
|
-
init_mode();
|
|
579
|
-
init_style();
|
|
580
|
-
OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
581
|
-
USAGE_PREFIX = /^usage:\s*/i;
|
|
582
|
-
FULL_STOP = /\.$/;
|
|
583
|
-
PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
|
|
584
|
-
});
|
|
585
|
-
|
|
586
|
-
// ../kit/src/text.ts
|
|
587
|
-
function stripAnsi(text) {
|
|
588
|
-
return text.replace(ANSI, "");
|
|
589
|
-
}
|
|
590
|
-
function distance(a, b) {
|
|
591
|
-
const left = [...a];
|
|
592
|
-
const right = [...b];
|
|
593
|
-
let before = [];
|
|
594
|
-
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
595
|
-
for (const [i, x] of left.entries()) {
|
|
596
|
-
const current = [i + 1];
|
|
597
|
-
for (const [j, y] of right.entries()) {
|
|
598
|
-
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
599
|
-
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
600
|
-
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
601
|
-
current.push(cost);
|
|
602
|
-
}
|
|
603
|
-
before = previous;
|
|
604
|
-
previous = current;
|
|
605
|
-
}
|
|
606
|
-
return previous[right.length] ?? 0;
|
|
607
|
-
}
|
|
608
|
-
function closest(name, names) {
|
|
609
|
-
const started = names.find((known) => known.startsWith(name));
|
|
610
|
-
if (started !== undefined)
|
|
611
|
-
return started;
|
|
612
|
-
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
613
|
-
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
614
|
-
}
|
|
615
|
-
var ANSI;
|
|
616
|
-
var init_text2 = __esm(() => {
|
|
617
|
-
ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
|
|
618
|
-
});
|
|
619
|
-
|
|
620
|
-
// ../kit/src/input.ts
|
|
621
|
-
import process9 from "process";
|
|
622
|
-
function durationMs(text, unit) {
|
|
623
|
-
if (BARE_DURATION.test(text))
|
|
624
|
-
return Number(text) * UNIT_MS[unit];
|
|
625
|
-
if (!DURATION.test(text))
|
|
626
|
-
return 0;
|
|
627
|
-
let ms = 0;
|
|
628
|
-
for (const [, amount, part] of text.matchAll(DURATION_PART))
|
|
629
|
-
ms += Number(amount) * UNIT_MS[part];
|
|
630
|
-
return ms;
|
|
631
|
-
}
|
|
632
|
-
function duration(value, name, fallback, unit = "s") {
|
|
633
|
-
if (value === undefined)
|
|
634
|
-
return fallback;
|
|
635
|
-
const ms = durationMs(value.trim(), unit);
|
|
636
|
-
if (ms < 1)
|
|
637
|
-
badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
|
|
638
|
-
return ms;
|
|
639
|
-
}
|
|
640
|
-
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
641
|
-
if (path === "-") {
|
|
642
|
-
if (process9.stdin.isTTY)
|
|
643
|
-
fail(noStdin);
|
|
644
|
-
return Bun.stdin.text();
|
|
645
|
-
}
|
|
646
|
-
const file = Bun.file(path);
|
|
647
|
-
if (!await file.exists())
|
|
648
|
-
fail(`no file ${path}`);
|
|
649
|
-
return file.text();
|
|
650
|
-
}
|
|
651
|
-
var BARE_DURATION, DURATION, DURATION_PART, UNIT_MS;
|
|
652
|
-
var init_input = __esm(() => {
|
|
653
|
-
init_args();
|
|
654
|
-
BARE_DURATION = /^\d+(?:\.\d+)?$/;
|
|
655
|
-
DURATION = /^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/;
|
|
656
|
-
DURATION_PART = /(\d+(?:\.\d+)?)(ms|min|[smhd])/g;
|
|
657
|
-
UNIT_MS = { ms: 1, s: 1000, m: 60000, min: 60000, h: 3600000, d: 86400000 };
|
|
658
|
-
});
|
|
659
|
-
|
|
660
|
-
// ../kit/src/args.ts
|
|
661
|
-
import process10 from "process";
|
|
662
|
-
import { parseArgs } from "util";
|
|
663
|
-
function jsonOption(holds) {
|
|
664
|
-
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
665
|
-
}
|
|
666
|
-
function fail(message, code = 2, hint) {
|
|
667
|
-
throw new Exit(message, code, hint);
|
|
668
|
-
}
|
|
669
|
-
function badUsage(message) {
|
|
670
|
-
throw new UsageError(message);
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
class Completing {
|
|
674
|
-
options;
|
|
675
|
-
positionals;
|
|
676
|
-
candidates;
|
|
677
|
-
constructor(options, positionals = [], candidates = {}) {
|
|
678
|
-
this.options = options;
|
|
679
|
-
this.positionals = positionals;
|
|
680
|
-
this.candidates = candidates;
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
function applyOutput(color, plain, env = process10.env) {
|
|
684
|
-
const when = plain === true ? "never" : color ?? "auto";
|
|
685
|
-
if (when === "auto")
|
|
686
|
-
return;
|
|
687
|
-
if (when !== "always" && when !== "never")
|
|
688
|
-
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
689
|
-
if (when === "always") {
|
|
690
|
-
env.FORCE_COLOR = "1";
|
|
691
|
-
delete env.NO_COLOR;
|
|
692
|
-
} else {
|
|
693
|
-
env.NO_COLOR = "1";
|
|
694
|
-
delete env.FORCE_COLOR;
|
|
695
|
-
}
|
|
696
|
-
}
|
|
697
|
-
function parse(args, usage, options, settings = {}) {
|
|
698
|
-
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
699
|
-
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
700
|
-
const listing = listed(all, settings.allowNegative === true);
|
|
701
|
-
if (completion.active)
|
|
702
|
-
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
703
|
-
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
704
|
-
let parsed;
|
|
705
|
-
try {
|
|
706
|
-
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
707
|
-
} catch (error) {
|
|
708
|
-
const message = parseError(error);
|
|
709
|
-
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
710
|
-
}
|
|
711
|
-
const values = parsed.values;
|
|
712
|
-
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
713
|
-
if (values.help === true) {
|
|
714
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, { ...settings, bin: heading.bin }));
|
|
715
|
-
throw new HelpShown;
|
|
716
|
-
}
|
|
717
|
-
checkChoices(parsed.values, all);
|
|
718
|
-
checkConflicts(parsed.values, all);
|
|
719
|
-
if (settings.positionals !== undefined)
|
|
720
|
-
checkPositionals(parsed.positionals, settings.positionals);
|
|
721
|
-
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
722
|
-
}
|
|
723
|
-
function splitRest(args, passes) {
|
|
724
|
-
const separator = passes ? args.indexOf("--") : -1;
|
|
725
|
-
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
726
|
-
}
|
|
727
|
-
function splitTrailing(args, options, count) {
|
|
728
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
729
|
-
let seen = 0;
|
|
730
|
-
if (count === 0)
|
|
731
|
-
return { own: args, rest: undefined };
|
|
732
|
-
for (let at = 0;at < args.length; at++) {
|
|
733
|
-
const word = args[at];
|
|
734
|
-
if (word === "--")
|
|
735
|
-
break;
|
|
736
|
-
if (word.startsWith("-")) {
|
|
737
|
-
if (takesValue(word))
|
|
738
|
-
at++;
|
|
739
|
-
continue;
|
|
740
|
-
}
|
|
741
|
-
seen++;
|
|
742
|
-
if (seen === count)
|
|
743
|
-
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
744
|
-
}
|
|
745
|
-
return { own: args, rest: undefined };
|
|
746
|
-
}
|
|
747
|
-
function listed(options, allowNegative) {
|
|
748
|
-
if (!allowNegative)
|
|
749
|
-
return options;
|
|
750
|
-
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
751
|
-
if (option.type !== "boolean" || option.negative === undefined)
|
|
752
|
-
return [[name, option]];
|
|
753
|
-
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
754
|
-
}));
|
|
755
|
-
}
|
|
756
|
-
function withAliases(args, options) {
|
|
757
|
-
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
758
|
-
if (named.size === 0)
|
|
759
|
-
return args;
|
|
760
|
-
const separator = args.indexOf("--");
|
|
761
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
762
|
-
return [...own.map((arg) => {
|
|
763
|
-
const at = arg.indexOf("=");
|
|
764
|
-
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
765
|
-
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
766
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
767
|
-
}
|
|
768
|
-
function withBare(args, options) {
|
|
769
|
-
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
770
|
-
if (bare.size === 0)
|
|
771
|
-
return args;
|
|
772
|
-
const separator = args.indexOf("--");
|
|
773
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
774
|
-
return [...own.flatMap((arg, index) => {
|
|
775
|
-
const optional = bare.get(arg);
|
|
776
|
-
const next = own[index + 1];
|
|
777
|
-
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
778
|
-
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
779
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
780
|
-
}
|
|
781
|
-
function checkConflicts(values, options) {
|
|
782
|
-
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
783
|
-
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
784
|
-
const other = given(name) ? conflicts.find(given) : undefined;
|
|
785
|
-
if (other !== undefined)
|
|
786
|
-
badUsage(`--${name} cannot be used with --${other}`);
|
|
787
|
-
}
|
|
788
|
-
}
|
|
789
|
-
function checkChoices(values, options) {
|
|
790
|
-
for (const [name, option] of Object.entries(options)) {
|
|
791
|
-
if (option.choices === undefined)
|
|
792
|
-
continue;
|
|
793
|
-
const given = values[name];
|
|
794
|
-
for (const value of Array.isArray(given) ? given : [given]) {
|
|
795
|
-
if (typeof value === "string")
|
|
796
|
-
oneOf(value, name, option.choices);
|
|
797
|
-
}
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
function oneOf(value, name, choices) {
|
|
801
|
-
if (!choices.includes(value))
|
|
802
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
803
|
-
return value;
|
|
804
|
-
}
|
|
805
|
-
function checkPositionals(given, names) {
|
|
806
|
-
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
807
|
-
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
808
|
-
if (given.length < required)
|
|
809
|
-
badUsage(`missing ${names[given.length]}`);
|
|
810
|
-
if (!variadic && given.length > names.length)
|
|
811
|
-
badUsage(`unexpected argument ${given[names.length]}`);
|
|
812
|
-
}
|
|
813
|
-
function joinDashValues(args, options) {
|
|
814
|
-
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
815
|
-
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
816
|
-
const joined = [];
|
|
817
|
-
for (let i = 0;i < args.length; i++) {
|
|
818
|
-
const arg = args[i] ?? "";
|
|
819
|
-
if (arg === "--")
|
|
820
|
-
return [...joined, ...args.slice(i)];
|
|
821
|
-
const name = longOf.get(arg);
|
|
822
|
-
const next = args[i + 1];
|
|
823
|
-
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
824
|
-
joined.push(`--${name}=${next}`);
|
|
825
|
-
i++;
|
|
826
|
-
} else {
|
|
827
|
-
joined.push(arg);
|
|
828
|
-
}
|
|
829
|
-
}
|
|
830
|
-
return joined;
|
|
831
|
-
}
|
|
832
|
-
function parseError(error) {
|
|
833
|
-
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
834
|
-
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
835
|
-
}
|
|
836
|
-
function nearestOption(message, options, allowNegative) {
|
|
837
|
-
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
838
|
-
if (typed === undefined)
|
|
839
|
-
return;
|
|
840
|
-
const word = typed.replace(DASHES, "");
|
|
841
|
-
if (word.length < 2 && !typed.startsWith("--"))
|
|
842
|
-
return;
|
|
843
|
-
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
844
|
-
...option.short === undefined ? [] : [`-${option.short}`],
|
|
845
|
-
`--${name}`,
|
|
846
|
-
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
847
|
-
]);
|
|
848
|
-
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
849
|
-
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
850
|
-
}
|
|
851
|
-
var DASHES, EXIT, Exit, UsageError, HelpShown, completion, heading, OUTPUT_OPTIONS, UNKNOWN_OPTION;
|
|
852
|
-
var init_args = __esm(() => {
|
|
853
|
-
init_format();
|
|
854
|
-
init_help();
|
|
855
|
-
init_text2();
|
|
856
|
-
init_help();
|
|
857
|
-
init_input();
|
|
858
|
-
DASHES = /^-+/;
|
|
859
|
-
EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
|
|
860
|
-
Exit = class Exit extends Error {
|
|
861
|
-
code;
|
|
862
|
-
hint;
|
|
863
|
-
[EXIT] = true;
|
|
864
|
-
constructor(message, code, hint) {
|
|
865
|
-
super(message);
|
|
866
|
-
this.code = code;
|
|
867
|
-
this.hint = hint;
|
|
868
|
-
}
|
|
869
|
-
static [Symbol.hasInstance](value) {
|
|
870
|
-
if (this !== Exit)
|
|
871
|
-
return Function.prototype[Symbol.hasInstance].call(this, value);
|
|
872
|
-
return typeof value === "object" && value !== null && value[EXIT] === true;
|
|
873
|
-
}
|
|
874
|
-
};
|
|
875
|
-
UsageError = class UsageError extends Exit {
|
|
876
|
-
constructor(message, hint) {
|
|
877
|
-
super(message, 2, hint);
|
|
878
|
-
}
|
|
879
|
-
};
|
|
880
|
-
HelpShown = class HelpShown extends Exit {
|
|
881
|
-
constructor() {
|
|
882
|
-
super("help shown", 0);
|
|
883
|
-
}
|
|
884
|
-
};
|
|
885
|
-
completion = { active: false };
|
|
886
|
-
heading = { bin: undefined };
|
|
887
|
-
OUTPUT_OPTIONS = {
|
|
888
|
-
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
889
|
-
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
890
|
-
};
|
|
891
|
-
UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
892
|
-
});
|
|
893
|
-
|
|
894
|
-
// ../kit/src/folders.ts
|
|
895
|
-
import { homedir as homedir5 } from "os";
|
|
896
|
-
import { join as join7 } from "path";
|
|
897
|
-
import process18 from "process";
|
|
898
|
-
function ignoredFolders(extra = [], where = {}) {
|
|
899
|
-
const configured = readUserConfig("config", where).ignore;
|
|
900
|
-
const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
|
|
901
|
-
return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
|
|
902
|
-
}
|
|
903
|
-
function cacheFolder({ home = homedir5(), env = process18.env } = {}) {
|
|
904
|
-
return xdgFolder(env.XDG_CACHE_HOME, join7(home, ".cache"));
|
|
905
|
-
}
|
|
906
|
-
var SKIPPED_FOLDERS;
|
|
907
|
-
var init_folders = __esm(() => {
|
|
908
|
-
init_user_config();
|
|
909
|
-
SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
910
|
-
});
|
|
911
|
-
|
|
912
|
-
// ../kit/src/picker/line.ts
|
|
913
|
-
function isEditKey(key) {
|
|
914
|
-
return EDIT_KEYS.has(key);
|
|
915
|
-
}
|
|
916
|
-
function endsKills(key) {
|
|
917
|
-
return typeof key !== "object" && !isEditKey(key);
|
|
918
|
-
}
|
|
919
|
-
function isWord(char) {
|
|
920
|
-
return char !== undefined && WORD_CHARACTER.test(char);
|
|
921
|
-
}
|
|
922
|
-
function wordStart(chars, from) {
|
|
923
|
-
let at = from;
|
|
924
|
-
while (at > 0 && !isWord(chars[at - 1]))
|
|
925
|
-
at--;
|
|
926
|
-
while (at > 0 && isWord(chars[at - 1]))
|
|
927
|
-
at--;
|
|
928
|
-
return at;
|
|
929
|
-
}
|
|
930
|
-
function wordEnd(chars, from) {
|
|
931
|
-
let at = from;
|
|
932
|
-
while (at < chars.length && !isWord(chars[at]))
|
|
933
|
-
at++;
|
|
934
|
-
while (at < chars.length && isWord(chars[at]))
|
|
935
|
-
at++;
|
|
936
|
-
return at;
|
|
937
|
-
}
|
|
938
|
-
function spacedStart(chars, from) {
|
|
939
|
-
let at = from;
|
|
940
|
-
while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
|
|
941
|
-
at--;
|
|
942
|
-
while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
|
|
943
|
-
at--;
|
|
944
|
-
return at;
|
|
945
|
-
}
|
|
946
|
-
function cut2(chars, from, to) {
|
|
947
|
-
return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
|
|
948
|
-
}
|
|
949
|
-
function insert(chars, at, text) {
|
|
950
|
-
const typed = [...text];
|
|
951
|
-
return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
|
|
952
|
-
}
|
|
953
|
-
function editLine(line, key) {
|
|
954
|
-
const { killed = "", chained = false } = line;
|
|
955
|
-
const chars = [...line.text];
|
|
956
|
-
const at = Math.min(Math.max(line.caret, 0), chars.length);
|
|
957
|
-
const edited = edit(chars, at, key, killed);
|
|
958
|
-
if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
|
|
959
|
-
return line.killed === undefined ? edited : { ...edited, killed };
|
|
960
|
-
const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
|
|
961
|
-
if (taken === "")
|
|
962
|
-
return { ...edited, killed, chained };
|
|
963
|
-
if (!chained)
|
|
964
|
-
return { ...edited, killed: taken, chained: true };
|
|
965
|
-
return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
|
|
966
|
-
}
|
|
967
|
-
function edit(chars, at, key, killed) {
|
|
968
|
-
const text = chars.join("");
|
|
969
|
-
if (typeof key === "object")
|
|
970
|
-
return insert(chars, at, key.text);
|
|
971
|
-
switch (key) {
|
|
972
|
-
case "left":
|
|
973
|
-
return { text, caret: Math.max(at - 1, 0) };
|
|
974
|
-
case "right":
|
|
975
|
-
return { text, caret: Math.min(at + 1, chars.length) };
|
|
976
|
-
case "wordleft":
|
|
977
|
-
return { text, caret: wordStart(chars, at) };
|
|
978
|
-
case "wordright":
|
|
979
|
-
return { text, caret: wordEnd(chars, at) };
|
|
980
|
-
case "linestart":
|
|
981
|
-
return { text, caret: 0 };
|
|
982
|
-
case "lineend":
|
|
983
|
-
return { text, caret: chars.length };
|
|
984
|
-
case "erase":
|
|
985
|
-
return cut2(chars, Math.max(at - 1, 0), at);
|
|
986
|
-
case "delete":
|
|
987
|
-
return cut2(chars, at, Math.min(at + 1, chars.length));
|
|
988
|
-
case "word":
|
|
989
|
-
return cut2(chars, spacedStart(chars, at), at);
|
|
990
|
-
case "killword":
|
|
991
|
-
return cut2(chars, wordStart(chars, at), at);
|
|
992
|
-
case "killnext":
|
|
993
|
-
return cut2(chars, at, wordEnd(chars, at));
|
|
994
|
-
case "clear":
|
|
995
|
-
return cut2(chars, 0, at);
|
|
996
|
-
case "killend":
|
|
997
|
-
return cut2(chars, at, chars.length);
|
|
998
|
-
case "yank":
|
|
999
|
-
return insert(chars, at, killed);
|
|
1000
|
-
}
|
|
1001
|
-
}
|
|
1002
|
-
function visible({ text, caret }, room) {
|
|
1003
|
-
const chars = [...text];
|
|
1004
|
-
const at = Math.min(Math.max(caret, 0), chars.length);
|
|
1005
|
-
const cells = at === chars.length ? [...chars, " "] : chars;
|
|
1006
|
-
const widths = cells.map((char) => Bun.stringWidth(char));
|
|
1007
|
-
const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
|
|
1008
|
-
const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
|
|
1009
|
-
let start = at;
|
|
1010
|
-
let end = at + 1;
|
|
1011
|
-
while (start > 0 && fits(start - 1, end))
|
|
1012
|
-
start--;
|
|
1013
|
-
while (end < cells.length && fits(start, end + 1))
|
|
1014
|
-
end++;
|
|
1015
|
-
const left = start > 0 ? "\u2026" : "";
|
|
1016
|
-
const right = end < cells.length ? "\u2026" : "";
|
|
1017
|
-
return { before: left + chars.slice(start, at).join(""), at: chars[at], after: chars.slice(at + 1, end).join("") + right, column: left.length + width(start, at) };
|
|
1018
|
-
}
|
|
1019
|
-
var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS, WORD_CHARACTER, SPACE;
|
|
1020
|
-
var init_line = __esm(() => {
|
|
1021
|
-
EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
|
|
1022
|
-
BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
|
|
1023
|
-
FORWARD_KILLS = new Set(["killnext", "killend"]);
|
|
1024
|
-
WORD_CHARACTER = /[\p{L}\p{N}_]/u;
|
|
1025
|
-
SPACE = /\s/;
|
|
1026
|
-
});
|
|
1027
|
-
|
|
1028
|
-
// ../kit/src/picker/score.ts
|
|
1029
|
-
function startsWord(text, index) {
|
|
1030
|
-
if (index === 0)
|
|
1031
|
-
return true;
|
|
1032
|
-
const before = text[index - 1];
|
|
1033
|
-
return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
|
|
1034
|
-
}
|
|
1035
|
-
function fuzzy(query, text) {
|
|
1036
|
-
if (query === "")
|
|
1037
|
-
return { score: 0, positions: [] };
|
|
1038
|
-
const exact = query !== query.toLowerCase();
|
|
1039
|
-
const needle = exact ? query : query.toLowerCase();
|
|
1040
|
-
const haystack = exact ? text : text.toLowerCase();
|
|
1041
|
-
if (haystack.length !== text.length || needle.length > haystack.length)
|
|
1042
|
-
return;
|
|
1043
|
-
const width = haystack.length;
|
|
1044
|
-
const best = Array.from({ length: needle.length }, () => new Array(width).fill(NONE));
|
|
1045
|
-
const from = Array.from({ length: needle.length }, () => new Array(width).fill(-1));
|
|
1046
|
-
for (let j = 0;j < needle.length; j++) {
|
|
1047
|
-
let run = NONE;
|
|
1048
|
-
let runAt = -1;
|
|
1049
|
-
for (let i = j;i < width; i++) {
|
|
1050
|
-
if (j > 0 && i - 2 >= j - 1) {
|
|
1051
|
-
const candidate = best[j - 1][i - 2] + (i - 2) * GAP;
|
|
1052
|
-
if (candidate > run) {
|
|
1053
|
-
run = candidate;
|
|
1054
|
-
runAt = i - 2;
|
|
1055
|
-
}
|
|
1056
|
-
}
|
|
1057
|
-
if (haystack[i] !== needle[j])
|
|
1058
|
-
continue;
|
|
1059
|
-
const here = MATCH + (startsWord(text, i) ? BOUNDARY2 : 0) + (i === 0 ? PREFIX : 0);
|
|
1060
|
-
if (j === 0) {
|
|
1061
|
-
best[0][i] = here - i * GAP;
|
|
1062
|
-
continue;
|
|
1063
|
-
}
|
|
1064
|
-
const joined = best[j - 1][i - 1] + CONSECUTIVE;
|
|
1065
|
-
const skipped = run - (i - 1) * GAP;
|
|
1066
|
-
if (joined > NONE && joined >= skipped) {
|
|
1067
|
-
best[j][i] = joined + here;
|
|
1068
|
-
from[j][i] = i - 1;
|
|
1069
|
-
} else if (skipped > NONE) {
|
|
1070
|
-
best[j][i] = skipped + here;
|
|
1071
|
-
from[j][i] = runAt;
|
|
1072
|
-
}
|
|
1073
|
-
}
|
|
1074
|
-
}
|
|
1075
|
-
const last = best[needle.length - 1];
|
|
1076
|
-
let end = -1;
|
|
1077
|
-
for (let i = 0;i < width; i++) {
|
|
1078
|
-
if (last[i] > NONE && (end === -1 || last[i] > last[end]))
|
|
1079
|
-
end = i;
|
|
1080
|
-
}
|
|
1081
|
-
if (end === -1)
|
|
1082
|
-
return;
|
|
1083
|
-
const positions = [];
|
|
1084
|
-
for (let j = needle.length - 1, i = end;j >= 0; j--) {
|
|
1085
|
-
positions.unshift(i);
|
|
1086
|
-
i = from[j][i];
|
|
1087
|
-
}
|
|
1088
|
-
return { score: last[end], positions };
|
|
1089
|
-
}
|
|
1090
|
-
function rank(query, lines) {
|
|
1091
|
-
if (query === "")
|
|
1092
|
-
return lines.map((_, index) => ({ index, positions: [] }));
|
|
1093
|
-
const found = [];
|
|
1094
|
-
for (const [index, line] of lines.entries()) {
|
|
1095
|
-
const match = fuzzy(query, line);
|
|
1096
|
-
if (match !== undefined)
|
|
1097
|
-
found.push({ index, positions: match.positions, score: match.score });
|
|
1098
|
-
}
|
|
1099
|
-
return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
|
|
1100
|
-
}
|
|
1101
|
-
var MATCH = 16, CONSECUTIVE = 12, BOUNDARY2 = 10, PREFIX = 8, GAP = 1, BOUNDARY_AFTER, UPPER, LOWER, NONE;
|
|
1102
|
-
var init_score = __esm(() => {
|
|
1103
|
-
BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
|
|
1104
|
-
UPPER = /\p{Lu}/u;
|
|
1105
|
-
LOWER = /\p{Ll}/u;
|
|
1106
|
-
NONE = Number.NEGATIVE_INFINITY;
|
|
1107
|
-
});
|
|
1108
|
-
|
|
1109
|
-
// ../kit/src/picker/state.ts
|
|
1110
|
-
function repeat(value, count) {
|
|
1111
|
-
return Array.from({ length: count }).fill(value);
|
|
1112
|
-
}
|
|
1113
|
-
function styled(line) {
|
|
1114
|
-
let text = "";
|
|
1115
|
-
const styles = [];
|
|
1116
|
-
let active = "";
|
|
1117
|
-
let colored = false;
|
|
1118
|
-
let last = 0;
|
|
1119
|
-
function add(chunk) {
|
|
1120
|
-
const flat = chunk.replace(CONTROL2, " ");
|
|
1121
|
-
text += flat;
|
|
1122
|
-
colored ||= active !== "" && flat !== "";
|
|
1123
|
-
styles.push(...repeat(active, flat.length));
|
|
1124
|
-
}
|
|
1125
|
-
for (const found of line.matchAll(ANSI)) {
|
|
1126
|
-
add(line.slice(last, found.index));
|
|
1127
|
-
last = found.index + found[0].length;
|
|
1128
|
-
if (SGR.test(found[0]))
|
|
1129
|
-
active = RESET.test(found[0]) ? "" : active + found[0];
|
|
1130
|
-
}
|
|
1131
|
-
add(line.slice(last));
|
|
1132
|
-
return { text, styles: colored ? styles : undefined };
|
|
1133
|
-
}
|
|
1134
|
-
function lay(rows, searched) {
|
|
1135
|
-
const parsed = rows.map((row) => row.cells.map(styled));
|
|
1136
|
-
const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
|
|
1137
|
-
return parsed.map((cells, at) => {
|
|
1138
|
-
let text = "";
|
|
1139
|
-
const styles = [];
|
|
1140
|
-
let colored = false;
|
|
1141
|
-
let searchEnd = 0;
|
|
1142
|
-
for (const [column, cell] of cells.entries()) {
|
|
1143
|
-
const last = column === cells.length - 1;
|
|
1144
|
-
const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
|
|
1145
|
-
text += shown;
|
|
1146
|
-
colored ||= cell.styles !== undefined;
|
|
1147
|
-
styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
|
|
1148
|
-
if (column < searched)
|
|
1149
|
-
searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
|
|
1150
|
-
if (!last) {
|
|
1151
|
-
const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
|
|
1152
|
-
text += " ".repeat(pad);
|
|
1153
|
-
styles.push(...repeat("", pad));
|
|
1154
|
-
}
|
|
1155
|
-
}
|
|
1156
|
-
return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
|
|
1157
|
-
});
|
|
1158
|
-
}
|
|
1159
|
-
function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
1160
|
-
const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
|
|
1161
|
-
return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
|
|
1162
|
-
const wheel = MOUSE.exec(sequence)?.[1];
|
|
1163
|
-
if (wheel !== undefined)
|
|
1164
|
-
return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
|
|
1165
|
-
const named = codes.get(sequence);
|
|
1166
|
-
const key = named === undefined ? KEYS[sequence] : { ctrl: named };
|
|
1167
|
-
if (sequence === PASTE_START || sequence === PASTE_END) {
|
|
1168
|
-
paste.active = sequence === PASTE_START;
|
|
1169
|
-
return [];
|
|
1170
|
-
}
|
|
1171
|
-
if (paste.active && (sequence === "\r" || sequence === `
|
|
1172
|
-
`))
|
|
1173
|
-
return [];
|
|
1174
|
-
if (key !== undefined)
|
|
1175
|
-
return [key];
|
|
1176
|
-
return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
|
|
1177
|
-
});
|
|
1178
|
-
}
|
|
1179
|
-
function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
|
|
1180
|
-
const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, caret: [...query].length, killed: "", chained: false, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
|
|
1181
|
-
return withRows(state, rows);
|
|
1182
|
-
}
|
|
1183
|
-
function withRows(state, rows, header = state.header) {
|
|
1184
|
-
const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
|
|
1185
|
-
const laid = lay(cells, state.searched);
|
|
1186
|
-
const searchable = laid.map((row) => row.searchable);
|
|
1187
|
-
const matches = rank(state.query, searchable);
|
|
1188
|
-
return { ...state, rows: cells, items: laid.map((row) => row.text), styles: laid.map((row) => row.styles), searchable, header, matches, cursor: Math.max(0, Math.min(matches.length - 1, state.cursor)), marked: new Set };
|
|
1189
|
-
}
|
|
1190
|
-
function withQuery(state, key) {
|
|
1191
|
-
const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
|
|
1192
|
-
return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
|
|
1193
|
-
}
|
|
1194
|
-
function move(state, by) {
|
|
1195
|
-
return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
|
|
1196
|
-
}
|
|
1197
|
-
function highlighted(state) {
|
|
1198
|
-
return state.matches[state.cursor]?.index;
|
|
1199
|
-
}
|
|
1200
|
-
function press(state, key) {
|
|
1201
|
-
if (state.done !== undefined)
|
|
1202
|
-
return state;
|
|
1203
|
-
if (state.chained && endsKills(key))
|
|
1204
|
-
state = { ...state, chained: false };
|
|
1205
|
-
if (state.help)
|
|
1206
|
-
return { ...state, help: false };
|
|
1207
|
-
if (typeof key === "object") {
|
|
1208
|
-
if ("text" in key)
|
|
1209
|
-
return withQuery(state, key);
|
|
1210
|
-
return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
|
|
1211
|
-
}
|
|
1212
|
-
if (isEditKey(key))
|
|
1213
|
-
return withQuery(state, key);
|
|
1214
|
-
switch (key) {
|
|
1215
|
-
case "up":
|
|
1216
|
-
return move(state, -1);
|
|
1217
|
-
case "down":
|
|
1218
|
-
return move(state, 1);
|
|
1219
|
-
case "pageup":
|
|
1220
|
-
return move(state, -state.page);
|
|
1221
|
-
case "pagedown":
|
|
1222
|
-
return move(state, state.page);
|
|
1223
|
-
case "home":
|
|
1224
|
-
return move(state, -state.matches.length);
|
|
1225
|
-
case "end":
|
|
1226
|
-
return move(state, state.matches.length);
|
|
1227
|
-
case "cancel":
|
|
1228
|
-
return { ...state, done: "cancel" };
|
|
1229
|
-
case "help":
|
|
1230
|
-
return { ...state, help: true };
|
|
1231
|
-
case "suspend":
|
|
1232
|
-
return state;
|
|
1233
|
-
case "enter":
|
|
1234
|
-
return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
|
|
1235
|
-
case "tab": {
|
|
1236
|
-
const at = highlighted(state);
|
|
1237
|
-
if (!state.multi || at === undefined)
|
|
1238
|
-
return state;
|
|
1239
|
-
const marked = new Set(state.marked);
|
|
1240
|
-
if (!marked.delete(at))
|
|
1241
|
-
marked.add(at);
|
|
1242
|
-
return move({ ...state, marked }, 1);
|
|
1243
|
-
}
|
|
1244
|
-
}
|
|
1245
|
-
}
|
|
1246
|
-
function chosen(state) {
|
|
1247
|
-
if (state.marked.size > 0)
|
|
1248
|
-
return state.rows.filter((_, index) => state.marked.has(index));
|
|
1249
|
-
const at = highlighted(state);
|
|
1250
|
-
return at === undefined ? [] : [state.rows[at]];
|
|
1251
|
-
}
|
|
1252
|
-
var CONTROL2, IS_CONTROL, SGR, RESET, COLUMN_GAP = 2, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS, CTRL_KEY;
|
|
1253
|
-
var init_state = __esm(() => {
|
|
1254
|
-
init_text2();
|
|
1255
|
-
init_line();
|
|
1256
|
-
init_score();
|
|
1257
|
-
CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
|
|
1258
|
-
IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
|
|
1259
|
-
SGR = /^\x1B\[[0-9;]*m$/;
|
|
1260
|
-
RESET = /^\x1B\[0?m$/;
|
|
1261
|
-
KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
|
|
1262
|
-
MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
|
|
1263
|
-
KEYS = {
|
|
1264
|
-
"\x1B[A": "up",
|
|
1265
|
-
"\x1BOA": "up",
|
|
1266
|
-
"\x10": "up",
|
|
1267
|
-
"\x1B[B": "down",
|
|
1268
|
-
"\x1BOB": "down",
|
|
1269
|
-
"\x0E": "down",
|
|
1270
|
-
"\x1B[5~": "pageup",
|
|
1271
|
-
"\x1B[6~": "pagedown",
|
|
1272
|
-
"\x1B[H": "home",
|
|
1273
|
-
"\x1B[1~": "home",
|
|
1274
|
-
"\x1BOH": "home",
|
|
1275
|
-
"\x1B[F": "end",
|
|
1276
|
-
"\x1B[4~": "end",
|
|
1277
|
-
"\x1BOF": "end",
|
|
1278
|
-
"\r": "enter",
|
|
1279
|
-
"\n": "enter",
|
|
1280
|
-
"\x03": "cancel",
|
|
1281
|
-
"\x1B": "cancel",
|
|
1282
|
-
"\x1B[D": "left",
|
|
1283
|
-
"\x1BOD": "left",
|
|
1284
|
-
"\x1B[C": "right",
|
|
1285
|
-
"\x1BOC": "right",
|
|
1286
|
-
"\x1B[1;5D": "wordleft",
|
|
1287
|
-
"\x1B[1;3D": "wordleft",
|
|
1288
|
-
"\x1Bb": "wordleft",
|
|
1289
|
-
"\x1B[1;5C": "wordright",
|
|
1290
|
-
"\x1B[1;3C": "wordright",
|
|
1291
|
-
"\x1Bf": "wordright",
|
|
1292
|
-
"\x01": "linestart",
|
|
1293
|
-
"\x05": "lineend",
|
|
1294
|
-
"\x7F": "erase",
|
|
1295
|
-
"\x1B[3~": "delete",
|
|
1296
|
-
"\b": "killword",
|
|
1297
|
-
"\x1B\x7F": "killword",
|
|
1298
|
-
"\x1B[3;5~": "killnext",
|
|
1299
|
-
"\x1Bd": "killnext",
|
|
1300
|
-
"\x15": "clear",
|
|
1301
|
-
"\v": "killend",
|
|
1302
|
-
"\x17": "word",
|
|
1303
|
-
"\x19": "yank",
|
|
1304
|
-
"\x1A": "suspend",
|
|
1305
|
-
"\t": "tab",
|
|
1306
|
-
"\x1F": "help",
|
|
1307
|
-
"\x1BOP": "help",
|
|
1308
|
-
"\x1B[11~": "help"
|
|
1309
|
-
};
|
|
1310
|
-
CTRL_KEY = /^ctrl-[abd-gkln-z]$/;
|
|
1311
|
-
});
|
|
1312
|
-
|
|
1313
|
-
// ../kit/src/job.ts
|
|
1314
|
-
import process20 from "process";
|
|
1315
|
-
function stopJob() {
|
|
1316
|
-
process20.kill(0, "SIGTSTP");
|
|
1317
|
-
}
|
|
1318
|
-
var init_job = () => {};
|
|
1319
|
-
|
|
1320
|
-
// ../kit/src/redraw.ts
|
|
1321
|
-
function overwrite(lines, columns) {
|
|
1322
|
-
return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
|
|
1323
|
-
`);
|
|
1324
|
-
}
|
|
1325
|
-
function rowsTaken(lines, columns) {
|
|
1326
|
-
return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
|
|
1327
|
-
}
|
|
1328
|
-
var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
|
|
1329
|
-
var init_redraw = __esm(() => {
|
|
1330
|
-
init_format();
|
|
1331
|
-
});
|
|
1332
|
-
|
|
1333
|
-
// ../kit/src/answers.ts
|
|
1334
|
-
import { mkdirSync as mkdirSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync2 } from "fs";
|
|
1335
|
-
import { dirname as dirname5, join as join9 } from "path";
|
|
1336
|
-
function answersFile() {
|
|
1337
|
-
return join9(cacheFolder(), "kaynooo-cli", "answers.json");
|
|
1338
|
-
}
|
|
1339
|
-
function stored() {
|
|
1340
|
-
try {
|
|
1341
|
-
const parsed = JSON.parse(readFileSync7(answersFile(), "utf-8"));
|
|
1342
|
-
if (typeof parsed !== "object" || parsed === null)
|
|
1343
|
-
return {};
|
|
1344
|
-
return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
|
|
1345
|
-
} catch {
|
|
1346
|
-
return {};
|
|
1347
|
-
}
|
|
1348
|
-
}
|
|
1349
|
-
function earlierAnswers(key) {
|
|
1350
|
-
return stored()[key] ?? [];
|
|
1351
|
-
}
|
|
1352
|
-
function rememberAnswer(key, answer) {
|
|
1353
|
-
const all = stored();
|
|
1354
|
-
const file = answersFile();
|
|
1355
|
-
all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
|
|
1356
|
-
try {
|
|
1357
|
-
mkdirSync3(dirname5(file), { recursive: true });
|
|
1358
|
-
writeFileSync2(file, JSON.stringify(all));
|
|
1359
|
-
} catch {}
|
|
1360
|
-
}
|
|
1361
|
-
var KEPT = 50;
|
|
1362
|
-
var init_answers = __esm(() => {
|
|
1363
|
-
init_folders();
|
|
1364
|
-
});
|
|
1365
|
-
|
|
1366
|
-
// ../kit/src/prompt.ts
|
|
1367
|
-
import process24 from "process";
|
|
1368
|
-
function readKeys(input, paste = { active: false }) {
|
|
1369
|
-
return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
|
|
1370
|
-
}
|
|
1371
|
-
function roomAfter(question, columns) {
|
|
1372
|
-
return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
|
|
1373
|
-
}
|
|
1374
|
-
function withCaret(colors, line, room, dim = false) {
|
|
1375
|
-
const { before, at, after } = visible(line, room);
|
|
1376
|
-
const tone = dim ? colors.dim : (text) => text;
|
|
1377
|
-
return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
|
|
1378
|
-
}
|
|
1379
|
-
function sharedStart(texts) {
|
|
1380
|
-
const [first = [], ...rest] = texts.map((text) => [...text]);
|
|
1381
|
-
let length = first.length;
|
|
1382
|
-
for (const chars of rest) {
|
|
1383
|
-
const differs = chars.findIndex((char, index) => char !== first[index]);
|
|
1384
|
-
length = Math.min(length, differs === -1 ? chars.length : differs);
|
|
1385
|
-
}
|
|
1386
|
-
return first.slice(0, length).join("");
|
|
1387
|
-
}
|
|
1388
|
-
function listed2(colors, found, columns) {
|
|
1389
|
-
const shared = sharedStart(found);
|
|
1390
|
-
const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
|
|
1391
|
-
const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
|
|
1392
|
-
const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
|
|
1393
|
-
return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
|
|
1394
|
-
}
|
|
1395
|
-
async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
|
|
1396
|
-
let line = { text: "", caret: 0 };
|
|
1397
|
-
let invalid;
|
|
1398
|
-
let completions = [];
|
|
1399
|
-
const remembered = history === undefined || mask ? undefined : history;
|
|
1400
|
-
const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
|
|
1401
|
-
let recalled = -1;
|
|
1402
|
-
let draft = line;
|
|
1403
|
-
const taken = () => line.text === "" ? fallback ?? "" : line.text;
|
|
1404
|
-
const shown = () => mask ? "*".repeat([...taken()].length) : taken();
|
|
1405
|
-
const accepted = await ask(question, settings, (colors, state, { columns }) => {
|
|
1406
|
-
if (state !== "asking")
|
|
1407
|
-
return [answer(colors, question, state, shown())];
|
|
1408
|
-
const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
|
|
1409
|
-
return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
|
|
1410
|
-
}, (key) => {
|
|
1411
|
-
if (key === "cancel")
|
|
1412
|
-
return "cancel";
|
|
1413
|
-
invalid = undefined;
|
|
1414
|
-
completions = [];
|
|
1415
|
-
if (line.chained === true && endsKills(key))
|
|
1416
|
-
line = { ...line, chained: false };
|
|
1417
|
-
if (key === "tab") {
|
|
1418
|
-
const chars = [...line.text];
|
|
1419
|
-
const before = chars.slice(0, line.caret).join("");
|
|
1420
|
-
const found = complete?.(before) ?? [];
|
|
1421
|
-
const filled = sharedStart(found);
|
|
1422
|
-
if ([...filled].length > [...before].length)
|
|
1423
|
-
line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
|
|
1424
|
-
else
|
|
1425
|
-
completions = found;
|
|
1426
|
-
return;
|
|
1427
|
-
}
|
|
1428
|
-
if (key === "enter") {
|
|
1429
|
-
invalid = validate?.(taken());
|
|
1430
|
-
return invalid === undefined ? "enter" : undefined;
|
|
1431
|
-
}
|
|
1432
|
-
if (key === "up" || key === "down") {
|
|
1433
|
-
const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
|
|
1434
|
-
if (recalled === -1)
|
|
1435
|
-
draft = line;
|
|
1436
|
-
recalled = to;
|
|
1437
|
-
const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
|
|
1438
|
-
line = { ...shown, killed: line.killed ?? "" };
|
|
1439
|
-
return;
|
|
1440
|
-
}
|
|
1441
|
-
const edit = { home: "linestart", end: "lineend" }[key] ?? key;
|
|
1442
|
-
if (typeof edit === "object" || isEditKey(edit))
|
|
1443
|
-
line = editLine(line, edit);
|
|
1444
|
-
return;
|
|
1445
|
-
});
|
|
1446
|
-
if (!accepted)
|
|
1447
|
-
return;
|
|
1448
|
-
if (remembered !== undefined && taken() !== "")
|
|
1449
|
-
rememberAnswer(remembered, taken());
|
|
1450
|
-
return taken();
|
|
1451
|
-
}
|
|
1452
|
-
function answer(colors, question, state, picked) {
|
|
1453
|
-
return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
|
|
1454
|
-
}
|
|
1455
|
-
async function ask(question, { hint, terminal = process24 }, render, press) {
|
|
1456
|
-
const { stdin, stderr } = terminal;
|
|
1457
|
-
if (!isInteractive(terminal))
|
|
1458
|
-
fail(`cannot ask "${question}" off a terminal`, 2, hint);
|
|
1459
|
-
const colors = paint(stderr);
|
|
1460
|
-
let current = "asking";
|
|
1461
|
-
let outcome;
|
|
1462
|
-
const columns = () => stderr.columns || 80;
|
|
1463
|
-
const draw = (state, last = false) => {
|
|
1464
|
-
const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
|
|
1465
|
-
const rows = rowsTaken(frame, columns());
|
|
1466
|
-
stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
|
|
1467
|
-
current = state;
|
|
1468
|
-
};
|
|
1469
|
-
const redraw = () => draw(current);
|
|
1470
|
-
const paste = { active: false };
|
|
1471
|
-
const stop = terminal.stop ?? (terminal === process24 ? stopJob : undefined);
|
|
1472
|
-
const suspend = () => {
|
|
1473
|
-
if (stop === undefined)
|
|
1474
|
-
return;
|
|
1475
|
-
stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
|
|
1476
|
-
stdin.setRawMode(false);
|
|
1477
|
-
stop();
|
|
1478
|
-
stdin.setRawMode(true);
|
|
1479
|
-
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
1480
|
-
};
|
|
1481
|
-
try {
|
|
1482
|
-
stderr.on?.("resize", redraw);
|
|
1483
|
-
stdin.setRawMode(true);
|
|
1484
|
-
stdin.resume();
|
|
1485
|
-
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
1486
|
-
draw("asking");
|
|
1487
|
-
return await new Promise((resolve) => {
|
|
1488
|
-
function onData(data) {
|
|
1489
|
-
for (const key of readKeys(data.toString(), paste)) {
|
|
1490
|
-
if (key === "suspend") {
|
|
1491
|
-
suspend();
|
|
1492
|
-
continue;
|
|
1493
|
-
}
|
|
1494
|
-
const pressed = press(key);
|
|
1495
|
-
if (pressed !== undefined) {
|
|
1496
|
-
settle(pressed);
|
|
1497
|
-
return;
|
|
1498
|
-
}
|
|
1499
|
-
}
|
|
1500
|
-
draw("asking");
|
|
1501
|
-
}
|
|
1502
|
-
function onEnd() {
|
|
1503
|
-
settle("cancel");
|
|
1504
|
-
}
|
|
1505
|
-
function settle(settled) {
|
|
1506
|
-
outcome = settled;
|
|
1507
|
-
stdin.off("data", onData);
|
|
1508
|
-
stdin.off("end", onEnd);
|
|
1509
|
-
resolve(settled === "enter");
|
|
1510
|
-
}
|
|
1511
|
-
stdin.on("data", onData);
|
|
1512
|
-
stdin.on("end", onEnd);
|
|
1513
|
-
});
|
|
1514
|
-
} finally {
|
|
1515
|
-
stderr.off?.("resize", redraw);
|
|
1516
|
-
draw(outcome ?? "cancel", true);
|
|
1517
|
-
stderr.write(`
|
|
1518
|
-
\x1B[?25h\x1B[?2004l`);
|
|
1519
|
-
stdin.setRawMode(false);
|
|
1520
|
-
stdin.pause();
|
|
1521
|
-
}
|
|
1522
|
-
}
|
|
1523
|
-
var PROMPT_KEYS, MAX_LISTED = 12;
|
|
1524
|
-
var init_prompt = __esm(() => {
|
|
1525
|
-
init_answers();
|
|
1526
|
-
init_args();
|
|
1527
|
-
init_format();
|
|
1528
|
-
init_job();
|
|
1529
|
-
init_mode();
|
|
1530
|
-
init_line();
|
|
1531
|
-
init_state();
|
|
1532
|
-
init_redraw();
|
|
1533
|
-
init_style();
|
|
1534
|
-
PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
|
|
1535
|
-
});
|
|
1536
|
-
|
|
1537
|
-
// src/j-cli.ts
|
|
1538
|
-
import process27 from "process";
|
|
1539
|
-
|
|
1540
|
-
// ../kit/src/index.ts
|
|
1541
|
-
init_args();
|
|
1542
|
-
|
|
1543
|
-
// ../kit/src/argv.ts
|
|
1544
|
-
import { readFileSync as readFileSync3, realpathSync } from "fs";
|
|
1545
|
-
import { resolve as resolve3 } from "path";
|
|
1546
|
-
import process11 from "process";
|
|
1547
|
-
function commandLine() {
|
|
1548
|
-
try {
|
|
1549
|
-
return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
1550
|
-
} catch {
|
|
1551
|
-
return;
|
|
1552
|
-
}
|
|
1553
|
-
}
|
|
1554
|
-
function realPath(word) {
|
|
1555
|
-
try {
|
|
1556
|
-
return realpathSync(resolve3(word));
|
|
1557
|
-
} catch {
|
|
1558
|
-
return;
|
|
1559
|
-
}
|
|
1560
|
-
}
|
|
1561
|
-
function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
|
|
1562
|
-
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
1563
|
-
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
1564
|
-
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
1565
|
-
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
1566
|
-
}
|
|
1567
|
-
// ../kit/src/chart.ts
|
|
1568
|
-
init_format();
|
|
1569
|
-
init_mode();
|
|
1570
|
-
init_style();
|
|
1571
|
-
init_theme();
|
|
1572
|
-
// ../kit/src/ci.ts
|
|
1573
|
-
init_args();
|
|
1574
|
-
init_format();
|
|
1575
|
-
|
|
1576
|
-
// ../kit/src/progress.ts
|
|
1577
|
-
init_format();
|
|
1578
|
-
|
|
1579
|
-
// ../kit/src/process.ts
|
|
1580
|
-
import { readFileSync as readFileSync4 } from "fs";
|
|
1581
|
-
import { constants } from "os";
|
|
1582
|
-
import process12 from "process";
|
|
1583
|
-
var KILL_GRACE_MS = 2000;
|
|
1584
|
-
var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
1585
|
-
var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
|
|
1586
|
-
function exitCodeOf(code, signal) {
|
|
1587
|
-
if (code !== null)
|
|
1588
|
-
return code;
|
|
1589
|
-
if (typeof signal === "number")
|
|
1590
|
-
return 128 + signal;
|
|
1591
|
-
return signal === null ? 129 : 128 + constants.signals[signal];
|
|
1592
|
-
}
|
|
1593
|
-
function groupsOf(pid) {
|
|
1594
|
-
try {
|
|
1595
|
-
const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
|
|
1596
|
-
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
1597
|
-
return { group: Number(fields[2]), foreground: Number(fields[5]) };
|
|
1598
|
-
} catch {
|
|
1599
|
-
return;
|
|
1600
|
-
}
|
|
1601
|
-
}
|
|
1602
|
-
function heardTheTerminal(child) {
|
|
1603
|
-
if (child.pid === undefined)
|
|
1604
|
-
return false;
|
|
1605
|
-
const own = groupsOf("self");
|
|
1606
|
-
return own !== undefined && own.group === own.foreground && groupsOf(child.pid)?.group === own.group;
|
|
1607
|
-
}
|
|
1608
|
-
function holdSignals(cleanup) {
|
|
1609
|
-
let received;
|
|
1610
|
-
let child;
|
|
1611
|
-
const held = {
|
|
1612
|
-
get signal() {
|
|
1613
|
-
return received;
|
|
1614
|
-
},
|
|
1615
|
-
forward: (to) => {
|
|
1616
|
-
child = to;
|
|
1617
|
-
},
|
|
1618
|
-
release: () => {
|
|
1619
|
-
for (const signal of SIGNALS)
|
|
1620
|
-
process12.off(signal, onSignal);
|
|
1621
|
-
}
|
|
1622
|
-
};
|
|
1623
|
-
function onSignal(signal) {
|
|
1624
|
-
received = signal;
|
|
1625
|
-
if (child !== undefined) {
|
|
1626
|
-
if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
|
|
1627
|
-
child.kill(signal);
|
|
1628
|
-
return;
|
|
1629
|
-
}
|
|
1630
|
-
if (cleanup === undefined)
|
|
1631
|
-
return;
|
|
1632
|
-
held.release();
|
|
1633
|
-
cleanup(signal);
|
|
1634
|
-
process12.kill(process12.pid, signal);
|
|
1635
|
-
}
|
|
1636
|
-
for (const signal of SIGNALS)
|
|
1637
|
-
process12.on(signal, onSignal);
|
|
1638
|
-
return held;
|
|
1639
|
-
}
|
|
1640
|
-
async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
1641
|
-
const chunks = [];
|
|
1642
|
-
const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
|
|
1643
|
-
const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin: input === undefined ? stdin : new TextEncoder().encode(input), stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
|
|
1644
|
-
const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
|
|
1645
|
-
const timers = [];
|
|
1646
|
-
const killGroup = (killing) => {
|
|
1647
|
-
if (state.done)
|
|
1648
|
-
return;
|
|
1649
|
-
try {
|
|
1650
|
-
if (grouped)
|
|
1651
|
-
process12.kill(-proc.pid, killing);
|
|
1652
|
-
else
|
|
1653
|
-
proc.kill(killing);
|
|
1654
|
-
} catch {}
|
|
1655
|
-
};
|
|
1656
|
-
const stop = () => {
|
|
1657
|
-
killGroup("SIGTERM");
|
|
1658
|
-
timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
|
|
1659
|
-
};
|
|
1660
|
-
const onAbort = () => stop();
|
|
1661
|
-
if (timeoutMs !== undefined) {
|
|
1662
|
-
timers.push(setTimeout(() => {
|
|
1663
|
-
state.timedOut = true;
|
|
1664
|
-
stop();
|
|
1665
|
-
}, timeoutMs));
|
|
1666
|
-
}
|
|
1667
|
-
if (signal?.aborted === true)
|
|
1668
|
-
onAbort();
|
|
1669
|
-
else
|
|
1670
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1671
|
-
onStart?.({ kill: (killing) => killGroup(killing) });
|
|
1672
|
-
const drain = async (stream, name) => {
|
|
1673
|
-
for await (const data of stream) {
|
|
1674
|
-
if (state.failure !== undefined)
|
|
1675
|
-
continue;
|
|
1676
|
-
try {
|
|
1677
|
-
onChunk?.({ stream: name, data });
|
|
1678
|
-
} catch (error) {
|
|
1679
|
-
state.failure = error;
|
|
1680
|
-
stop();
|
|
1681
|
-
continue;
|
|
1682
|
-
}
|
|
1683
|
-
if (state.truncated)
|
|
1684
|
-
continue;
|
|
1685
|
-
let kept = data;
|
|
1686
|
-
if (state.kept + data.length > maxBytes) {
|
|
1687
|
-
let cut = maxBytes - state.kept;
|
|
1688
|
-
while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
|
|
1689
|
-
cut--;
|
|
1690
|
-
kept = data.subarray(0, cut);
|
|
1691
|
-
state.truncated = true;
|
|
1692
|
-
}
|
|
1693
|
-
state.kept += kept.length;
|
|
1694
|
-
if (kept.length > 0)
|
|
1695
|
-
chunks.push({ stream: name, data: kept });
|
|
1696
|
-
}
|
|
1697
|
-
};
|
|
1698
|
-
try {
|
|
1699
|
-
await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
|
|
1700
|
-
await proc.exited;
|
|
1701
|
-
} finally {
|
|
1702
|
-
state.done = true;
|
|
1703
|
-
for (const timer of timers)
|
|
1704
|
-
clearTimeout(timer);
|
|
1705
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1706
|
-
}
|
|
1707
|
-
if (state.failure !== undefined)
|
|
1708
|
-
throw state.failure;
|
|
1709
|
-
const joined = () => Buffer.concat(chunks.map(({ data }) => data));
|
|
1710
|
-
let output;
|
|
1711
|
-
let text;
|
|
1712
|
-
let stdout;
|
|
1713
|
-
return {
|
|
1714
|
-
code: exitCodeOf(proc.exitCode, proc.signalCode),
|
|
1715
|
-
chunks,
|
|
1716
|
-
timedOut: state.timedOut,
|
|
1717
|
-
truncated: state.truncated,
|
|
1718
|
-
get output() {
|
|
1719
|
-
return output ??= joined();
|
|
1720
|
-
},
|
|
1721
|
-
get text() {
|
|
1722
|
-
return text ??= (output ??= joined()).toString();
|
|
1723
|
-
},
|
|
1724
|
-
get stdout() {
|
|
1725
|
-
return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
|
|
1726
|
-
}
|
|
1727
|
-
};
|
|
1728
|
-
}
|
|
1729
|
-
|
|
1730
|
-
// ../kit/src/progress.ts
|
|
1731
|
-
init_style();
|
|
1732
|
-
init_theme();
|
|
1733
|
-
var ESC = String.fromCharCode(27);
|
|
1734
|
-
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
1735
|
-
var RESET_STYLE = `${ESC}[0m`;
|
|
1736
|
-
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
1737
|
-
|
|
1738
|
-
// ../kit/src/ci.ts
|
|
1739
|
-
init_style();
|
|
1740
|
-
|
|
1741
|
-
// ../kit/src/tool.ts
|
|
1742
|
-
init_format();
|
|
1743
|
-
// ../kit/src/cli.ts
|
|
1744
|
-
init_args();
|
|
1745
|
-
import { readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
|
|
1746
|
-
import { dirname as dirname3, join as join6 } from "path";
|
|
1747
|
-
import process17 from "process";
|
|
1748
|
-
|
|
1749
|
-
// ../kit/src/askpass.ts
|
|
1750
|
-
import process13 from "process";
|
|
1751
|
-
var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
|
|
1752
|
-
async function askpassClient(argv) {
|
|
1753
|
-
const socketPath = process13.env[SOCKET_VARIABLE];
|
|
1754
|
-
if (socketPath === undefined)
|
|
1755
|
-
return;
|
|
1756
|
-
const request = { prompt: argv[0] ?? "", ...process13.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
|
|
1757
|
-
const { promise, resolve } = Promise.withResolvers();
|
|
1758
|
-
let received = "";
|
|
1759
|
-
try {
|
|
1760
|
-
await Bun.connect({
|
|
1761
|
-
unix: socketPath,
|
|
1762
|
-
socket: {
|
|
1763
|
-
open: (socket) => void socket.write(`${JSON.stringify(request)}
|
|
1764
|
-
`),
|
|
1765
|
-
data: (_, chunk) => {
|
|
1766
|
-
received += chunk.toString();
|
|
1767
|
-
},
|
|
1768
|
-
close: () => resolve(received),
|
|
1769
|
-
error: () => resolve("")
|
|
1770
|
-
}
|
|
1771
|
-
});
|
|
1772
|
-
} catch {
|
|
1773
|
-
return 1;
|
|
1774
|
-
}
|
|
1775
|
-
const reply = await promise;
|
|
1776
|
-
if (reply === "")
|
|
1777
|
-
return 1;
|
|
1778
|
-
const { answer } = JSON.parse(reply);
|
|
1779
|
-
if (request.notice === true)
|
|
1780
|
-
return 0;
|
|
1781
|
-
if (answer === undefined)
|
|
1782
|
-
return 1;
|
|
1783
|
-
process13.stdout.write(`${answer}
|
|
1784
|
-
`);
|
|
1785
|
-
return 0;
|
|
1786
|
-
}
|
|
1787
|
-
|
|
1788
|
-
// ../kit/src/completions.ts
|
|
1789
|
-
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
1790
|
-
var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
|
|
1791
|
-
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
1792
|
-
set -l current (commandline -ct)
|
|
1793
|
-
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
1794
|
-
if test "$line" = __files__
|
|
1795
|
-
__fish_complete_path $current
|
|
1796
|
-
else
|
|
1797
|
-
echo $line
|
|
1798
|
-
end
|
|
1799
|
-
end
|
|
1800
|
-
end`;
|
|
1801
|
-
var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1802
|
-
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
1803
|
-
local -a lines
|
|
1804
|
-
COMPREPLY=()
|
|
1805
|
-
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
1806
|
-
for line in "\${lines[@]}"; do
|
|
1807
|
-
if [[ $line == __files__ ]]; then
|
|
1808
|
-
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
1809
|
-
else
|
|
1810
|
-
words+="\${line%%$'\\t'*}"$'\\n'
|
|
1811
|
-
fi
|
|
1812
|
-
done
|
|
1813
|
-
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
1814
|
-
}`;
|
|
1815
|
-
var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1816
|
-
local line
|
|
1817
|
-
local -a described plain
|
|
1818
|
-
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
1819
|
-
if [[ $line == __files__ ]]; then
|
|
1820
|
-
_files
|
|
1821
|
-
elif [[ $line == *$'\\t'* ]]; then
|
|
1822
|
-
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
1823
|
-
else
|
|
1824
|
-
plain+=("$line")
|
|
1825
|
-
fi
|
|
1826
|
-
done
|
|
1827
|
-
(( \${#described} )) && _describe -V value described
|
|
1828
|
-
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
1829
|
-
return 0
|
|
1830
|
-
}`;
|
|
1831
|
-
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
1832
|
-
if (shell === "fish")
|
|
1833
|
-
return `${header}
|
|
1834
|
-
${FISH_FUNCTION}
|
|
1835
|
-
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
1836
|
-
`).join("")}`;
|
|
1837
|
-
if (shell === "bash")
|
|
1838
|
-
return `${header}
|
|
1839
|
-
${BASH_FUNCTION}
|
|
1840
|
-
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
1841
|
-
`;
|
|
1842
|
-
return `${header}
|
|
1843
|
-
${ZSH_FUNCTION}
|
|
1844
|
-
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
1845
|
-
`;
|
|
1846
|
-
}
|
|
1847
|
-
|
|
1848
|
-
// ../kit/src/notify.ts
|
|
1849
|
-
init_format();
|
|
1850
|
-
init_mode();
|
|
1851
|
-
import process14 from "process";
|
|
1852
|
-
var NOTIFY_AFTER_MS = 1e4;
|
|
1853
|
-
var CANCELLED = 130;
|
|
1854
|
-
function base64(text) {
|
|
1855
|
-
return Buffer.from(text).toString("base64");
|
|
1856
|
-
}
|
|
1857
|
-
function notification(title, body, env = process14.env) {
|
|
1858
|
-
const id = `kit${process14.pid}`;
|
|
1859
|
-
const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
|
|
1860
|
-
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
1861
|
-
}
|
|
1862
|
-
function notifyEnd(command, code, ms, { stream = process14.stderr, env = process14.env } = {}) {
|
|
1863
|
-
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
1864
|
-
return;
|
|
1865
|
-
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
1866
|
-
}
|
|
1867
|
-
|
|
1868
|
-
// ../kit/src/cli.ts
|
|
1869
|
-
init_style();
|
|
1870
|
-
init_text2();
|
|
1871
|
-
|
|
1872
|
-
// ../kit/src/usage.ts
|
|
1873
|
-
import { appendFileSync, mkdirSync } from "fs";
|
|
1874
|
-
import { homedir as homedir4 } from "os";
|
|
1875
|
-
import { dirname as dirname2, join as join5 } from "path";
|
|
1876
|
-
import process16 from "process";
|
|
1877
|
-
|
|
1878
|
-
// ../kit/src/logs.ts
|
|
1879
|
-
init_user_config();
|
|
1880
|
-
import { lstatSync, openSync } from "fs";
|
|
1881
|
-
import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
|
|
1882
|
-
import { homedir as homedir3, tmpdir } from "os";
|
|
1883
|
-
import { join as join4 } from "path";
|
|
1884
|
-
import process15 from "process";
|
|
1885
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
1886
|
-
var CLI_FOLDER = "kaynooo-cli";
|
|
1887
|
-
function isPrivateDirectory(path) {
|
|
1888
|
-
try {
|
|
1889
|
-
const info = lstatSync(path, { throwIfNoEntry: false });
|
|
1890
|
-
return info !== undefined && info.isDirectory() && info.uid === (process15.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
|
|
1891
|
-
} catch {
|
|
1892
|
-
return false;
|
|
1893
|
-
}
|
|
1894
|
-
}
|
|
1895
|
-
async function privateLogDirectory(name, env = process15.env) {
|
|
1896
|
-
const path = join4(xdgFolder(env.XDG_RUNTIME_DIR, join4(homedir3(), ".cache")), CLI_FOLDER, name);
|
|
1897
|
-
try {
|
|
1898
|
-
await mkdir(path, { recursive: true, mode: 448 });
|
|
1899
|
-
if (isPrivateDirectory(path))
|
|
1900
|
-
return path;
|
|
1901
|
-
} catch {}
|
|
1902
|
-
return mkdtemp(join4(tmpdir(), `${name.replaceAll("/", "-")}-`));
|
|
1903
|
-
}
|
|
1904
|
-
async function sweepLogs(dir, maxAgeMs = DAY_MS, now = Date.now()) {
|
|
1905
|
-
let names;
|
|
1906
|
-
try {
|
|
1907
|
-
names = await readdir(dir);
|
|
1908
|
-
} catch {
|
|
1909
|
-
return;
|
|
1910
|
-
}
|
|
1911
|
-
for (const name of names) {
|
|
1912
|
-
const path = join4(dir, name);
|
|
1913
|
-
try {
|
|
1914
|
-
const info = await stat(path);
|
|
1915
|
-
if (info.isDirectory())
|
|
1916
|
-
await sweepLogs(path, maxAgeMs, now);
|
|
1917
|
-
if (now - info.mtimeMs > maxAgeMs)
|
|
1918
|
-
await rm(path, { force: true, recursive: info.isDirectory() });
|
|
1919
|
-
} catch {
|
|
1920
|
-
continue;
|
|
1921
|
-
}
|
|
1922
|
-
}
|
|
1923
|
-
}
|
|
1924
|
-
|
|
1925
|
-
// ../kit/src/usage.ts
|
|
1926
|
-
init_user_config();
|
|
1927
|
-
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
1928
|
-
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
1929
|
-
var LONGEST_NAME = 40;
|
|
1930
|
-
var usageError;
|
|
1931
|
-
function noteUsageError(message) {
|
|
1932
|
-
usageError = message;
|
|
1933
|
-
}
|
|
1934
|
-
function stateHome(env = process16.env) {
|
|
1935
|
-
return xdgFolder(env.XDG_STATE_HOME, join5(homedir4(), ".local", "state"));
|
|
1936
|
-
}
|
|
1937
|
-
function usagePath(env = process16.env) {
|
|
1938
|
-
return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1939
|
-
}
|
|
1940
|
-
function usageRecorded(env = process16.env) {
|
|
1941
|
-
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1942
|
-
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1943
|
-
}
|
|
1944
|
-
function flagNames(argv) {
|
|
1945
|
-
const end = argv.indexOf("--");
|
|
1946
|
-
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
1947
|
-
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
1948
|
-
}
|
|
1949
|
-
function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
|
|
1950
|
-
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
1951
|
-
usageError = undefined;
|
|
1952
|
-
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
|
|
1953
|
-
}
|
|
1954
|
-
function recordUsage(entry, env = process16.env) {
|
|
1955
|
-
if (!usageRecorded(env))
|
|
1956
|
-
return;
|
|
1957
|
-
try {
|
|
1958
|
-
const path = usagePath(env);
|
|
1959
|
-
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
1960
|
-
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1961
|
-
`, { mode: 384 });
|
|
1962
|
-
} catch {}
|
|
1963
|
-
}
|
|
1964
|
-
|
|
1965
|
-
// ../kit/src/cli.ts
|
|
1966
|
-
var LEVEL_OPTIONS = {
|
|
1967
|
-
...OUTPUT_OPTIONS,
|
|
1968
|
-
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1969
|
-
};
|
|
1970
|
-
var TOP_OPTIONS = {
|
|
1971
|
-
...LEVEL_OPTIONS,
|
|
1972
|
-
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1973
|
-
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1974
|
-
};
|
|
1975
|
-
function printError(prefix, message, hint, cause) {
|
|
1976
|
-
const colors = paint(process17.stderr);
|
|
1977
|
-
const styled = takesControlCodes(process17.stderr);
|
|
1978
|
-
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1979
|
-
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1980
|
-
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1981
|
-
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1982
|
-
}
|
|
1983
|
-
function printJsonError(message, hint, cause) {
|
|
1984
|
-
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1985
|
-
}
|
|
1986
|
-
function wantsJson(argv) {
|
|
1987
|
-
const end = argv.indexOf("--");
|
|
1988
|
-
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1989
|
-
}
|
|
1990
|
-
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1991
|
-
if (error instanceof HelpShown)
|
|
1992
|
-
return 0;
|
|
1993
|
-
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1994
|
-
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1995
|
-
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1996
|
-
if (error instanceof Exit && error.code === 2)
|
|
1997
|
-
noteUsageError(error.message);
|
|
1998
|
-
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1999
|
-
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
2000
|
-
return error instanceof Exit ? error.code : 1;
|
|
2001
|
-
}
|
|
2002
|
-
var COMPLETE = "__complete";
|
|
2003
|
-
var FILES = "__files__";
|
|
2004
|
-
async function completingOf(run) {
|
|
2005
|
-
completion.active = true;
|
|
2006
|
-
try {
|
|
2007
|
-
await run([]);
|
|
2008
|
-
} catch (error) {
|
|
2009
|
-
if (error instanceof Completing)
|
|
2010
|
-
return error;
|
|
2011
|
-
} finally {
|
|
2012
|
-
completion.active = false;
|
|
2013
|
-
}
|
|
2014
|
-
return new Completing({});
|
|
2015
|
-
}
|
|
2016
|
-
function candidateLine(candidate) {
|
|
2017
|
-
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
2018
|
-
}
|
|
2019
|
-
function positionalBeingTyped(before, { options, positionals }) {
|
|
2020
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
2021
|
-
const typed = [];
|
|
2022
|
-
let at = 0;
|
|
2023
|
-
while (at < before.length) {
|
|
2024
|
-
const word = before[at];
|
|
2025
|
-
if (word === "--") {
|
|
2026
|
-
typed.push(...before.slice(at + 1));
|
|
2027
|
-
break;
|
|
2028
|
-
}
|
|
2029
|
-
if (!word.startsWith("-"))
|
|
2030
|
-
typed.push(word);
|
|
2031
|
-
else if (takesValue(word))
|
|
2032
|
-
at++;
|
|
2033
|
-
at++;
|
|
2034
|
-
}
|
|
2035
|
-
const last = positionals.at(-1);
|
|
2036
|
-
if (typed.length < positionals.length)
|
|
2037
|
-
return { name: positionals[typed.length], typed };
|
|
2038
|
-
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
2039
|
-
}
|
|
2040
|
-
async function leafCandidates(run, words) {
|
|
2041
|
-
const completing = await completingOf(run);
|
|
2042
|
-
if ((words.at(-1) ?? "").startsWith("-"))
|
|
2043
|
-
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
2044
|
-
const flag = words.at(-2);
|
|
2045
|
-
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
2046
|
-
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
2047
|
-
if (option?.type === "string") {
|
|
2048
|
-
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
2049
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
2050
|
-
}
|
|
2051
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
2052
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
2053
|
-
}
|
|
2054
|
-
var COMPLETIONS = "--completions";
|
|
2055
|
-
function flagValue([flag = "", ...rest]) {
|
|
2056
|
-
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
2057
|
-
}
|
|
2058
|
-
function printCompletionScript(name, args) {
|
|
2059
|
-
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
2060
|
-
if (shell === undefined || args.length !== 1) {
|
|
2061
|
-
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
2062
|
-
return 2;
|
|
2063
|
-
}
|
|
2064
|
-
console.log(completionScript(shell, [name]).trimEnd());
|
|
2065
|
-
return 0;
|
|
2066
|
-
}
|
|
2067
|
-
async function printCandidates(found) {
|
|
2068
|
-
for (const line of await found)
|
|
2069
|
-
console.log(line);
|
|
2070
|
-
return 0;
|
|
2071
|
-
}
|
|
2072
|
-
function packageVersion(entry = Bun.main) {
|
|
2073
|
-
let resolved = entry;
|
|
2074
|
-
try {
|
|
2075
|
-
resolved = realpathSync2(entry);
|
|
2076
|
-
} catch {}
|
|
2077
|
-
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
2078
|
-
try {
|
|
2079
|
-
const { version } = JSON.parse(readFileSync5(join6(dir, "package.json"), "utf8"));
|
|
2080
|
-
if (typeof version === "string")
|
|
2081
|
-
return version;
|
|
2082
|
-
} catch {}
|
|
2083
|
-
if (dirname3(dir) === dir)
|
|
2084
|
-
return "0.0.0";
|
|
2085
|
-
}
|
|
2086
|
-
}
|
|
2087
|
-
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
2088
|
-
const answered = await askpassClient(argv);
|
|
2089
|
-
if (answered !== undefined)
|
|
2090
|
-
return answered;
|
|
2091
|
-
if (argv[0] === COMPLETE)
|
|
2092
|
-
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
2093
|
-
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
2094
|
-
return printCompletionScript(name, flagValue(argv));
|
|
2095
|
-
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
2096
|
-
console.log(version ?? packageVersion());
|
|
2097
|
-
return 0;
|
|
2098
|
-
}
|
|
2099
|
-
let code;
|
|
2100
|
-
const started = performance.now();
|
|
2101
|
-
heading.bin = { name, version: () => version ?? packageVersion() };
|
|
2102
|
-
try {
|
|
2103
|
-
code = await run(argv);
|
|
2104
|
-
} catch (error) {
|
|
2105
|
-
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
2106
|
-
} finally {
|
|
2107
|
-
heading.bin = undefined;
|
|
2108
|
-
}
|
|
2109
|
-
notifyEnd(name, code, performance.now() - started);
|
|
2110
|
-
if (usage !== false) {
|
|
2111
|
-
try {
|
|
2112
|
-
recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
|
|
2113
|
-
} catch {}
|
|
2114
|
-
}
|
|
2115
|
-
return code;
|
|
2116
|
-
}
|
|
2117
|
-
|
|
2118
|
-
// ../kit/src/index.ts
|
|
2119
|
-
init_config();
|
|
2120
|
-
|
|
2121
|
-
// ../kit/src/excerpt.ts
|
|
2122
|
-
init_text2();
|
|
2123
|
-
var BASH_ECHO = /^\$ /;
|
|
2124
|
-
var DURATION2 = / \[[\d.]+m?s\]$/;
|
|
2125
|
-
var BOUNDARY = /^(?:\((?:pass|fail|skip|todo)\) |\S+\.test\.[jt]sx?:$)/;
|
|
2126
|
-
var BUN_TEST_SUMMARY = /^\s*\d+ (?:pass|fail|skip|todo)$|^Ran \d+ tests?/;
|
|
2127
|
-
var BUN_CHECK_BLOCK = /<error file=[\s\S]*?<\/error>/g;
|
|
2128
|
-
var BUN_CHECK_SOURCE = /<source>[\s\S]*?<\/source>\n?/g;
|
|
2129
|
-
var BUN_CHECK_ATTRIBUTE = /(\w+)="([^"]*)"/g;
|
|
2130
|
-
var BUN_CHECK_SUMMARY = /^Found \d+ errors?/;
|
|
2131
|
-
var TSC_ERROR = /\berror TS\d+/;
|
|
2132
|
-
var TSC_CONTINUATION = /^\s{2,}\S/;
|
|
2133
|
-
var TSC_FRAME = /^\s*[~^|]/;
|
|
2134
|
-
var TSC_SUMMARY = /^Found \d+ errors?/;
|
|
2135
|
-
var ESLINT_PROBLEM = /^\s+\d+:\d+\s+(?:error|warning)\s/;
|
|
2136
|
-
var ESLINT_SUMMARY = /^(?:\u2716 )?\d+ problems? \(/;
|
|
2137
|
-
var PHPSTAN_TABLE = /^\s*-{3,} -{3,}/;
|
|
2138
|
-
var PHPSTAN_NOISE = /^\s*\[OK\]/;
|
|
2139
|
-
var PHP_FAILURES = /^(?:There w(?:as|ere) \d+ (?:failure|error|risky|warning)|\s+(?:FAIL|FAILED)\s+\S|In \S+\.php line \d+:$)/;
|
|
2140
|
-
var VITEST_FAIL_LINE = /^ FAIL {2}\S/;
|
|
2141
|
-
var PLAYWRIGHT_FAIL_LINE = /^ {2}1\) .+:\d+:\d+ \u203A .+ \u2500+$/;
|
|
2142
|
-
var CS_FIXER_LINE = /^\s+\d+\) \S.*\.php(?: \(.+\))?$/;
|
|
2143
|
-
var CS_FIXER_TOTAL = /^Found \d+ of \d+ files/;
|
|
2144
|
-
var MAX_TESTS = 10;
|
|
2145
|
-
var MAX_LINES = 100;
|
|
2146
|
-
var TAIL = 30;
|
|
2147
|
-
var bunTest = (lines) => {
|
|
2148
|
-
const seen = new Set;
|
|
2149
|
-
const blocks = [];
|
|
2150
|
-
for (const [index, line] of lines.entries()) {
|
|
2151
|
-
const name = line.replace(DURATION2, "");
|
|
2152
|
-
if (!line.startsWith("(fail) ") || seen.has(name))
|
|
2153
|
-
continue;
|
|
2154
|
-
seen.add(name);
|
|
2155
|
-
if (blocks.length < MAX_TESTS)
|
|
2156
|
-
blocks.push(lines.slice(lines.findLastIndex((text, at) => at < index && BOUNDARY.test(text)) + 1, index + 1).join(`
|
|
2157
|
-
`).trim());
|
|
2158
|
-
}
|
|
2159
|
-
if (blocks.length === 0)
|
|
2160
|
-
return;
|
|
2161
|
-
if (seen.size > MAX_TESTS)
|
|
2162
|
-
blocks.push(`and ${seen.size - MAX_TESTS} more failed tests`);
|
|
2163
|
-
return [...blocks.join(`
|
|
2164
|
-
|
|
2165
|
-
`).split(`
|
|
2166
|
-
`), "", ...lines.filter((line) => BUN_TEST_SUMMARY.test(line)).map((line) => line.trim())];
|
|
2167
|
-
};
|
|
2168
|
-
var bunCheck = (lines) => {
|
|
2169
|
-
const text = lines.join(`
|
|
2170
|
-
`);
|
|
2171
|
-
const blocks = text.match(BUN_CHECK_BLOCK);
|
|
2172
|
-
if (blocks === null)
|
|
2173
|
-
return;
|
|
2174
|
-
const errors = blocks.map((block) => {
|
|
2175
|
-
const { file, line, column, code, message } = bunCheckFields(block);
|
|
2176
|
-
return `${file}:${line}:${column} ${code}: ${message}`;
|
|
2177
|
-
});
|
|
2178
|
-
return [...errors, ...lines.filter((line) => BUN_CHECK_SUMMARY.test(line))];
|
|
2179
|
-
};
|
|
2180
|
-
function bunCheckFields(block) {
|
|
2181
|
-
const attributes = Object.fromEntries([...block.slice(0, block.indexOf(`
|
|
2182
|
-
`)).matchAll(BUN_CHECK_ATTRIBUTE)].map((match) => [match[1] ?? "", match[2] ?? ""]));
|
|
2183
|
-
return {
|
|
2184
|
-
file: attributes.file ?? "",
|
|
2185
|
-
line: attributes.line ?? "",
|
|
2186
|
-
column: attributes.column ?? "",
|
|
2187
|
-
code: attributes.code ?? "",
|
|
2188
|
-
message: block.replace(BUN_CHECK_SOURCE, "").split(`
|
|
2189
|
-
`).slice(1, -1).join(`
|
|
2190
|
-
`).trim()
|
|
2191
|
-
};
|
|
2192
|
-
}
|
|
2193
|
-
var tsc = (lines) => {
|
|
2194
|
-
const kept = [];
|
|
2195
|
-
let inError = false;
|
|
2196
|
-
for (const line of lines) {
|
|
2197
|
-
if (TSC_ERROR.test(line)) {
|
|
2198
|
-
inError = true;
|
|
2199
|
-
kept.push(line);
|
|
2200
|
-
} else if (TSC_SUMMARY.test(line)) {
|
|
2201
|
-
inError = false;
|
|
2202
|
-
kept.push(line);
|
|
2203
|
-
} else if (inError && TSC_CONTINUATION.test(line) && !TSC_FRAME.test(line)) {
|
|
2204
|
-
kept.push(line);
|
|
2205
|
-
} else {
|
|
2206
|
-
inError = false;
|
|
2207
|
-
}
|
|
2208
|
-
}
|
|
2209
|
-
return kept.some((line) => TSC_ERROR.test(line)) ? kept : undefined;
|
|
2210
|
-
};
|
|
2211
|
-
var eslint = (lines) => {
|
|
2212
|
-
const kept = [];
|
|
2213
|
-
let file = "";
|
|
2214
|
-
let shown = "";
|
|
2215
|
-
for (const line of lines) {
|
|
2216
|
-
if (ESLINT_PROBLEM.test(line)) {
|
|
2217
|
-
if (file !== shown) {
|
|
2218
|
-
kept.push(file);
|
|
2219
|
-
shown = file;
|
|
2220
|
-
}
|
|
2221
|
-
kept.push(line);
|
|
2222
|
-
} else if (ESLINT_SUMMARY.test(line)) {
|
|
2223
|
-
kept.push(line);
|
|
2224
|
-
} else if (line.trim() !== "") {
|
|
2225
|
-
file = line;
|
|
2226
|
-
}
|
|
2227
|
-
}
|
|
2228
|
-
return kept.some((line) => ESLINT_PROBLEM.test(line)) ? kept : undefined;
|
|
2229
|
-
};
|
|
2230
|
-
var phpstan = (lines) => {
|
|
2231
|
-
const start = lines.findIndex((line) => PHPSTAN_TABLE.test(line));
|
|
2232
|
-
return start === -1 ? undefined : lines.slice(start).filter((line) => !PHPSTAN_NOISE.test(line));
|
|
2233
|
-
};
|
|
2234
|
-
var php = (lines) => {
|
|
2235
|
-
const start = lines.findIndex((line) => PHP_FAILURES.test(line));
|
|
2236
|
-
return start === -1 ? undefined : lines.slice(start);
|
|
2237
|
-
};
|
|
2238
|
-
var vitest = (lines) => {
|
|
2239
|
-
const start = lines.findIndex((line) => VITEST_FAIL_LINE.test(line));
|
|
2240
|
-
return start === -1 ? undefined : lines.slice(start);
|
|
2241
|
-
};
|
|
2242
|
-
var playwright = (lines) => {
|
|
2243
|
-
const start = lines.findIndex((line) => PLAYWRIGHT_FAIL_LINE.test(line));
|
|
2244
|
-
return start === -1 ? undefined : lines.slice(start);
|
|
2245
|
-
};
|
|
2246
|
-
var phpCsFixer = (lines) => {
|
|
2247
|
-
const files = lines.filter((line) => CS_FIXER_LINE.test(line) || CS_FIXER_TOTAL.test(line));
|
|
2248
|
-
return files.some((line) => CS_FIXER_LINE.test(line)) ? files : undefined;
|
|
2249
|
-
};
|
|
2250
|
-
var PARSERS = [bunTest, bunCheck, tsc, eslint, vitest, playwright, phpCsFixer, phpstan, php];
|
|
2251
|
-
function squeeze(lines) {
|
|
2252
|
-
const out = [];
|
|
2253
|
-
for (const line of lines.map((text) => text.trimEnd())) {
|
|
2254
|
-
if (line !== "" || out.at(-1) !== "")
|
|
2255
|
-
out.push(line);
|
|
2256
|
-
}
|
|
2257
|
-
while (out.at(-1) === "")
|
|
2258
|
-
out.pop();
|
|
2259
|
-
return out;
|
|
2260
|
-
}
|
|
2261
|
-
function cut(shown) {
|
|
2262
|
-
return shown.length > MAX_LINES ? [...shown.slice(0, MAX_LINES), `... ${shown.length - MAX_LINES} more lines`].join(`
|
|
2263
|
-
`) : shown.join(`
|
|
2264
|
-
`);
|
|
2265
|
-
}
|
|
2266
|
-
function recognised(lines, parsers) {
|
|
2267
|
-
return parsers.map((parser) => parser(lines)).find((result) => result !== undefined && result.some((line) => line.trim() !== ""));
|
|
2268
|
-
}
|
|
2269
|
-
function failureExcerpt(output) {
|
|
2270
|
-
const lines = stripAnsi(output).split(`
|
|
2271
|
-
`);
|
|
2272
|
-
if (BASH_ECHO.test(lines[0] ?? ""))
|
|
2273
|
-
lines.shift();
|
|
2274
|
-
return cut(squeeze(recognised(lines, PARSERS) ?? lines.slice(-TAIL)));
|
|
2275
|
-
}
|
|
2276
|
-
var LOG_PATTERNS = { BASH_ECHO, DURATION: DURATION2, BOUNDARY, BUN_TEST_SUMMARY, BUN_CHECK_SUMMARY, TSC_CONTINUATION, TSC_FRAME, TSC_SUMMARY, ESLINT_PROBLEM, ESLINT_SUMMARY };
|
|
2277
|
-
|
|
2278
|
-
// ../kit/src/index.ts
|
|
2279
|
-
init_folders();
|
|
2280
|
-
init_format();
|
|
2281
|
-
|
|
2282
|
-
// ../kit/src/git.ts
|
|
2283
|
-
init_args();
|
|
2284
|
-
// ../kit/src/limit.ts
|
|
2285
|
-
init_args();
|
|
2286
|
-
|
|
2287
|
-
// ../kit/src/index.ts
|
|
2288
|
-
init_mode();
|
|
2289
|
-
|
|
2290
|
-
// ../kit/src/report.ts
|
|
2291
|
-
init_style();
|
|
2292
|
-
init_text2();
|
|
2293
|
-
// ../kit/src/secrets.ts
|
|
2294
|
-
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
2295
|
-
var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
|
|
2296
|
-
// ../kit/src/sessions.ts
|
|
2297
|
-
var {Glob } = globalThis.Bun;
|
|
2298
|
-
var SESSION_FILES = new Glob("*.json");
|
|
2299
|
-
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
2300
|
-
|
|
2301
|
-
// ../kit/src/index.ts
|
|
2302
|
-
init_style();
|
|
2303
|
-
init_text2();
|
|
2304
|
-
init_theme();
|
|
2305
|
-
init_user_config();
|
|
2306
|
-
|
|
2307
|
-
// ../kit/src/watch.ts
|
|
2308
|
-
init_args();
|
|
2309
|
-
init_input();
|
|
2310
|
-
init_style();
|
|
2311
|
-
// ../kit/src/workspace-root.ts
|
|
2312
|
-
init_user_config();
|
|
2313
|
-
// package.json
|
|
2314
|
-
var version = "0.22.2";
|
|
2315
|
-
|
|
2316
|
-
// src/j.ts
|
|
2317
|
-
import process26 from "process";
|
|
2318
|
-
|
|
2319
|
-
// ../kit/src/picker.ts
|
|
2320
|
-
init_folders();
|
|
2321
|
-
init_state();
|
|
2322
|
-
import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync6, writeFileSync } from "fs";
|
|
2323
|
-
import { dirname as dirname4, join as join8 } from "path";
|
|
2324
|
-
import process23 from "process";
|
|
2325
|
-
|
|
2326
|
-
// ../kit/src/picker/terminal.ts
|
|
2327
|
-
init_args();
|
|
2328
|
-
init_job();
|
|
2329
|
-
init_redraw();
|
|
2330
|
-
init_style();
|
|
2331
|
-
import { openSync as openSync2 } from "fs";
|
|
2332
|
-
import process22 from "process";
|
|
2333
|
-
import tty from "tty";
|
|
2334
|
-
|
|
2335
|
-
// ../kit/src/picker/preview.ts
|
|
2336
|
-
import process21 from "process";
|
|
2337
|
-
|
|
2338
|
-
// ../kit/src/shell.ts
|
|
2339
|
-
var SEPARATORS = new Set([`
|
|
2340
|
-
`, ";", "|"]);
|
|
2341
|
-
var PLAIN_BREAKERS = new Set(["<", ">", "(", ")", "&", "|"]);
|
|
2342
|
-
var GLOB_CHARS = new Set(["*", "?", "["]);
|
|
2343
|
-
var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
|
|
2344
|
-
var SAFE_WORD = /^[\w@%+=:,./-]+$/;
|
|
2345
|
-
var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
|
|
2346
|
-
var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
|
|
2347
|
-
var FISH_COMBINERS = new Set(["and", "or", "not"]);
|
|
2348
|
-
var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
|
|
2349
|
-
var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
|
|
2350
|
-
var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
|
|
2351
|
-
var POWERSHELL = new Set(["pwsh", "powershell"]);
|
|
2352
|
-
var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
|
|
2353
|
-
var FISH_VALUE_OPTIONS = new Set(["-C", "--init-command"]);
|
|
2354
|
-
var PRINTERS = new Set(["echo", "printf"]);
|
|
2355
|
-
var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
|
|
2356
|
-
function wrapper(short = "", long = [], operands = 0, runsString = false) {
|
|
2357
|
-
return { short, long, operands, runsString };
|
|
2358
|
-
}
|
|
2359
|
-
var RUNNER = { ...wrapper(), afterDashes: true };
|
|
2360
|
-
var WRAPPERS = new Map([
|
|
2361
|
-
["command", wrapper()],
|
|
2362
|
-
["builtin", wrapper()],
|
|
2363
|
-
["nohup", wrapper()],
|
|
2364
|
-
["setsid", wrapper()],
|
|
2365
|
-
["busybox", wrapper()],
|
|
2366
|
-
["exec", wrapper("a")],
|
|
2367
|
-
["time", wrapper("fo", ["--format", "--output"])],
|
|
2368
|
-
["env", wrapper("uCS", ["--unset", "--chdir", "--split-string", "--argv0"])],
|
|
2369
|
-
["sudo", wrapper("ughpCTrtUDR", ["--user", "--group", "--host", "--prompt", "--close-from", "--command-timeout", "--role", "--type", "--other-user", "--chdir", "--chroot"])],
|
|
2370
|
-
["doas", wrapper("uC")],
|
|
2371
|
-
["timeout", wrapper("sk", ["--signal", "--kill-after"], 1)],
|
|
2372
|
-
["nice", wrapper("n", ["--adjustment"])],
|
|
2373
|
-
["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
|
|
2374
|
-
["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
|
|
2375
|
-
["chroot", wrapper("", ["--userspec", "--groups"], 1)],
|
|
2376
|
-
["watch", wrapper("n", ["--interval"], 0, true)],
|
|
2377
|
-
["flock", wrapper("wE", ["--timeout", "--conflict-exit-code"], 1)],
|
|
2378
|
-
["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
|
|
2379
|
-
["unbuffer", wrapper()],
|
|
2380
|
-
["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
|
|
2381
|
-
["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])],
|
|
2382
|
-
["strace", wrapper("abeEIoOpPsSuUX", ["--trace", "--output", "--attach", "--string-limit", "--user", "--env", "--columns", "--trace-path", "--signal", "--status", "--summary-sort-by", "--summary-columns", "--const-print-style", "--interruptible", "--detach-on"])],
|
|
2383
|
-
["ltrace", wrapper("aeFlnopsuxX", ["--output", "--user", "--library", "--config", "--align", "--indent"])],
|
|
2384
|
-
["taskset", wrapper("", [], 1)],
|
|
2385
|
-
["fakeroot", wrapper("lsib", ["--lib", "--faked"])],
|
|
2386
|
-
["sshpass", wrapper("pfdP")],
|
|
2387
|
-
["coproc", wrapper()],
|
|
2388
|
-
["proxychains", wrapper("f")],
|
|
2389
|
-
["proxychains4", wrapper("f")],
|
|
2390
|
-
["torsocks", wrapper("upaP", ["--user", "--pass", "--address", "--port"])],
|
|
2391
|
-
["chrt", wrapper("TPD", ["--sched-runtime", "--sched-period", "--sched-deadline"], 1)],
|
|
2392
|
-
["unshare", wrapper("SGRw", ["--setuid", "--setgid", "--root", "--wd", "--map-user", "--map-group", "--map-users", "--map-groups", "--propagation", "--setgroups"])],
|
|
2393
|
-
["nsenter", wrapper("tSG", ["--target", "--setuid", "--setgid"])],
|
|
2394
|
-
["out", RUNNER],
|
|
2395
|
-
["slot", RUNNER],
|
|
2396
|
-
["waitfor", RUNNER],
|
|
2397
|
-
["base", RUNNER]
|
|
2398
|
-
]);
|
|
2399
|
-
function shellQuote(word) {
|
|
2400
|
-
return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
|
|
2401
|
-
}
|
|
2402
|
-
|
|
2403
|
-
// ../kit/src/picker/preview.ts
|
|
2404
|
-
var PREVIEW_BYTES = 64 * 1024;
|
|
2405
|
-
var PREVIEW_LINES = 200;
|
|
2406
|
-
var PREVIEW_TIMEOUT_MS = 3000;
|
|
2407
|
-
var PLACEHOLDER = /\{([1-9]\d*)?\}/g;
|
|
2408
|
-
function previewCommand(template, line, hidden = []) {
|
|
2409
|
-
return template.replace(PLACEHOLDER, (_, field) => shellQuote(field === undefined ? line : hidden[Number(field) - 1] ?? ""));
|
|
2410
|
-
}
|
|
2411
|
-
function previewLines(output) {
|
|
2412
|
-
const lines = output.split(`
|
|
2413
|
-
`);
|
|
2414
|
-
if (lines.at(-1) === "")
|
|
2415
|
-
lines.pop();
|
|
2416
|
-
return lines.slice(0, PREVIEW_LINES);
|
|
2417
|
-
}
|
|
2418
|
-
async function runPreview(template, line, signal, hidden = []) {
|
|
2419
|
-
const proc = Bun.spawn(["sh", "-c", `exec 2>&1
|
|
2420
|
-
${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
|
|
2421
|
-
const stop = () => {
|
|
2422
|
-
try {
|
|
2423
|
-
process21.kill(-proc.pid, "SIGKILL");
|
|
2424
|
-
} catch {
|
|
2425
|
-
proc.kill();
|
|
2426
|
-
}
|
|
2427
|
-
};
|
|
2428
|
-
const timer = setTimeout(stop, PREVIEW_TIMEOUT_MS);
|
|
2429
|
-
const chunks = [];
|
|
2430
|
-
let size = 0;
|
|
2431
|
-
signal.addEventListener("abort", stop);
|
|
2432
|
-
try {
|
|
2433
|
-
for await (const chunk of proc.stdout) {
|
|
2434
|
-
chunks.push(chunk);
|
|
2435
|
-
size += chunk.length;
|
|
2436
|
-
if (size >= PREVIEW_BYTES) {
|
|
2437
|
-
stop();
|
|
2438
|
-
break;
|
|
2439
|
-
}
|
|
2440
|
-
}
|
|
2441
|
-
} finally {
|
|
2442
|
-
clearTimeout(timer);
|
|
2443
|
-
signal.removeEventListener("abort", stop);
|
|
2444
|
-
}
|
|
2445
|
-
return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
|
|
2446
|
-
}
|
|
2447
|
-
|
|
2448
|
-
// ../kit/src/picker/terminal.ts
|
|
2449
|
-
init_state();
|
|
2450
|
-
|
|
2451
|
-
// ../kit/src/picker/view.ts
|
|
2452
|
-
init_line();
|
|
2453
|
-
init_state();
|
|
2454
|
-
var MIN_HEIGHT = 4;
|
|
2455
|
-
var PREVIEW_MIN_COLUMNS = 80;
|
|
2456
|
-
var PREVIEW_MIN_ROWS = 10;
|
|
2457
|
-
var PREVIEW_SHARE = 0.4;
|
|
2458
|
-
var RESET2 = "\x1B[0m";
|
|
2459
|
-
var SEPARATOR = " \u2502 ";
|
|
2460
|
-
var HEIGHT = /^(\d+)(%?)$/;
|
|
2461
|
-
function parseHeight(text) {
|
|
2462
|
-
const found = HEIGHT.exec(text);
|
|
2463
|
-
if (found === null || Number(found[1]) < 1)
|
|
2464
|
-
return;
|
|
2465
|
-
return found[2] === "%" ? { percent: Math.min(100, Number(found[1])) } : { lines: Number(found[1]) };
|
|
2466
|
-
}
|
|
2467
|
-
function layoutFor(size, height, previewing, position = "right") {
|
|
2468
|
-
const wanted = "lines" in height ? height.lines : Math.round(size.rows * height.percent / 100);
|
|
2469
|
-
const rows = Math.min(size.rows, Math.max(MIN_HEIGHT, wanted));
|
|
2470
|
-
if (position === "down") {
|
|
2471
|
-
const previewHeight = previewing && rows >= PREVIEW_MIN_ROWS ? Math.round(rows * PREVIEW_SHARE) : 0;
|
|
2472
|
-
return { height: rows, listHeight: rows - previewHeight, listWidth: size.columns, previewWidth: 0, previewHeight };
|
|
2473
|
-
}
|
|
2474
|
-
const split = previewing && size.columns >= PREVIEW_MIN_COLUMNS;
|
|
2475
|
-
const listWidth = split ? Math.floor(size.columns / 2) : size.columns;
|
|
2476
|
-
return { height: rows, listHeight: rows, listWidth, previewWidth: split ? size.columns - listWidth - SEPARATOR.length : 0, previewHeight: 0 };
|
|
2477
|
-
}
|
|
2478
|
-
function fit(text, width, plain, mark = plain, marked = new Set, styles) {
|
|
2479
|
-
const room = Bun.stringWidth(text) > width ? width - 1 : width;
|
|
2480
|
-
let out = "";
|
|
2481
|
-
let used = 0;
|
|
2482
|
-
let at = 0;
|
|
2483
|
-
for (const char of text) {
|
|
2484
|
-
const size = Bun.stringWidth(char);
|
|
2485
|
-
if (used + size > room)
|
|
2486
|
-
break;
|
|
2487
|
-
const style = marked.has(at) ? "" : styles?.[at] ?? "";
|
|
2488
|
-
out += style === "" ? (marked.has(at) ? mark : plain)(char) : `${style}${char}${RESET2}`;
|
|
2489
|
-
used += size;
|
|
2490
|
-
at += char.length;
|
|
2491
|
-
}
|
|
2492
|
-
if (room < width) {
|
|
2493
|
-
out += plain("\u2026");
|
|
2494
|
-
used += 1;
|
|
2495
|
-
}
|
|
2496
|
-
return { text: out, width: used };
|
|
2497
|
-
}
|
|
2498
|
-
var identity = (text) => text;
|
|
2499
|
-
function fitStyled(line, width, plain = identity) {
|
|
2500
|
-
const { text, styles } = styled(line);
|
|
2501
|
-
return fit(text, width, plain, plain, new Set, styles);
|
|
2502
|
-
}
|
|
2503
|
-
function queryShown(state, layout) {
|
|
2504
|
-
return visible({ text: state.query, caret: state.caret }, Math.max(1, layout.listWidth - Bun.stringWidth(state.prompt)));
|
|
2505
|
-
}
|
|
2506
|
-
function caretCell(state, layout) {
|
|
2507
|
-
const shown = queryShown(state, layout);
|
|
2508
|
-
return { column: Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + shown.column + 1), char: shown.at ?? " " };
|
|
2509
|
-
}
|
|
2510
|
-
function helpLines(state, layout, theme) {
|
|
2511
|
-
const lines = [
|
|
2512
|
-
"type to filter, up, down, ctrl-p, ctrl-n, pgup, pgdn, home, end, the wheel move",
|
|
2513
|
-
"left, right, ctrl-a, ctrl-e move in the query, ctrl or alt with left or right by a word",
|
|
2514
|
-
"ctrl-w or ctrl-backspace erase a word, ctrl-u back to the start, ctrl-k to the end, del ahead",
|
|
2515
|
-
"ctrl-y puts back what they erased, ctrl-z suspends to the shell",
|
|
2516
|
-
`enter picks${state.multi ? ", tab marks" : ""}, esc or ctrl-c cancels`,
|
|
2517
|
-
...state.expect.length > 0 ? [`${state.expect.join(", ")} end the pick as this command asks`] : []
|
|
2518
|
-
];
|
|
2519
|
-
const title = "keys, any key closes this help";
|
|
2520
|
-
return [{ text: theme.accent(title), width: title.length }, ...lines.map((line) => fit(` ${line}`, layout.listWidth, theme.label))];
|
|
2521
|
-
}
|
|
2522
|
-
function listLines(state, layout, theme) {
|
|
2523
|
-
if (state.help)
|
|
2524
|
-
return helpLines(state, layout, theme);
|
|
2525
|
-
const header = state.header === "" ? [] : state.header.split(`
|
|
2526
|
-
`).map((line) => fitStyled(line, layout.listWidth, theme.label));
|
|
2527
|
-
const rows = Math.max(1, layout.listHeight - 2 - header.length);
|
|
2528
|
-
const prefixWidth = state.multi ? 4 : 2;
|
|
2529
|
-
const top = Math.max(0, Math.min(state.cursor - Math.floor(rows / 2), state.matches.length - rows));
|
|
2530
|
-
const marks = (state.marked.size > 0 ? ` (${state.marked.size} marked)` : "") + (state.status === "" ? "" : ` ${state.status}`);
|
|
2531
|
-
const promptWidth = Bun.stringWidth(state.prompt);
|
|
2532
|
-
const shown = queryShown(state, layout);
|
|
2533
|
-
const text = `${shown.before}${shown.at ?? ""}${shown.after}`;
|
|
2534
|
-
const query = { text, width: Bun.stringWidth(text) };
|
|
2535
|
-
const place = state.matches.length > rows ? ` (${state.cursor + 1} of ${state.matches.length})` : "";
|
|
2536
|
-
const count = fit(` ${state.matches.length}/${state.items.length}${place}${marks} ctrl-/ keys`, layout.listWidth, theme.label);
|
|
2537
|
-
const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count, ...header];
|
|
2538
|
-
if (state.matches.length === 0)
|
|
2539
|
-
lines.push(fit(" no match", layout.listWidth, theme.label));
|
|
2540
|
-
for (const [offset, match] of state.matches.slice(top, top + rows).entries()) {
|
|
2541
|
-
const current = top + offset === state.cursor;
|
|
2542
|
-
const pointer = current ? theme.accent("\u276F") : " ";
|
|
2543
|
-
const mark = state.multi ? `${state.marked.has(match.index) ? theme.id("\u25CF") : " "} ` : "";
|
|
2544
|
-
const text = fit(state.items[match.index], layout.listWidth - prefixWidth, current ? theme.value : identity, theme.match ?? theme.accent, new Set(match.positions), state.styles[match.index]);
|
|
2545
|
-
lines.push({ text: `${pointer} ${mark}${text.text}`, width: prefixWidth + text.width });
|
|
2546
|
-
}
|
|
2547
|
-
return lines;
|
|
2548
|
-
}
|
|
2549
|
-
function render(state, layout, theme, preview = []) {
|
|
2550
|
-
const left = listLines(state, layout, theme);
|
|
2551
|
-
return Array.from({ length: layout.height }, (_, row) => {
|
|
2552
|
-
if (row >= layout.listHeight)
|
|
2553
|
-
return row === layout.listHeight ? theme.label("\u2500".repeat(layout.listWidth)) : fitStyled(preview[row - layout.listHeight - 1] ?? "", layout.listWidth).text;
|
|
2554
|
-
const list = left[row] ?? { text: "", width: 0 };
|
|
2555
|
-
if (layout.previewWidth === 0)
|
|
2556
|
-
return list.text;
|
|
2557
|
-
return `${list.text}${" ".repeat(Math.max(0, layout.listWidth - list.width))}${theme.label(SEPARATOR)}${fitStyled(preview[row] ?? "", layout.previewWidth).text}`;
|
|
2558
|
-
});
|
|
2559
|
-
}
|
|
2560
|
-
|
|
2561
|
-
// ../kit/src/picker/terminal.ts
|
|
2562
|
-
var PREVIEW_DELAY_MS = 120;
|
|
2563
|
-
var ESCAPE_WAIT_MS = 30;
|
|
2564
|
-
var OPEN = { ctrl: "open" };
|
|
2565
|
-
var HIDE_CURSOR = "\x1B[?25l";
|
|
2566
|
-
var SHOW_CURSOR = "\x1B[?25h";
|
|
2567
|
-
var REVERSE = "\x1B[7m";
|
|
2568
|
-
var REVERSE_END = "\x1B[27m";
|
|
2569
|
-
var PASTE_ON = "\x1B[?2004h";
|
|
2570
|
-
var PASTE_OFF = "\x1B[?2004l";
|
|
2571
|
-
var MOUSE_ON = "\x1B[?1000h\x1B[?1006h";
|
|
2572
|
-
var MOUSE_OFF = "\x1B[?1006l\x1B[?1000l";
|
|
2573
|
-
var CLEAR_BELOW = "\r\x1B[J";
|
|
2574
|
-
var SIGNALS2 = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
2575
|
-
function up(lines) {
|
|
2576
|
-
return lines > 0 ? `\x1B[${lines}A` : "";
|
|
2577
|
-
}
|
|
2578
|
-
function openTerminal() {
|
|
2579
|
-
let mode;
|
|
2580
|
-
try {
|
|
2581
|
-
mode = new tty.ReadStream(openSync2("/dev/tty", "r"));
|
|
2582
|
-
} catch {
|
|
2583
|
-
return fail("no terminal to read keys from (/dev/tty)");
|
|
2584
|
-
}
|
|
2585
|
-
const keys = Bun.file("/dev/tty").stream().getReader();
|
|
2586
|
-
const out = process22.stderr;
|
|
2587
|
-
let resize;
|
|
2588
|
-
async function read(onChunk) {
|
|
2589
|
-
const decoder = new TextDecoder;
|
|
2590
|
-
try {
|
|
2591
|
-
for (let chunk = await keys.read();!chunk.done; chunk = await keys.read())
|
|
2592
|
-
onChunk(decoder.decode(chunk.value, { stream: true }));
|
|
2593
|
-
} catch {
|
|
2594
|
-
onChunk("\x03");
|
|
2595
|
-
}
|
|
2596
|
-
}
|
|
2597
|
-
return {
|
|
2598
|
-
get columns() {
|
|
2599
|
-
return out.columns || 80;
|
|
2600
|
-
},
|
|
2601
|
-
get rows() {
|
|
2602
|
-
return out.rows || 24;
|
|
2603
|
-
},
|
|
2604
|
-
theme: { accent: role("accent", out), label: role("label", out), value: role("value", out), id: role("id", out), match: (text) => paint(out).underline(role("accent", out)(text)) },
|
|
2605
|
-
write: (text) => void out.write(text),
|
|
2606
|
-
listen(onChunk, onResize) {
|
|
2607
|
-
resize = onResize;
|
|
2608
|
-
mode.setRawMode(true);
|
|
2609
|
-
out.on("resize", onResize);
|
|
2610
|
-
read(onChunk);
|
|
2611
|
-
},
|
|
2612
|
-
suspend() {
|
|
2613
|
-
mode.setRawMode(false);
|
|
2614
|
-
stopJob();
|
|
2615
|
-
mode.setRawMode(true);
|
|
2616
|
-
},
|
|
2617
|
-
close() {
|
|
2618
|
-
if (resize !== undefined)
|
|
2619
|
-
out.off("resize", resize);
|
|
2620
|
-
try {
|
|
2621
|
-
mode.setRawMode(false);
|
|
2622
|
-
} finally {
|
|
2623
|
-
mode.destroy();
|
|
2624
|
-
keys.cancel();
|
|
2625
|
-
}
|
|
2626
|
-
}
|
|
2627
|
-
};
|
|
2628
|
-
}
|
|
2629
|
-
async function select(rows, settings, terminal = openTerminal()) {
|
|
2630
|
-
const { theme } = terminal;
|
|
2631
|
-
let state = createState(rows, settings);
|
|
2632
|
-
let preview = [];
|
|
2633
|
-
let reserved = 0;
|
|
2634
|
-
let previewTimer;
|
|
2635
|
-
let previewing = new AbortController;
|
|
2636
|
-
let shownLine;
|
|
2637
|
-
let finish;
|
|
2638
|
-
let restored = false;
|
|
2639
|
-
let escape;
|
|
2640
|
-
function draw(clear = false) {
|
|
2641
|
-
if (restored)
|
|
2642
|
-
return;
|
|
2643
|
-
const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
|
|
2644
|
-
let frame = SYNC_START + HIDE_CURSOR;
|
|
2645
|
-
if (reserved !== layout.height || clear) {
|
|
2646
|
-
frame += CLEAR_BELOW + `
|
|
2647
|
-
`.repeat(layout.height - 1) + up(layout.height - 1);
|
|
2648
|
-
reserved = layout.height;
|
|
2649
|
-
}
|
|
2650
|
-
const caret = caretCell(state, layout);
|
|
2651
|
-
frame += `\r${overwrite(render(state, layout, theme, preview), terminal.columns)}${up(layout.height - 1)}\r\x1B[${caret.column}G${REVERSE}${caret.char}${REVERSE_END}\r${SYNC_END}`;
|
|
2652
|
-
terminal.write(frame);
|
|
2653
|
-
}
|
|
2654
|
-
function pageSize() {
|
|
2655
|
-
const headerLines = state.header === "" ? 0 : state.header.split(`
|
|
2656
|
-
`).length;
|
|
2657
|
-
return Math.max(1, layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition).listHeight - 2 - headerLines);
|
|
2658
|
-
}
|
|
2659
|
-
function refreshPreview() {
|
|
2660
|
-
const at = highlighted(state);
|
|
2661
|
-
if (settings.preview === undefined || at === shownLine)
|
|
2662
|
-
return;
|
|
2663
|
-
shownLine = at;
|
|
2664
|
-
clearTimeout(previewTimer);
|
|
2665
|
-
previewing.abort();
|
|
2666
|
-
previewing = new AbortController;
|
|
2667
|
-
if (at === undefined) {
|
|
2668
|
-
preview = [];
|
|
2669
|
-
return;
|
|
2670
|
-
}
|
|
2671
|
-
const { signal } = previewing;
|
|
2672
|
-
const template = settings.preview;
|
|
2673
|
-
const row = state.rows[at];
|
|
2674
|
-
async function show() {
|
|
2675
|
-
const shown = typeof template === "string" ? await runPreview(template, row.cells.join(" "), signal, row.hidden) : await previewOf(template, row.hidden, signal);
|
|
2676
|
-
if (!signal.aborted) {
|
|
2677
|
-
preview = shown;
|
|
2678
|
-
draw();
|
|
2679
|
-
}
|
|
2680
|
-
}
|
|
2681
|
-
previewTimer = setTimeout(() => void show(), PREVIEW_DELAY_MS);
|
|
2682
|
-
}
|
|
2683
|
-
function restore() {
|
|
2684
|
-
if (restored)
|
|
2685
|
-
return;
|
|
2686
|
-
restored = true;
|
|
2687
|
-
clearTimeout(previewTimer);
|
|
2688
|
-
clearTimeout(escape);
|
|
2689
|
-
previewing.abort();
|
|
2690
|
-
terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
|
|
2691
|
-
terminal.close();
|
|
2692
|
-
}
|
|
2693
|
-
function suspend() {
|
|
2694
|
-
if (terminal.suspend === undefined)
|
|
2695
|
-
return;
|
|
2696
|
-
terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
|
|
2697
|
-
terminal.suspend();
|
|
2698
|
-
terminal.write(`${PASTE_ON}${MOUSE_ON}`);
|
|
2699
|
-
draw(true);
|
|
2700
|
-
}
|
|
2701
|
-
const stop = () => {
|
|
2702
|
-
state = { ...state, done: "cancel" };
|
|
2703
|
-
finish?.();
|
|
2704
|
-
};
|
|
2705
|
-
const paste = { active: false };
|
|
2706
|
-
const { reload } = settings;
|
|
2707
|
-
const pending = [];
|
|
2708
|
-
let busy = false;
|
|
2709
|
-
let draining = false;
|
|
2710
|
-
async function reloadRows() {
|
|
2711
|
-
if (reload === undefined)
|
|
2712
|
-
return;
|
|
2713
|
-
busy = true;
|
|
2714
|
-
state = { ...state, status: "reloading" };
|
|
2715
|
-
draw();
|
|
2716
|
-
try {
|
|
2717
|
-
const next = await reload.run();
|
|
2718
|
-
state = { ...withRows(state, next.rows, next.header), status: "" };
|
|
2719
|
-
shownLine = undefined;
|
|
2720
|
-
} catch (error) {
|
|
2721
|
-
state = { ...state, status: `reload failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
2722
|
-
} finally {
|
|
2723
|
-
busy = false;
|
|
2724
|
-
}
|
|
2725
|
-
}
|
|
2726
|
-
async function drain() {
|
|
2727
|
-
if (draining)
|
|
2728
|
-
return;
|
|
2729
|
-
draining = true;
|
|
2730
|
-
try {
|
|
2731
|
-
for (let key = pending.shift();key !== undefined && state.done === undefined; key = pending.shift()) {
|
|
2732
|
-
if (key === OPEN || typeof key === "object" && "ctrl" in key && key.ctrl === reload?.key)
|
|
2733
|
-
await reloadRows();
|
|
2734
|
-
else if (key === "suspend")
|
|
2735
|
-
suspend();
|
|
2736
|
-
else
|
|
2737
|
-
state = press({ ...state, page: pageSize() }, key);
|
|
2738
|
-
}
|
|
2739
|
-
} finally {
|
|
2740
|
-
draining = false;
|
|
2741
|
-
}
|
|
2742
|
-
if (state.done !== undefined) {
|
|
2743
|
-
finish?.();
|
|
2744
|
-
return;
|
|
2745
|
-
}
|
|
2746
|
-
refreshPreview();
|
|
2747
|
-
draw();
|
|
2748
|
-
}
|
|
2749
|
-
function onChunk(chunk) {
|
|
2750
|
-
if (escape !== undefined) {
|
|
2751
|
-
clearTimeout(escape);
|
|
2752
|
-
escape = undefined;
|
|
2753
|
-
chunk = `\x1B${chunk}`;
|
|
2754
|
-
} else if (chunk === "\x1B") {
|
|
2755
|
-
escape = setTimeout(() => {
|
|
2756
|
-
escape = undefined;
|
|
2757
|
-
takeKeys("\x1B");
|
|
2758
|
-
}, ESCAPE_WAIT_MS);
|
|
2759
|
-
return;
|
|
2760
|
-
}
|
|
2761
|
-
takeKeys(chunk);
|
|
2762
|
-
}
|
|
2763
|
-
function takeKeys(chunk) {
|
|
2764
|
-
const keys = parseKeys(chunk, paste, [...settings.expect ?? [], ...reload?.key === undefined ? [] : [reload.key]]);
|
|
2765
|
-
if (busy && keys.includes("cancel")) {
|
|
2766
|
-
stop();
|
|
2767
|
-
return;
|
|
2768
|
-
}
|
|
2769
|
-
pending.push(...keys);
|
|
2770
|
-
drain();
|
|
2771
|
-
}
|
|
2772
|
-
const ended = new Promise((resolve) => {
|
|
2773
|
-
finish = resolve;
|
|
2774
|
-
});
|
|
2775
|
-
process22.once("exit", restore);
|
|
2776
|
-
for (const signal of SIGNALS2)
|
|
2777
|
-
process22.once(signal, stop);
|
|
2778
|
-
try {
|
|
2779
|
-
terminal.write(`${PASTE_ON}${MOUSE_ON}`);
|
|
2780
|
-
terminal.listen(onChunk, () => draw(true));
|
|
2781
|
-
refreshPreview();
|
|
2782
|
-
draw(true);
|
|
2783
|
-
if (reload?.onOpen === true) {
|
|
2784
|
-
pending.push(OPEN);
|
|
2785
|
-
drain();
|
|
2786
|
-
}
|
|
2787
|
-
await ended;
|
|
2788
|
-
} finally {
|
|
2789
|
-
for (const signal of SIGNALS2)
|
|
2790
|
-
process22.off(signal, stop);
|
|
2791
|
-
process22.off("exit", restore);
|
|
2792
|
-
restore();
|
|
2793
|
-
}
|
|
2794
|
-
return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
|
|
2795
|
-
}
|
|
2796
|
-
async function previewOf(preview, hidden, signal) {
|
|
2797
|
-
try {
|
|
2798
|
-
return previewLines(await preview(hidden, signal));
|
|
2799
|
-
} catch (error) {
|
|
2800
|
-
return [error instanceof Error ? error.message : String(error)];
|
|
2801
|
-
}
|
|
2802
|
-
}
|
|
2803
|
-
|
|
2804
|
-
// ../kit/src/picker.ts
|
|
2805
|
-
init_score();
|
|
2806
|
-
var REMEMBERED = 20;
|
|
2807
|
-
async function pick(rows, options) {
|
|
2808
|
-
const height = parseHeight(options.height ?? "100%");
|
|
2809
|
-
const keys = [...options.expect ?? [], ...options.reload?.key === undefined ? [] : [options.reload.key]];
|
|
2810
|
-
if (height === undefined)
|
|
2811
|
-
throw new Error(`pick: the height is lines or a percentage, not ${options.height}`);
|
|
2812
|
-
for (const key of keys) {
|
|
2813
|
-
if (!CTRL_KEY.test(key))
|
|
2814
|
-
throw new Error(`pick: ${key} is not a key it can report, one of ctrl-a to ctrl-z but ctrl-c, h, i, j and m`);
|
|
2815
|
-
}
|
|
2816
|
-
const found = await select(rows, { multi: false, prompt: options.prompt, query: "", height, preview: options.preview, previewPosition: "down", header: options.header, expect: options.expect, searched: options.searched, reload: options.reload });
|
|
2817
|
-
return found === undefined ? undefined : { key: found.key, hidden: found.rows[0]?.hidden ?? [], query: found.query };
|
|
2818
|
-
}
|
|
2819
|
-
function heightFor(count) {
|
|
2820
|
-
return String(Math.max(15, Math.ceil((count + 4) / 0.6)));
|
|
2821
|
-
}
|
|
2822
|
-
function historyFile(name) {
|
|
2823
|
-
return join8(cacheFolder(), name, "history.json");
|
|
2824
|
-
}
|
|
2825
|
-
function history(name) {
|
|
2826
|
-
try {
|
|
2827
|
-
const file = historyFile(name);
|
|
2828
|
-
return existsSync4(file) ? JSON.parse(readFileSync6(file, "utf-8")) : {};
|
|
2829
|
-
} catch {
|
|
2830
|
-
return {};
|
|
2831
|
-
}
|
|
2832
|
-
}
|
|
2833
|
-
function runs(name) {
|
|
2834
|
-
return history(name)[process23.cwd()] ?? [];
|
|
2835
|
-
}
|
|
2836
|
-
function record(name, run) {
|
|
2837
|
-
const all = history(name);
|
|
2838
|
-
const file = historyFile(name);
|
|
2839
|
-
all[process23.cwd()] = [run, ...(all[process23.cwd()] ?? []).filter((earlier) => earlier.id !== run.id)].slice(0, REMEMBERED);
|
|
2840
|
-
mkdirSync2(dirname4(file), { recursive: true });
|
|
2841
|
-
writeFileSync(file, JSON.stringify(all));
|
|
2842
|
-
}
|
|
2843
|
-
function byRecency(items, previous, idOf) {
|
|
2844
|
-
const rank = new Map(previous.map((run, index) => [run.id, index]));
|
|
2845
|
-
const recent = items.filter((item) => rank.has(idOf(item))).sort((a, b) => rank.get(idOf(a)) - rank.get(idOf(b)));
|
|
2846
|
-
return [...recent, ...items.filter((item) => !rank.has(idOf(item)))];
|
|
2847
|
-
}
|
|
2848
|
-
function word(arg) {
|
|
2849
|
-
if (typeof arg === "string")
|
|
2850
|
-
return `=${arg}`;
|
|
2851
|
-
return "given" in arg ? `+${arg.given}` : `?${arg.ask}`;
|
|
2852
|
-
}
|
|
2853
|
-
function emit(mode, typed, recorded, command) {
|
|
2854
|
-
const words = command.map(word);
|
|
2855
|
-
console.log([mode, typed, recorded, ...words].join(`
|
|
2856
|
-
`));
|
|
2857
|
-
}
|
|
2858
|
-
function list(rows) {
|
|
2859
|
-
console.log(JSON.stringify(rows));
|
|
2860
|
-
}
|
|
2861
|
-
|
|
2862
|
-
// src/j.ts
|
|
2863
|
-
init_prompt();
|
|
2864
|
-
|
|
2865
|
-
// src/job-picker.ts
|
|
2866
|
-
import process25 from "process";
|
|
2867
|
-
|
|
2868
|
-
// src/jobs.ts
|
|
2869
|
-
import { existsSync as existsSync5, readdirSync, readFileSync as readFileSync8 } from "fs";
|
|
2870
|
-
import { dirname as dirname6, join as join11, resolve as resolvePath } from "path";
|
|
2871
|
-
|
|
2872
|
-
// src/steps.ts
|
|
2873
|
-
import { readdir as readdir2 } from "fs/promises";
|
|
2874
|
-
import { join as join10 } from "path";
|
|
2875
|
-
var STEP_NAMES = ["check", "typecheck", "lint", "fmt", "test"];
|
|
2876
|
-
var STEP_SOURCES = { fmt: ["fmt:check", "format:check", "fmt-check", "format-check"] };
|
|
2877
|
-
var TARGET = /^@?([\w-]+)(?:[ \t][^:=\n]*)?:(?!=)/gm;
|
|
2878
|
-
var JUSTFILES = ["justfile", "Justfile", ".justfile"];
|
|
2879
|
-
var TASK_RUNNERS = new Set(["Justfile", "Makefile"]);
|
|
2880
|
-
var MAKEFILES = ["GNUmakefile", "makefile", "Makefile"];
|
|
2881
|
-
var CS_FIXER_CONFIGS = [".php-cs-fixer.php", ".php-cs-fixer.dist.php"];
|
|
2882
|
-
var JUST_TIMEOUT_MS = 1e4;
|
|
2883
|
-
var PHPSTAN_CONFIGS = ["phpstan.neon", "phpstan.neon.dist", "phpstan.dist.neon"];
|
|
2884
|
-
var PHPUNIT_CONFIGS = ["phpunit.xml", "phpunit.xml.dist", "phpunit.dist.xml"];
|
|
2885
|
-
async function readFirst(dir, files) {
|
|
2886
|
-
for (const file of files) {
|
|
2887
|
-
const handle = Bun.file(join10(dir, file));
|
|
2888
|
-
if (await handle.exists())
|
|
2889
|
-
return { file, text: await handle.text() };
|
|
2890
|
-
}
|
|
2891
|
-
return;
|
|
2892
|
-
}
|
|
2893
|
-
async function read(dir, ...files) {
|
|
2894
|
-
for (const file of files) {
|
|
2895
|
-
const handle = Bun.file(join10(dir, file));
|
|
2896
|
-
if (await handle.exists())
|
|
2897
|
-
return handle.text();
|
|
2898
|
-
}
|
|
2899
|
-
return;
|
|
2900
|
-
}
|
|
2901
|
-
function scripts(file, text) {
|
|
2902
|
-
try {
|
|
2903
|
-
const parsed = JSON.parse(text);
|
|
2904
|
-
return parsed.scripts ?? {};
|
|
2905
|
-
} catch {
|
|
2906
|
-
fail(`${file} is not valid JSON`);
|
|
2907
|
-
}
|
|
2908
|
-
}
|
|
2909
|
-
function targets(text) {
|
|
2910
|
-
return [...text.matchAll(TARGET)].map((match) => match[1] ?? "");
|
|
2911
|
-
}
|
|
2912
|
-
async function recipes(dir, file, text) {
|
|
2913
|
-
if (Bun.which("just") === null)
|
|
2914
|
-
return targets(text);
|
|
2915
|
-
try {
|
|
2916
|
-
const ran = await runCommand(["just", "--justfile", file, "--dump", "--dump-format", "json"], { cwd: dir, timeoutMs: JUST_TIMEOUT_MS });
|
|
2917
|
-
const dump = JSON.parse(ran.text);
|
|
2918
|
-
if (ran.code !== 0)
|
|
2919
|
-
return targets(text);
|
|
2920
|
-
return Object.entries(dump.recipes ?? {}).filter(([, recipe]) => recipe.private !== true && (recipe.parameters ?? []).every((parameter) => parameter.default !== null || parameter.kind === "star")).map(([name]) => name);
|
|
2921
|
-
} catch {
|
|
2922
|
-
return targets(text);
|
|
2923
|
-
}
|
|
2924
|
-
}
|
|
2925
|
-
function callsSelf(value, bin) {
|
|
2926
|
-
return typeof value === "string" && (value === bin || value.startsWith(`${bin} `) || value.startsWith(`${bin} `));
|
|
2927
|
-
}
|
|
2928
|
-
async function candidates(dir, bin) {
|
|
2929
|
-
const steps = [];
|
|
2930
|
-
const packageJson = await read(dir, "package.json");
|
|
2931
|
-
const composerJson = await read(dir, "composer.json");
|
|
2932
|
-
const justfile = await readFirst(dir, JUSTFILES);
|
|
2933
|
-
const makefile = await read(dir, ...MAKEFILES);
|
|
2934
|
-
if (packageJson !== undefined) {
|
|
2935
|
-
for (const [name, value] of Object.entries(scripts("package.json", packageJson))) {
|
|
2936
|
-
if (!callsSelf(value, bin))
|
|
2937
|
-
steps.push({ name, command: `bun run ${name}`, source: "package.json" });
|
|
2938
|
-
}
|
|
2939
|
-
}
|
|
2940
|
-
if (composerJson !== undefined) {
|
|
2941
|
-
for (const name of Object.keys(scripts("composer.json", composerJson)))
|
|
2942
|
-
steps.push({ name, command: `composer run ${name}`, source: "composer.json" });
|
|
2943
|
-
}
|
|
2944
|
-
if (justfile !== undefined) {
|
|
2945
|
-
for (const name of await recipes(dir, justfile.file, justfile.text))
|
|
2946
|
-
steps.push({ name, command: `just ${name}`, source: "Justfile" });
|
|
2947
|
-
}
|
|
2948
|
-
for (const name of targets(makefile ?? ""))
|
|
2949
|
-
steps.push({ name, command: `make ${name}`, source: "Makefile" });
|
|
2950
|
-
steps.push(...await phpSteps(dir));
|
|
2951
|
-
return steps;
|
|
2952
|
-
}
|
|
2953
|
-
async function firstFile(dir, names) {
|
|
2954
|
-
for (const name of names) {
|
|
2955
|
-
if (await Bun.file(join10(dir, name)).exists())
|
|
2956
|
-
return name;
|
|
2957
|
-
}
|
|
2958
|
-
return;
|
|
2959
|
-
}
|
|
2960
|
-
async function phpSteps(dir) {
|
|
2961
|
-
const steps = [];
|
|
2962
|
-
const phpstan = await firstFile(dir, PHPSTAN_CONFIGS);
|
|
2963
|
-
const csFixer = await firstFile(dir, CS_FIXER_CONFIGS);
|
|
2964
|
-
const phpunit = await firstFile(dir, PHPUNIT_CONFIGS);
|
|
2965
|
-
if (phpstan !== undefined)
|
|
2966
|
-
steps.push({ name: "typecheck", command: "vendor/bin/phpstan analyse --no-progress --memory-limit=1G", source: phpstan });
|
|
2967
|
-
if (csFixer !== undefined)
|
|
2968
|
-
steps.push({ name: "lint", command: "vendor/bin/php-cs-fixer fix --dry-run -v", source: csFixer });
|
|
2969
|
-
if (phpunit !== undefined)
|
|
2970
|
-
steps.push({ name: "test", command: "vendor/bin/phpunit", source: phpunit });
|
|
2971
|
-
return steps;
|
|
2972
|
-
}
|
|
2973
|
-
async function discoverProjects(dir) {
|
|
2974
|
-
const own = await discover(dir);
|
|
2975
|
-
if (own.length > 0)
|
|
2976
|
-
return [{ dir, steps: own }];
|
|
2977
|
-
const projects = [];
|
|
2978
|
-
const entries = await readdir2(dir, { withFileTypes: true });
|
|
2979
|
-
const ignored = ignoredFolders(["var", "tmp"]);
|
|
2980
|
-
for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
|
|
2981
|
-
if (!entry.isDirectory() || entry.name.startsWith(".") || ignored.has(entry.name))
|
|
2982
|
-
continue;
|
|
2983
|
-
const steps = await discover(join10(dir, entry.name));
|
|
2984
|
-
if (steps.length > 0)
|
|
2985
|
-
projects.push({ name: entry.name, dir: join10(dir, entry.name), steps });
|
|
2986
|
-
}
|
|
2987
|
-
return projects;
|
|
2988
|
-
}
|
|
2989
|
-
async function discover(dir) {
|
|
2990
|
-
const found = await candidates(dir, "check");
|
|
2991
|
-
const runnerCheck = found.find((candidate) => candidate.name === "check" && TASK_RUNNERS.has(candidate.source));
|
|
2992
|
-
return STEP_NAMES.flatMap((name) => {
|
|
2993
|
-
const step = name === "check" && runnerCheck !== undefined ? runnerCheck : (STEP_SOURCES[name] ?? [name]).map((each) => found.find((candidate) => candidate.name === each)).find((each) => each !== undefined);
|
|
2994
|
-
return step === undefined ? [] : [{ ...step, name }];
|
|
2995
|
-
});
|
|
2996
|
-
}
|
|
2997
|
-
|
|
2998
|
-
// src/jobs.ts
|
|
2999
|
-
var JUSTFILE = /^\.?justfile$/i;
|
|
3000
|
-
var TASKFILES = ["Taskfile.yml", "taskfile.yml", "Taskfile.yaml", "taskfile.yaml", "Taskfile.dist.yml", "taskfile.dist.yml", "Taskfile.dist.yaml", "taskfile.dist.yaml"];
|
|
3001
|
-
var MISE_FILES = ["mise.toml", ".mise.toml", "mise.local.toml", ".mise.local.toml", "mise", ".mise", "mise-tasks", ".mise-tasks", ".config/mise.toml", ".config/mise"];
|
|
3002
|
-
var LOCKFILES = [
|
|
3003
|
-
["bun.lock", "bun"],
|
|
3004
|
-
["bun.lockb", "bun"],
|
|
3005
|
-
["pnpm-lock.yaml", "pnpm"],
|
|
3006
|
-
["yarn.lock", "yarn"],
|
|
3007
|
-
["package-lock.json", "npm"]
|
|
3008
|
-
];
|
|
3009
|
-
var QUALIFIED = /^([a-z]+):(?!:)(.+)$/;
|
|
3010
|
-
var BLANKS = /\s+/;
|
|
3011
|
-
var TRAILING_SLASHES = /\/+$/;
|
|
3012
|
-
var VERSION_SUFFIX = /@.*/;
|
|
3013
|
-
var LEADING_HASHES = /^#*/;
|
|
3014
|
-
var installed = new Map;
|
|
3015
|
-
function has(tool) {
|
|
3016
|
-
if (!installed.has(tool))
|
|
3017
|
-
installed.set(tool, Bun.which(tool) !== null);
|
|
3018
|
-
return installed.get(tool);
|
|
3019
|
-
}
|
|
3020
|
-
function list2(dir) {
|
|
3021
|
-
try {
|
|
3022
|
-
return readdirSync(dir);
|
|
3023
|
-
} catch {
|
|
3024
|
-
return [];
|
|
3025
|
-
}
|
|
3026
|
-
}
|
|
3027
|
-
function locate(dir, here, names) {
|
|
3028
|
-
for (let current = dir;; current = join11(current, "..")) {
|
|
3029
|
-
const found = names.find((name) => existsSync5(join11(current, name)));
|
|
3030
|
-
if (found !== undefined)
|
|
3031
|
-
return join11(current, found);
|
|
3032
|
-
const absolute = resolvePath(current);
|
|
3033
|
-
if (!here || existsSync5(join11(current, ".git")) || dirname6(absolute) === absolute)
|
|
3034
|
-
return;
|
|
3035
|
-
}
|
|
3036
|
-
}
|
|
3037
|
-
function children(dir = ".") {
|
|
3038
|
-
const ignored = ignoredFolders();
|
|
3039
|
-
return readdirSync(dir, { withFileTypes: true }).filter((child) => child.isDirectory() && !child.name.startsWith(".") && !ignored.has(child.name)).map((child) => child.name).toSorted();
|
|
3040
|
-
}
|
|
3041
|
-
function build(base, items) {
|
|
3042
|
-
return items.map((item) => ({ ...base, doc: null, parameters: [], ...item }));
|
|
3043
|
-
}
|
|
3044
|
-
function text2(value) {
|
|
3045
|
-
if (typeof value === "string")
|
|
3046
|
-
return value;
|
|
3047
|
-
if (Array.isArray(value) && value.every((line) => typeof line === "string"))
|
|
3048
|
-
return value.join(`
|
|
3049
|
-
`);
|
|
3050
|
-
return Bun.YAML.stringify(value, null, 2) ?? "";
|
|
3051
|
-
}
|
|
3052
|
-
function field(value, key) {
|
|
3053
|
-
const found = value !== null && typeof value === "object" ? value[key] : undefined;
|
|
3054
|
-
return typeof found === "string" ? found : null;
|
|
3055
|
-
}
|
|
3056
|
-
function recipes2(tree) {
|
|
3057
|
-
return [...Object.values(tree.recipes).filter((recipe) => !recipe.private), ...Object.values(tree.modules).flatMap((module) => recipes2(module))];
|
|
3058
|
-
}
|
|
3059
|
-
function justFlags(dir, here) {
|
|
3060
|
-
if (here)
|
|
3061
|
-
return [];
|
|
3062
|
-
const file = list2(dir).find((name) => JUSTFILE.test(name));
|
|
3063
|
-
return file === undefined ? undefined : ["--justfile", join11(dir, file)];
|
|
3064
|
-
}
|
|
3065
|
-
function just(dir, here) {
|
|
3066
|
-
const flags = justFlags(dir, here);
|
|
3067
|
-
if (flags === undefined || !has("just"))
|
|
3068
|
-
return [];
|
|
3069
|
-
const proc = Bun.spawnSync(["just", ...flags, "--dump", "--dump-format", "json"], { stderr: "pipe" });
|
|
3070
|
-
if (!proc.success)
|
|
3071
|
-
return [];
|
|
3072
|
-
const items = recipes2(JSON.parse(proc.stdout.toString())).map((recipe) => ({ name: recipe.namepath, doc: recipe.doc, parameters: recipe.parameters }));
|
|
3073
|
-
return build({ kind: "just", tag: "just", runner: ["just"], separated: false, dir }, items);
|
|
3074
|
-
}
|
|
3075
|
-
function targets2(source) {
|
|
3076
|
-
const found = new Map;
|
|
3077
|
-
let pending = null;
|
|
3078
|
-
for (const line of source.split(`
|
|
3079
|
-
`)) {
|
|
3080
|
-
if (line.startsWith("\t"))
|
|
3081
|
-
continue;
|
|
3082
|
-
const [rule = "", ...rest] = line.split("#");
|
|
3083
|
-
const comment = rest.join("#").replace(LEADING_HASHES, "").trim() || null;
|
|
3084
|
-
if (rule.trim() === "") {
|
|
3085
|
-
pending = line.startsWith("##") ? comment : null;
|
|
3086
|
-
continue;
|
|
3087
|
-
}
|
|
3088
|
-
const colon = rule.indexOf(":");
|
|
3089
|
-
const assignment = rule[colon + 1] === "=" || rule.slice(colon + 1).startsWith(":=") || rule.slice(0, colon).includes("=");
|
|
3090
|
-
if (colon === -1 || assignment) {
|
|
3091
|
-
pending = null;
|
|
3092
|
-
continue;
|
|
3093
|
-
}
|
|
3094
|
-
const doc = comment ?? pending;
|
|
3095
|
-
for (const name of rule.slice(0, colon).trim().split(BLANKS)) {
|
|
3096
|
-
if (name.startsWith(".") || name.includes("%") || name.includes("$"))
|
|
3097
|
-
continue;
|
|
3098
|
-
if (!found.has(name))
|
|
3099
|
-
found.set(name, doc);
|
|
3100
|
-
}
|
|
3101
|
-
pending = null;
|
|
3102
|
-
}
|
|
3103
|
-
return [...found].map(([name, doc]) => ({ name, doc }));
|
|
3104
|
-
}
|
|
3105
|
-
function show(source, target) {
|
|
3106
|
-
const lines = source.split(`
|
|
3107
|
-
`);
|
|
3108
|
-
const start = lines.findIndex((line) => {
|
|
3109
|
-
const hash = line.indexOf("#");
|
|
3110
|
-
const rule = hash === -1 ? line : line.slice(0, hash);
|
|
3111
|
-
const colon = rule.indexOf(":");
|
|
3112
|
-
return colon !== -1 && rule[colon + 1] !== "=" && !rule.slice(0, colon).includes("=") && rule.slice(0, colon).trim().split(BLANKS).includes(target);
|
|
3113
|
-
});
|
|
3114
|
-
if (start === -1)
|
|
3115
|
-
return target;
|
|
3116
|
-
let end = start + 1;
|
|
3117
|
-
while (end < lines.length && (lines[end].startsWith("\t") || lines[end].trim() === ""))
|
|
3118
|
-
end++;
|
|
3119
|
-
return lines.slice(start, end).join(`
|
|
3120
|
-
`).trimEnd();
|
|
3121
|
-
}
|
|
3122
|
-
function make(dir) {
|
|
3123
|
-
const file = MAKEFILES.find((name) => existsSync5(join11(dir, name)));
|
|
3124
|
-
if (file === undefined)
|
|
3125
|
-
return [];
|
|
3126
|
-
const source = readFileSync8(join11(dir, file), "utf-8");
|
|
3127
|
-
return build({ kind: "make", tag: "make", runner: ["make"], separated: false, dir }, targets2(source).map((target) => ({ ...target, body: show(source, target.name) })));
|
|
3128
|
-
}
|
|
3129
|
-
function manager(dir, manifest) {
|
|
3130
|
-
const declared = typeof manifest.packageManager === "string" ? manifest.packageManager.replace(VERSION_SUFFIX, "") : undefined;
|
|
3131
|
-
const known = LOCKFILES.find(([, name]) => name === declared);
|
|
3132
|
-
if (known !== undefined)
|
|
3133
|
-
return known[1];
|
|
3134
|
-
for (let current = resolvePath(dir);; current = dirname6(current)) {
|
|
3135
|
-
const found = LOCKFILES.find(([file]) => existsSync5(join11(current, file)));
|
|
3136
|
-
if (found !== undefined)
|
|
3137
|
-
return found[1];
|
|
3138
|
-
if (dirname6(current) === current)
|
|
3139
|
-
return "bun";
|
|
3140
|
-
}
|
|
3141
|
-
}
|
|
3142
|
-
function table2(value) {
|
|
3143
|
-
return value !== null && typeof value === "object" ? value : {};
|
|
3144
|
-
}
|
|
3145
|
-
function packageScripts(dir, here) {
|
|
3146
|
-
const file = locate(dir, here, ["package.json"]);
|
|
3147
|
-
if (file === undefined)
|
|
3148
|
-
return [];
|
|
3149
|
-
const manifest = JSON.parse(readFileSync8(file, "utf-8"));
|
|
3150
|
-
const tool = manager(dirname6(file), manifest);
|
|
3151
|
-
const items = Object.entries(table2(manifest.scripts)).map(([name, command]) => ({ name, body: text2(command) }));
|
|
3152
|
-
return build({ kind: "package", tag: tool, runner: [tool, "run"], separated: tool === "npm", dir: dirname6(file) }, items);
|
|
3153
|
-
}
|
|
3154
|
-
function composer(dir, here) {
|
|
3155
|
-
const file = locate(dir, here, ["composer.json"]);
|
|
3156
|
-
if (file === undefined)
|
|
3157
|
-
return [];
|
|
3158
|
-
const manifest = JSON.parse(readFileSync8(file, "utf-8"));
|
|
3159
|
-
const descriptions = table2(manifest["scripts-descriptions"]);
|
|
3160
|
-
const items = Object.entries(table2(manifest.scripts)).map(([name, command]) => ({ name, doc: field(descriptions, name), body: text2(command) }));
|
|
3161
|
-
return build({ kind: "composer", tag: "composer", runner: ["composer", "run"], separated: true, dir: dirname6(file) }, items);
|
|
3162
|
-
}
|
|
3163
|
-
function deno(dir, here) {
|
|
3164
|
-
const file = locate(dir, here, ["deno.json", "deno.jsonc"]);
|
|
3165
|
-
if (file === undefined)
|
|
3166
|
-
return [];
|
|
3167
|
-
const manifest = Bun.JSONC.parse(readFileSync8(file, "utf-8"));
|
|
3168
|
-
const items = Object.entries(table2(manifest.tasks)).map(([name, task]) => ({ name, doc: field(task, "description"), body: field(task, "command") ?? text2(task) }));
|
|
3169
|
-
return build({ kind: "deno", tag: "deno", runner: ["deno", "task"], separated: false, dir: dirname6(file) }, items);
|
|
3170
|
-
}
|
|
3171
|
-
function taskfile(dir, here) {
|
|
3172
|
-
const file = locate(dir, here, TASKFILES);
|
|
3173
|
-
if (file === undefined)
|
|
3174
|
-
return [];
|
|
3175
|
-
const tasks = table2(Bun.YAML.parse(readFileSync8(file, "utf-8"))?.tasks);
|
|
3176
|
-
const items = Object.entries(tasks).filter(([, task]) => !(task !== null && typeof task === "object" && task.internal === true)).map(([name, task]) => ({ name, doc: field(task, "desc") ?? field(task, "summary"), body: text2(task) }));
|
|
3177
|
-
return build({ kind: "task", tag: "task", runner: ["task"], separated: true, dir: dirname6(file) }, items);
|
|
3178
|
-
}
|
|
3179
|
-
function mise(dir, here) {
|
|
3180
|
-
if (!has("mise") || !here && !MISE_FILES.some((name) => existsSync5(join11(dir, name))))
|
|
3181
|
-
return [];
|
|
3182
|
-
const proc = Bun.spawnSync(["mise", "tasks", "ls", "--json"], { cwd: dir, stderr: "pipe" });
|
|
3183
|
-
if (!proc.success)
|
|
3184
|
-
return [];
|
|
3185
|
-
const root = `${resolvePath(dir)}/`;
|
|
3186
|
-
const items = JSON.parse(proc.stdout.toString()).filter((task) => !task.hide && (here || !task.global && task.source.startsWith(root))).map((task) => ({ name: task.name, doc: task.description || null, body: task.file ?? task.run.join(`
|
|
3187
|
-
`) }));
|
|
3188
|
-
return build({ kind: "mise", tag: "mise", runner: ["mise", "run"], separated: false, dir }, items);
|
|
3189
|
-
}
|
|
3190
|
-
function pyproject(dir, here) {
|
|
3191
|
-
const file = locate(dir, here, ["pyproject.toml"]);
|
|
3192
|
-
if (file === undefined)
|
|
3193
|
-
return [];
|
|
3194
|
-
const manifest = Bun.TOML.parse(readFileSync8(file, "utf-8"));
|
|
3195
|
-
const tool = table2(manifest.tool);
|
|
3196
|
-
const project = table2(manifest.project);
|
|
3197
|
-
const uv = locate(dirname6(file), true, ["uv.lock"]) !== undefined;
|
|
3198
|
-
const poe = Object.entries(table2(table2(tool.poe).tasks)).filter(([name]) => !name.startsWith("_")).map(([name, task]) => ({ name, doc: field(task, "help"), body: field(task, "cmd") ?? field(task, "shell") ?? text2(task) }));
|
|
3199
|
-
const entryPoints = Object.entries(table2(project.scripts)).map(([name, target]) => ({ name, body: text2(target) }));
|
|
3200
|
-
return [
|
|
3201
|
-
...build({ kind: "poe", tag: "poe", runner: uv ? ["uv", "run", "poe"] : ["poe"], separated: false, dir: dirname6(file) }, poe),
|
|
3202
|
-
...build({ kind: "uv", tag: "uv", runner: ["uv", "run"], separated: false, dir: dirname6(file) }, entryPoints)
|
|
3203
|
-
];
|
|
3204
|
-
}
|
|
3205
|
-
var READERS = [just, make, packageScripts, composer, deno, taskfile, mise, pyproject];
|
|
3206
|
-
var READER_OF = {
|
|
3207
|
-
just,
|
|
3208
|
-
make,
|
|
3209
|
-
package: packageScripts,
|
|
3210
|
-
composer,
|
|
3211
|
-
deno,
|
|
3212
|
-
task: taskfile,
|
|
3213
|
-
mise,
|
|
3214
|
-
poe: pyproject,
|
|
3215
|
-
uv: pyproject
|
|
3216
|
-
};
|
|
3217
|
-
var MANIFEST_OF = new Map([[just, "justfile"], [make, "Makefile"], [packageScripts, "package.json"], [composer, "composer.json"], [deno, "deno.json"], [taskfile, "Taskfile.yml"], [mise, "mise.toml"], [pyproject, "pyproject.toml"]]);
|
|
3218
|
-
function readOr(read, fallback) {
|
|
3219
|
-
try {
|
|
3220
|
-
return read();
|
|
3221
|
-
} catch {
|
|
3222
|
-
return fallback;
|
|
3223
|
-
}
|
|
3224
|
-
}
|
|
3225
|
-
function workspaces() {
|
|
3226
|
-
const manifest = readOr(() => JSON.parse(readFileSync8("package.json", "utf-8")), {});
|
|
3227
|
-
const declared = Array.isArray(manifest.workspaces) ? manifest.workspaces : table2(manifest.workspaces).packages;
|
|
3228
|
-
const pnpm = readOr(() => table2(Bun.YAML.parse(readFileSync8("pnpm-workspace.yaml", "utf-8"))).packages, undefined);
|
|
3229
|
-
const patterns = [declared, pnpm].flatMap((value) => Array.isArray(value) ? value.filter((pattern) => typeof pattern === "string") : []);
|
|
3230
|
-
const excluded = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => new Bun.Glob(pattern.slice(1)));
|
|
3231
|
-
return patterns.filter((pattern) => !pattern.startsWith("!")).flatMap((pattern) => [...new Bun.Glob(`${pattern.replace(TRAILING_SLASHES, "")}/package.json`).scanSync({ cwd: "." })].map((file) => dirname6(file))).filter((dir) => !dir.split("/").includes("node_modules") && !excluded.some((glob) => glob.match(dir)));
|
|
3232
|
-
}
|
|
3233
|
-
function folders2() {
|
|
3234
|
-
return [...new Set([...children(), ...workspaces()])].filter((dir) => dir !== ".");
|
|
3235
|
-
}
|
|
3236
|
-
function guarded(reader, dir, here, isWarned = false) {
|
|
3237
|
-
try {
|
|
3238
|
-
return reader(dir, here);
|
|
3239
|
-
} catch (error) {
|
|
3240
|
-
if (isWarned)
|
|
3241
|
-
warn(`j: skipped ${join11(dir, MANIFEST_OF.get(reader) ?? "a manifest")}, it does not parse (${error instanceof Error ? error.message : String(error)})`);
|
|
3242
|
-
return [];
|
|
3243
|
-
}
|
|
3244
|
-
}
|
|
3245
|
-
function everything() {
|
|
3246
|
-
const here = READERS.flatMap((reader) => guarded(reader, ".", true, true));
|
|
3247
|
-
const below = folders2().flatMap((dir) => READERS.flatMap((reader) => guarded(reader, dir, false, true)));
|
|
3248
|
-
const seen = new Set;
|
|
3249
|
-
return [...here, ...below].filter((entry) => {
|
|
3250
|
-
const id = `${entry.kind} ${entry.dir} ${entry.name}`;
|
|
3251
|
-
const fresh = !seen.has(id);
|
|
3252
|
-
seen.add(id);
|
|
3253
|
-
return fresh;
|
|
3254
|
-
});
|
|
3255
|
-
}
|
|
3256
|
-
function readKind(kind, dir) {
|
|
3257
|
-
return guarded(READER_OF[kind], dir, dir === ".").filter((entry) => entry.kind === kind);
|
|
3258
|
-
}
|
|
3259
|
-
function key(entry) {
|
|
3260
|
-
return entry.dir === "." ? entry.name : `${entry.dir}/${entry.name}`;
|
|
3261
|
-
}
|
|
3262
|
-
function id(entry) {
|
|
3263
|
-
return `${entry.tag}:${key(entry)}`;
|
|
3264
|
-
}
|
|
3265
|
-
function resolve4(entries, named) {
|
|
3266
|
-
const qualified = QUALIFIED.exec(named);
|
|
3267
|
-
const tagged = qualified && entries.some((entry) => entry.tag === qualified[1]) ? qualified : undefined;
|
|
3268
|
-
const pool = tagged ? entries.filter((entry) => entry.tag === tagged[1]) : entries;
|
|
3269
|
-
const rest = tagged ? tagged[2] : named;
|
|
3270
|
-
const exact = pool.filter((entry) => key(entry) === rest);
|
|
3271
|
-
return exact.length > 0 ? exact : pool.filter((entry) => entry.name === rest);
|
|
3272
|
-
}
|
|
3273
|
-
function shortest(entries, entry) {
|
|
3274
|
-
const found = resolve4(entries, key(entry));
|
|
3275
|
-
return found.length === 1 && found[0] === entry ? key(entry) : id(entry);
|
|
3276
|
-
}
|
|
3277
|
-
function signature(entry) {
|
|
3278
|
-
return entry.parameters.map((parameter) => parameter.default === null && parameter.kind === "singular" ? `<${parameter.name}>` : `[${parameter.name}]`).join(" ");
|
|
3279
|
-
}
|
|
3280
|
-
|
|
3281
|
-
// src/job-picker.ts
|
|
3282
|
-
var TINTS = { just: "yellow", make: "blue", package: "magenta", composer: "cyan", deno: "green", task: "cyan", mise: "red", poe: "green", uv: "green" };
|
|
3283
|
-
function labelled(entries) {
|
|
3284
|
-
return new Set(entries.map((entry) => entry.tag)).size > 1;
|
|
3285
|
-
}
|
|
3286
|
-
function row(entry, labels, signed) {
|
|
3287
|
-
const colors = paint(process25.stderr);
|
|
3288
|
-
const keyed = entry.dir === "." ? entry.name : `${colors.dim(`${entry.dir}/`)}${entry.name}`;
|
|
3289
|
-
return {
|
|
3290
|
-
hidden: [entry.kind, entry.dir, entry.name, id(entry)],
|
|
3291
|
-
cells: [...labels ? [colors[TINTS[entry.kind]](entry.tag)] : [], keyed, ...signed ? [colors.cyan(signature(entry))] : [], colors.dim(entry.doc ?? "")]
|
|
3292
|
-
};
|
|
3293
|
-
}
|
|
3294
|
-
async function pickJob(entries, narrowed = false) {
|
|
3295
|
-
const labels = labelled(entries);
|
|
3296
|
-
const signed = entries.some((entry) => signature(entry) !== "");
|
|
3297
|
-
const picked = await pick(entries.map((entry) => row(entry, labels, signed)), {
|
|
3298
|
-
prompt: `${[...new Set(entries.map((entry) => entry.tag))].join("/")}> `,
|
|
3299
|
-
searched: labels ? 2 : 1,
|
|
3300
|
-
...narrowed ? { height: heightFor(entries.length) } : {},
|
|
3301
|
-
preview: `${process25.execPath} ${process25.argv[1]} --show {1} {2} {3}`
|
|
3302
|
-
});
|
|
3303
|
-
return entries.find((candidate) => id(candidate) === picked?.hidden[3]);
|
|
3304
|
-
}
|
|
3305
|
-
|
|
3306
|
-
// src/j.ts
|
|
3307
|
-
var usage2 = `j [name] [args...]
|
|
3308
|
-
j -
|
|
3309
|
-
|
|
3310
|
-
Without a name, picks a recipe, script or task of this folder, its parents and its child folders and runs it, the ones run last first; without a terminal it lists them instead.
|
|
3311
|
-
\`j -\` runs the last one again with the same arguments, \`j <name> [args...]\` runs without the picker, the words after the name filling the parameters in order.
|
|
3312
|
-
The sources are a Justfile, a Makefile, package.json and composer.json scripts, deno tasks, a Taskfile, mise tasks and a pyproject; a name several share offers them, unless qualified by its runner (\`just:check\`).`;
|
|
3313
|
-
var EXITS = [["its own", "the code of the command it ran"], [1, "there is nothing to run here or nothing by that name"]];
|
|
3314
|
-
var options = {
|
|
3315
|
-
json: jsonOption("[{ id, key, runner, dir, name, doc, parameters }]")
|
|
3316
|
-
};
|
|
3317
|
-
function preview(kind, dir, name) {
|
|
3318
|
-
const entry = readKind(kind, dir).find((candidate) => candidate.name === name);
|
|
3319
|
-
if (entry === undefined)
|
|
3320
|
-
return;
|
|
3321
|
-
const colors = paint(process26.stdout);
|
|
3322
|
-
console.log(`${colors.dim(`$ ${dir === "." ? "" : `env -C ${dir} `}`)}${colors.bold([...entry.runner, entry.name].join(" "))}
|
|
3323
|
-
`);
|
|
3324
|
-
if (entry.body !== undefined)
|
|
3325
|
-
console.log(entry.body);
|
|
3326
|
-
else
|
|
3327
|
-
Bun.spawnSync(["just", ...justFlags(dir, dir === ".") ?? [], "--show", name], { stdout: "inherit", stderr: "inherit" });
|
|
3328
|
-
}
|
|
3329
|
-
function names(found) {
|
|
3330
|
-
const described = (entry) => entry.doc === null || entry.doc === "" ? entry.tag : entry.doc;
|
|
3331
|
-
return [...new Set(found.map(key))].flatMap((name) => {
|
|
3332
|
-
const same = resolve4(found, name);
|
|
3333
|
-
return same.length === 1 ? [[name, described(same[0])]] : [[name, same.map((entry) => entry.tag).join(", ")], ...same.map((entry) => [id(entry), described(entry)])];
|
|
3334
|
-
});
|
|
3335
|
-
}
|
|
3336
|
-
function completions2() {
|
|
3337
|
-
try {
|
|
3338
|
-
return [...names(everything()), ["-", "the last one again, with its arguments"]];
|
|
3339
|
-
} catch {
|
|
3340
|
-
return [];
|
|
3341
|
-
}
|
|
3342
|
-
}
|
|
3343
|
-
function listed3(found) {
|
|
3344
|
-
const labels = labelled(found);
|
|
3345
|
-
return byRecency(found, runs("j"), id).map((entry) => ({
|
|
3346
|
-
label: [labels ? entry.tag : "", key(entry), signature(entry)].filter(Boolean).join(" "),
|
|
3347
|
-
hint: entry.doc ?? "",
|
|
3348
|
-
typed: shortest(found, entry),
|
|
3349
|
-
preview: ["--show", entry.kind, entry.dir, entry.name],
|
|
3350
|
-
editsTyped: true
|
|
3351
|
-
}));
|
|
3352
|
-
}
|
|
3353
|
-
function listing(found) {
|
|
3354
|
-
const colors = paint(process26.stdout);
|
|
3355
|
-
const labels = labelled(found);
|
|
3356
|
-
return table(found.map((entry) => [...labels ? [entry.tag] : [], key(entry), signature(entry), colors.dim(entry.doc ?? "")]));
|
|
3357
|
-
}
|
|
3358
|
-
function missing(entry, given) {
|
|
3359
|
-
return entry.parameters.slice(given.length).filter((parameter) => parameter.default === null && parameter.kind === "singular").map((parameter) => parameter.name);
|
|
3360
|
-
}
|
|
3361
|
-
function commandOf(entry, args) {
|
|
3362
|
-
const separated = entry.separated && args.length > 0 ? ["--"] : [];
|
|
3363
|
-
return [...entry.dir === "." ? [] : ["env", "-C", entry.dir], ...entry.runner, entry.name, ...separated, ...args];
|
|
3364
|
-
}
|
|
3365
|
-
async function j2(argv) {
|
|
3366
|
-
const [flag = ""] = argv;
|
|
3367
|
-
if (flag === "--show") {
|
|
3368
|
-
const [kind = "just", dir = ".", name = ""] = argv.slice(1);
|
|
3369
|
-
preview(kind, dir, name);
|
|
3370
|
-
return 0;
|
|
3371
|
-
}
|
|
3372
|
-
if (flag === "--record") {
|
|
3373
|
-
record("j", { id: argv[1] ?? "", args: argv.slice(2) });
|
|
3374
|
-
return 0;
|
|
3375
|
-
}
|
|
3376
|
-
if (flag === "--list" || flag === "--names") {
|
|
3377
|
-
const found = everything();
|
|
3378
|
-
if (found.length === 0)
|
|
3379
|
-
fail("nothing to run here: no recipe, target, script or task", 1);
|
|
3380
|
-
if (flag === "--list")
|
|
3381
|
-
list(listed3(found));
|
|
3382
|
-
else
|
|
3383
|
-
console.log(names(found).map(([name, description]) => `${name} ${description}`).join(`
|
|
3384
|
-
`));
|
|
3385
|
-
return 0;
|
|
3386
|
-
}
|
|
3387
|
-
const emitting = flag === "--emit";
|
|
3388
|
-
const args = emitting ? argv.slice(1) : argv;
|
|
3389
|
-
const last = args[0] === "-";
|
|
3390
|
-
const parsed = last ? { values: {}, positionals: ["-"], rest: args.slice(1) } : parse(args, usage2, options, {
|
|
3391
|
-
exits: EXITS,
|
|
3392
|
-
positionals: ["[name]"],
|
|
3393
|
-
candidates: { "[name]": completions2 },
|
|
3394
|
-
trailing: true,
|
|
3395
|
-
replaces: "reading the Justfile, Makefile, package.json scripts or composer scripts to find what to run, then retyping it",
|
|
3396
|
-
examples: ["j", ["j test", "run the test recipe, script or task"], ["j api/test --watch", "a child folder's, with an argument"], ["j just:check", "the one of a runner, when several share the name"], ["j -", "the last one again"]]
|
|
3397
|
-
});
|
|
3398
|
-
const [named] = parsed.positionals;
|
|
3399
|
-
const given = parsed.rest ?? [];
|
|
3400
|
-
const found = everything();
|
|
3401
|
-
if (found.length === 0)
|
|
3402
|
-
fail("nothing to run here: no recipe, target, script or task", 1);
|
|
3403
|
-
const previous = runs("j");
|
|
3404
|
-
const interactive = isInteractive() && parsed.values.json !== true;
|
|
3405
|
-
let entry;
|
|
3406
|
-
let words = given;
|
|
3407
|
-
if (named === "-") {
|
|
3408
|
-
const earlier = previous[0];
|
|
3409
|
-
entry = earlier && found.find((candidate) => id(candidate) === earlier.id);
|
|
3410
|
-
if (entry === undefined)
|
|
3411
|
-
fail(earlier ? `${earlier.id} is gone` : "nothing run here yet", 1);
|
|
3412
|
-
words = [...earlier.args, ...given];
|
|
3413
|
-
} else if (named === undefined) {
|
|
3414
|
-
if (!interactive) {
|
|
3415
|
-
if (emitting)
|
|
3416
|
-
fail("the picker needs a terminal", 1);
|
|
3417
|
-
if (parsed.values.json === true)
|
|
3418
|
-
printJson(found.map((each) => ({ id: id(each), key: key(each), runner: each.tag, dir: each.dir, name: each.name, doc: each.doc, parameters: each.parameters })));
|
|
3419
|
-
else
|
|
3420
|
-
console.log(listing(found));
|
|
3421
|
-
return 0;
|
|
3422
|
-
}
|
|
3423
|
-
entry = await pickJob(byRecency(found, previous, id));
|
|
3424
|
-
} else {
|
|
3425
|
-
const matching = resolve4(found, named);
|
|
3426
|
-
if (matching.length === 0) {
|
|
3427
|
-
const nearest = closest(named, found.map(key));
|
|
3428
|
-
fail(`nothing named ${named}${nearest === undefined ? "" : `, did you mean ${nearest}?`}`, 1);
|
|
3429
|
-
}
|
|
3430
|
-
if (matching.length > 1 && !interactive)
|
|
3431
|
-
fail(`${named} is several: ${matching.map(id).join(", ")}`, 1, "qualify it with its runner");
|
|
3432
|
-
entry = matching.length === 1 ? matching[0] : await pickJob(matching, true);
|
|
3433
|
-
}
|
|
3434
|
-
if (entry === undefined)
|
|
3435
|
-
return 1;
|
|
3436
|
-
const typed = shortest(found, entry);
|
|
3437
|
-
const asks = missing(entry, words);
|
|
3438
|
-
if (emitting) {
|
|
3439
|
-
emit("run", typed, id(entry), commandOf(entry, [...words.map((word) => ({ given: word })), ...asks.map((ask) => ({ ask }))]));
|
|
3440
|
-
return 0;
|
|
3441
|
-
}
|
|
3442
|
-
const answers = [];
|
|
3443
|
-
for (const ask of asks) {
|
|
3444
|
-
const answer = await input2(ask, { history: `j ${id(entry)} ${ask}` });
|
|
3445
|
-
if (answer === undefined)
|
|
3446
|
-
return 1;
|
|
3447
|
-
answers.push(answer);
|
|
3448
|
-
}
|
|
3449
|
-
const all = [...words, ...answers];
|
|
3450
|
-
record("j", { id: id(entry), args: all });
|
|
3451
|
-
return Bun.spawn(commandOf(entry, all), { stdio: ["inherit", "inherit", "inherit"] }).exited;
|
|
3452
|
-
}
|
|
3453
|
-
|
|
3454
|
-
// src/j-cli.ts
|
|
3455
|
-
process27.exitCode = await runMain({ name: "j", version, run: j2 });
|
|
3
|
+
import{isInteractive,paint,warn,role,closest,table,printJson,jsonOption,fail,parse,ignoredFolders,cacheFolder}from"./chunk-ef4tt9f7.js";import{runMain,version,shellQuote}from"./chunk-m3r6m4gc.js";import{stopJob,visible,CTRL_KEY,styled,parseKeys,createState,withRows,highlighted,press,chosen,SYNC_START,SYNC_END,overwrite,input2}from"./chunk-6wcnr992.js";import{MAKEFILES}from"./chunk-ykfkfr0c.js";import process6 from"process";import process5 from"process";import{existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{dirname,join}from"path";import process3 from"process";import{openSync}from"fs";import process2 from"process";import tty from"tty";import process from"process";var PREVIEW_BYTES=65536,PREVIEW_LINES=200,PREVIEW_TIMEOUT_MS=3000,PLACEHOLDER=/\{([1-9]\d*)?\}/g;function previewCommand(template,line,hidden=[]){return template.replace(PLACEHOLDER,(_,field)=>shellQuote(field===void 0?line:hidden[Number(field)-1]??""))}function previewLines(output){let lines=output.split(`
|
|
4
|
+
`);if(lines.at(-1)==="")lines.pop();return lines.slice(0,PREVIEW_LINES)}async function runPreview(template,line,signal,hidden=[]){let proc=Bun.spawn(["sh","-c",`exec 2>&1
|
|
5
|
+
${previewCommand(template,line,hidden)}`],{stdin:"ignore",stdout:"pipe",stderr:"ignore",detached:!0}),stop=()=>{try{process.kill(-proc.pid,"SIGKILL")}catch{proc.kill()}},timer=setTimeout(stop,PREVIEW_TIMEOUT_MS),chunks=[],size=0;signal.addEventListener("abort",stop);try{for await(let chunk of proc.stdout)if(chunks.push(chunk),size+=chunk.length,size>=PREVIEW_BYTES){stop();break}}finally{clearTimeout(timer),signal.removeEventListener("abort",stop)}return signal.aborted?[]:previewLines(Buffer.concat(chunks).subarray(0,PREVIEW_BYTES).toString())}var MIN_HEIGHT=4,PREVIEW_MIN_COLUMNS=80,PREVIEW_MIN_ROWS=10,PREVIEW_SHARE=0.4,RESET="\x1B[0m",SEPARATOR=" \u2502 ",HEIGHT=/^(\d+)(%?)$/;function parseHeight(text){let found=HEIGHT.exec(text);if(found===null||Number(found[1])<1)return;return found[2]==="%"?{percent:Math.min(100,Number(found[1]))}:{lines:Number(found[1])}}function layoutFor(size,height,previewing,position="right"){let wanted="lines"in height?height.lines:Math.round(size.rows*height.percent/100),rows=Math.min(size.rows,Math.max(MIN_HEIGHT,wanted));if(position==="down"){let previewHeight=previewing&&rows>=PREVIEW_MIN_ROWS?Math.round(rows*PREVIEW_SHARE):0;return{height:rows,listHeight:rows-previewHeight,listWidth:size.columns,previewWidth:0,previewHeight}}let split=previewing&&size.columns>=PREVIEW_MIN_COLUMNS,listWidth=split?Math.floor(size.columns/2):size.columns;return{height:rows,listHeight:rows,listWidth,previewWidth:split?size.columns-listWidth-SEPARATOR.length:0,previewHeight:0}}function fit(text,width,plain,mark=plain,marked=new Set,styles){let room=Bun.stringWidth(text)>width?width-1:width,out="",used=0,at=0;for(let char of text){let size=Bun.stringWidth(char);if(used+size>room)break;let style=marked.has(at)?"":styles?.[at]??"";out+=style===""?(marked.has(at)?mark:plain)(char):`${style}${char}${RESET}`,used+=size,at+=char.length}if(room<width)out+=plain("\u2026"),used+=1;return{text:out,width:used}}var identity=(text)=>text;function fitStyled(line,width,plain=identity){let{text,styles}=styled(line);return fit(text,width,plain,plain,new Set,styles)}function queryShown(state,layout){return visible({text:state.query,caret:state.caret},Math.max(1,layout.listWidth-Bun.stringWidth(state.prompt)))}function caretCell(state,layout){let shown=queryShown(state,layout);return{column:Math.min(layout.listWidth,Bun.stringWidth(state.prompt)+shown.column+1),char:shown.at??" "}}function helpLines(state,layout,theme){let lines=["type to filter, up, down, ctrl-p, ctrl-n, pgup, pgdn, home, end, the wheel move","left, right, ctrl-a, ctrl-e move in the query, ctrl or alt with left or right by a word","ctrl-w or ctrl-backspace erase a word, ctrl-u back to the start, ctrl-k to the end, del ahead","ctrl-y puts back what they erased, ctrl-z suspends to the shell",`enter picks${state.multi?", tab marks":""}, esc or ctrl-c cancels`,...state.expect.length>0?[`${state.expect.join(", ")} end the pick as this command asks`]:[]],title="keys, any key closes this help";return[{text:theme.accent("keys, any key closes this help"),width:30},...lines.map((line)=>fit(` ${line}`,layout.listWidth,theme.label))]}function listLines(state,layout,theme){if(state.help)return helpLines(state,layout,theme);let header=state.header===""?[]:state.header.split(`
|
|
6
|
+
`).map((line)=>fitStyled(line,layout.listWidth,theme.label)),rows=Math.max(1,layout.listHeight-2-header.length),prefixWidth=state.multi?4:2,top=Math.max(0,Math.min(state.cursor-Math.floor(rows/2),state.matches.length-rows)),marks=(state.marked.size>0?` (${state.marked.size} marked)`:"")+(state.status===""?"":` ${state.status}`),promptWidth=Bun.stringWidth(state.prompt),shown=queryShown(state,layout),text=`${shown.before}${shown.at??""}${shown.after}`,query={text,width:Bun.stringWidth(text)},place=state.matches.length>rows?` (${state.cursor+1} of ${state.matches.length})`:"",count=fit(` ${state.matches.length}/${state.items.length}${place}${marks} ctrl-/ keys`,layout.listWidth,theme.label),lines=[{text:theme.accent(state.prompt)+query.text,width:promptWidth+query.width},count,...header];if(state.matches.length===0)lines.push(fit(" no match",layout.listWidth,theme.label));for(let[offset,match]of state.matches.slice(top,top+rows).entries()){let current=top+offset===state.cursor,pointer=current?theme.accent("\u276F"):" ",mark=state.multi?`${state.marked.has(match.index)?theme.id("\u25CF"):" "} `:"",text=fit(state.items[match.index],layout.listWidth-prefixWidth,current?theme.value:identity,theme.match??theme.accent,new Set(match.positions),state.styles[match.index]);lines.push({text:`${pointer} ${mark}${text.text}`,width:prefixWidth+text.width})}return lines}function render(state,layout,theme,preview=[]){let left=listLines(state,layout,theme);return Array.from({length:layout.height},(_,row)=>{if(row>=layout.listHeight)return row===layout.listHeight?theme.label("\u2500".repeat(layout.listWidth)):fitStyled(preview[row-layout.listHeight-1]??"",layout.listWidth).text;let list=left[row]??{text:"",width:0};if(layout.previewWidth===0)return list.text;return`${list.text}${" ".repeat(Math.max(0,layout.listWidth-list.width))}${theme.label(SEPARATOR)}${fitStyled(preview[row]??"",layout.previewWidth).text}`})}var PREVIEW_DELAY_MS=120,ESCAPE_WAIT_MS=30,OPEN={ctrl:"open"},HIDE_CURSOR="\x1B[?25l",SHOW_CURSOR="\x1B[?25h",REVERSE="\x1B[7m",REVERSE_END="\x1B[27m",PASTE_ON="\x1B[?2004h",PASTE_OFF="\x1B[?2004l",MOUSE_ON="\x1B[?1000h\x1B[?1006h",MOUSE_OFF="\x1B[?1006l\x1B[?1000l",CLEAR_BELOW="\r\x1B[J",SIGNALS=["SIGINT","SIGTERM","SIGHUP"];function up(lines){return lines>0?`\x1B[${lines}A`:""}function openTerminal(){let mode;try{mode=new tty.ReadStream(openSync("/dev/tty","r"))}catch{return fail("no terminal to read keys from (/dev/tty)")}let keys=Bun.file("/dev/tty").stream().getReader(),out=process2.stderr,resize;async function read(onChunk){let decoder=new TextDecoder;try{for(let chunk=await keys.read();!chunk.done;chunk=await keys.read())onChunk(decoder.decode(chunk.value,{stream:!0}))}catch{onChunk("\x03")}}return{get columns(){return out.columns||80},get rows(){return out.rows||24},theme:{accent:role("accent",out),label:role("label",out),value:role("value",out),id:role("id",out),match:(text)=>paint(out).underline(role("accent",out)(text))},write:(text)=>void out.write(text),listen(onChunk,onResize){resize=onResize,mode.setRawMode(!0),out.on("resize",onResize),read(onChunk)},suspend(){mode.setRawMode(!1),stopJob(),mode.setRawMode(!0)},close(){if(resize!==void 0)out.off("resize",resize);try{mode.setRawMode(!1)}finally{mode.destroy(),keys.cancel()}}}}async function select(rows,settings,terminal=openTerminal()){let{theme}=terminal,state=createState(rows,settings),preview=[],reserved=0,previewTimer,previewing=new AbortController,shownLine,finish,restored=!1,escape;function draw(clear=!1){if(restored)return;let layout=layoutFor({columns:terminal.columns,rows:terminal.rows},settings.height,settings.preview!==void 0,settings.previewPosition),frame=SYNC_START+HIDE_CURSOR;if(reserved!==layout.height||clear)frame+=CLEAR_BELOW+`
|
|
7
|
+
`.repeat(layout.height-1)+up(layout.height-1),reserved=layout.height;let caret=caretCell(state,layout);frame+=`\r${overwrite(render(state,layout,theme,preview),terminal.columns)}${up(layout.height-1)}\r\x1B[${caret.column}G${REVERSE}${caret.char}${REVERSE_END}\r${SYNC_END}`,terminal.write(frame)}function pageSize(){let headerLines=state.header===""?0:state.header.split(`
|
|
8
|
+
`).length;return Math.max(1,layoutFor({columns:terminal.columns,rows:terminal.rows},settings.height,settings.preview!==void 0,settings.previewPosition).listHeight-2-headerLines)}function refreshPreview(){let at=highlighted(state);if(settings.preview===void 0||at===shownLine)return;if(shownLine=at,clearTimeout(previewTimer),previewing.abort(),previewing=new AbortController,at===void 0){preview=[];return}let{signal}=previewing,template=settings.preview,row=state.rows[at];async function show(){let shown=typeof template==="string"?await runPreview(template,row.cells.join(" "),signal,row.hidden):await previewOf(template,row.hidden,signal);if(!signal.aborted)preview=shown,draw()}previewTimer=setTimeout(()=>void show(),PREVIEW_DELAY_MS)}function restore(){if(restored)return;restored=!0,clearTimeout(previewTimer),clearTimeout(escape),previewing.abort(),terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`),terminal.close()}function suspend(){if(terminal.suspend===void 0)return;terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`),terminal.suspend(),terminal.write(`${PASTE_ON}${MOUSE_ON}`),draw(!0)}let stop=()=>{state={...state,done:"cancel"},finish?.()},paste={active:!1},{reload}=settings,pending=[],busy=!1,draining=!1;async function reloadRows(){if(reload===void 0)return;busy=!0,state={...state,status:"reloading"},draw();try{let next=await reload.run();state={...withRows(state,next.rows,next.header),status:""},shownLine=void 0}catch(error){state={...state,status:`reload failed: ${error instanceof Error?error.message:String(error)}`}}finally{busy=!1}}async function drain(){if(draining)return;draining=!0;try{for(let key=pending.shift();key!==void 0&&state.done===void 0;key=pending.shift())if(key===OPEN||typeof key==="object"&&"ctrl"in key&&key.ctrl===reload?.key)await reloadRows();else if(key==="suspend")suspend();else state=press({...state,page:pageSize()},key)}finally{draining=!1}if(state.done!==void 0){finish?.();return}refreshPreview(),draw()}function onChunk(chunk){if(escape!==void 0)clearTimeout(escape),escape=void 0,chunk=`\x1B${chunk}`;else if(chunk==="\x1B"){escape=setTimeout(()=>{escape=void 0,takeKeys("\x1B")},ESCAPE_WAIT_MS);return}takeKeys(chunk)}function takeKeys(chunk){let keys=parseKeys(chunk,paste,[...settings.expect??[],...reload?.key===void 0?[]:[reload.key]]);if(busy&&keys.includes("cancel")){stop();return}pending.push(...keys),drain()}let ended=new Promise((resolve)=>{finish=resolve});process2.once("exit",restore);for(let signal of SIGNALS)process2.once(signal,stop);try{if(terminal.write(`${PASTE_ON}${MOUSE_ON}`),terminal.listen(onChunk,()=>draw(!0)),refreshPreview(),draw(!0),reload?.onOpen===!0)pending.push(OPEN),drain();await ended}finally{for(let signal of SIGNALS)process2.off(signal,stop);process2.off("exit",restore),restore()}return state.done==="accept"?{rows:chosen(state),key:state.key,query:state.query}:void 0}async function previewOf(preview,hidden,signal){try{return previewLines(await preview(hidden,signal))}catch(error){return[error instanceof Error?error.message:String(error)]}}var REMEMBERED=20;async function pick(rows,options){let height=parseHeight(options.height??"100%"),keys=[...options.expect??[],...options.reload?.key===void 0?[]:[options.reload.key]];if(height===void 0)throw Error(`pick: the height is lines or a percentage, not ${options.height}`);for(let key of keys)if(!CTRL_KEY.test(key))throw Error(`pick: ${key} is not a key it can report, one of ctrl-a to ctrl-z but ctrl-c, h, i, j and m`);let found=await select(rows,{multi:!1,prompt:options.prompt,query:"",height,preview:options.preview,previewPosition:"down",header:options.header,expect:options.expect,searched:options.searched,reload:options.reload});return found===void 0?void 0:{key:found.key,hidden:found.rows[0]?.hidden??[],query:found.query}}function heightFor(count){return String(Math.max(15,Math.ceil((count+4)/0.6)))}function historyFile(name){return join(cacheFolder(),name,"history.json")}function history(name){try{let file=historyFile(name);return existsSync(file)?JSON.parse(readFileSync(file,"utf-8")):{}}catch{return{}}}function runs(name){return history(name)[process3.cwd()]??[]}function record(name,run){let all=history(name),file=historyFile(name);all[process3.cwd()]=[run,...(all[process3.cwd()]??[]).filter((earlier)=>earlier.id!==run.id)].slice(0,REMEMBERED),mkdirSync(dirname(file),{recursive:!0}),writeFileSync(file,JSON.stringify(all))}function byRecency(items,previous,idOf){let rank=new Map(previous.map((run,index)=>[run.id,index]));return[...items.filter((item)=>rank.has(idOf(item))).sort((a,b)=>rank.get(idOf(a))-rank.get(idOf(b))),...items.filter((item)=>!rank.has(idOf(item)))]}function word(arg){if(typeof arg==="string")return`=${arg}`;return"given"in arg?`+${arg.given}`:`?${arg.ask}`}function emit(mode,typed,recorded,command){let words=command.map(word);console.log([mode,typed,recorded,...words].join(`
|
|
9
|
+
`))}function list(rows){console.log(JSON.stringify(rows))}import process4 from"process";import{existsSync as existsSync2,readdirSync,readFileSync as readFileSync2}from"fs";import{dirname as dirname2,join as join2,resolve as resolvePath}from"path";var JUSTFILE=/^\.?justfile$/i,TASKFILES=["Taskfile.yml","taskfile.yml","Taskfile.yaml","taskfile.yaml","Taskfile.dist.yml","taskfile.dist.yml","Taskfile.dist.yaml","taskfile.dist.yaml"],MISE_FILES=["mise.toml",".mise.toml","mise.local.toml",".mise.local.toml","mise",".mise","mise-tasks",".mise-tasks",".config/mise.toml",".config/mise"],LOCKFILES=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]],QUALIFIED=/^([a-z]+):(?!:)(.+)$/,BLANKS=/\s+/,TRAILING_SLASHES=/\/+$/,VERSION_SUFFIX=/@.*/,LEADING_HASHES=/^#*/,INCLUDE=/^(?:-|s)?include[ \t]+([^#]+)/,GLOB_CHARS=/[*?[]/,installed=new Map;function has(tool){if(!installed.has(tool))installed.set(tool,Bun.which(tool)!==null);return installed.get(tool)}function list2(dir){try{return readdirSync(dir)}catch{return[]}}function locate(dir,here,names){for(let current=dir;;current=join2(current,"..")){let found=names.find((name)=>existsSync2(join2(current,name)));if(found!==void 0)return join2(current,found);let absolute=resolvePath(current);if(!here||existsSync2(join2(current,".git"))||dirname2(absolute)===absolute)return}}function children(dir="."){let ignored=ignoredFolders();return readdirSync(dir,{withFileTypes:!0}).filter((child)=>child.isDirectory()&&!child.name.startsWith(".")&&!ignored.has(child.name)).map((child)=>child.name).toSorted()}function build(base,items){return items.map((item)=>({...base,doc:null,parameters:[],...item}))}function text(value){if(typeof value==="string")return value;if(Array.isArray(value)&&value.every((line)=>typeof line==="string"))return value.join(`
|
|
10
|
+
`);return Bun.YAML.stringify(value,null,2)??""}function field(value,key){let found=value!==null&&typeof value==="object"?value[key]:void 0;return typeof found==="string"?found:null}function recipes(tree){return[...Object.values(tree.recipes).filter((recipe)=>!recipe.private),...Object.values(tree.modules).flatMap((module)=>recipes(module))]}function justFlags(dir,here){if(here)return[];let file=list2(dir).find((name)=>JUSTFILE.test(name));return file===void 0?void 0:["--justfile",join2(dir,file)]}function just(dir,here){let flags=justFlags(dir,here);if(flags===void 0||!has("just"))return[];let proc=Bun.spawnSync(["just",...flags,"--dump","--dump-format","json"],{stderr:"pipe"});if(!proc.success)return[];let items=recipes(JSON.parse(proc.stdout.toString())).map((recipe)=>({name:recipe.namepath,doc:recipe.doc,parameters:recipe.parameters}));return build({kind:"just",tag:"just",runner:["just"],separated:!1,dir},items)}function targets(source){let found=new Map,pending=null;for(let line of source.split(`
|
|
11
|
+
`)){if(line.startsWith("\t"))continue;let[rule="",...rest]=line.split("#"),comment=rest.join("#").replace(LEADING_HASHES,"").trim()||null;if(rule.trim()===""){pending=line.startsWith("##")?comment:null;continue}let colon=rule.indexOf(":"),assignment=rule[colon+1]==="="||rule.slice(colon+1).startsWith(":=")||rule.slice(0,colon).includes("=");if(colon===-1||assignment){pending=null;continue}let doc=comment??pending;for(let name of rule.slice(0,colon).trim().split(BLANKS)){if(name.startsWith(".")||name.includes("%")||name.includes("$"))continue;if(!found.has(name))found.set(name,doc)}pending=null}return[...found].map(([name,doc])=>({name,doc}))}function show(source,target){let lines=source.split(`
|
|
12
|
+
`),start=lines.findIndex((line)=>{let hash=line.indexOf("#"),rule=hash===-1?line:line.slice(0,hash),colon=rule.indexOf(":");return colon!==-1&&rule[colon+1]!=="="&&!rule.slice(0,colon).includes("=")&&rule.slice(0,colon).trim().split(BLANKS).includes(target)});if(start===-1)return target;let end=start+1;while(end<lines.length&&(lines[end].startsWith("\t")||lines[end].trim()===""))end++;return lines.slice(start,end).join(`
|
|
13
|
+
`).trimEnd()}function withIncludes(source,dir,seen){return source.split(`
|
|
14
|
+
`).map((line)=>{let match=INCLUDE.exec(line);if(!match)return line;return match[1].trim().split(BLANKS).flatMap((path)=>GLOB_CHARS.test(path)?[...new Bun.Glob(path).scanSync({cwd:dir})].sort():[path]).map((path)=>resolvePath(dir,path)).filter((file)=>!seen.has(file)&&existsSync2(file)).map((file)=>(seen.add(file),withIncludes(readFileSync2(file,"utf-8"),dir,seen))).join(`
|
|
15
|
+
`)}).join(`
|
|
16
|
+
`)}function make(dir){let file=MAKEFILES.find((name)=>existsSync2(join2(dir,name)));if(file===void 0)return[];let path=resolvePath(dir,file),source=withIncludes(readFileSync2(path,"utf-8"),dir,new Set([path]));return build({kind:"make",tag:"make",runner:["make"],separated:!1,dir},targets(source).map((target)=>({...target,body:show(source,target.name)})))}function manager(dir,manifest){let declared=typeof manifest.packageManager==="string"?manifest.packageManager.replace(VERSION_SUFFIX,""):void 0,known=LOCKFILES.find(([,name])=>name===declared);if(known!==void 0)return known[1];for(let current=resolvePath(dir);;current=dirname2(current)){let found=LOCKFILES.find(([file])=>existsSync2(join2(current,file)));if(found!==void 0)return found[1];if(dirname2(current)===current)return"bun"}}function table2(value){return value!==null&&typeof value==="object"?value:{}}function packageScripts(dir,here){let file=locate(dir,here,["package.json"]);if(file===void 0)return[];let manifest=JSON.parse(readFileSync2(file,"utf-8")),tool=manager(dirname2(file),manifest),items=Object.entries(table2(manifest.scripts)).map(([name,command])=>({name,body:text(command)}));return build({kind:"package",tag:tool,runner:[tool,"run"],separated:tool==="npm",dir:dirname2(file)},items)}function composer(dir,here){let file=locate(dir,here,["composer.json"]);if(file===void 0)return[];let manifest=JSON.parse(readFileSync2(file,"utf-8")),descriptions=table2(manifest["scripts-descriptions"]),items=Object.entries(table2(manifest.scripts)).map(([name,command])=>({name,doc:field(descriptions,name),body:text(command)}));return build({kind:"composer",tag:"composer",runner:["composer","run"],separated:!0,dir:dirname2(file)},items)}function deno(dir,here){let file=locate(dir,here,["deno.json","deno.jsonc"]);if(file===void 0)return[];let manifest=Bun.JSONC.parse(readFileSync2(file,"utf-8")),items=Object.entries(table2(manifest.tasks)).map(([name,task])=>({name,doc:field(task,"description"),body:field(task,"command")??text(task)}));return build({kind:"deno",tag:"deno",runner:["deno","task"],separated:!1,dir:dirname2(file)},items)}function taskfile(dir,here){let file=locate(dir,here,TASKFILES);if(file===void 0)return[];let tasks=table2(Bun.YAML.parse(readFileSync2(file,"utf-8"))?.tasks),items=Object.entries(tasks).filter(([,task])=>!(task!==null&&typeof task==="object"&&task.internal===!0)).map(([name,task])=>({name,doc:field(task,"desc")??field(task,"summary"),body:text(task)}));return build({kind:"task",tag:"task",runner:["task"],separated:!0,dir:dirname2(file)},items)}function mise(dir,here){if(!has("mise")||!here&&!MISE_FILES.some((name)=>existsSync2(join2(dir,name))))return[];let proc=Bun.spawnSync(["mise","tasks","ls","--json"],{cwd:dir,stderr:"pipe"});if(!proc.success)return[];let root=`${resolvePath(dir)}/`,items=JSON.parse(proc.stdout.toString()).filter((task)=>!task.hide&&(here||!task.global&&task.source.startsWith(root))).map((task)=>({name:task.name,doc:task.description||null,body:task.file??task.run.join(`
|
|
17
|
+
`)}));return build({kind:"mise",tag:"mise",runner:["mise","run"],separated:!1,dir},items)}function pyproject(dir,here){let file=locate(dir,here,["pyproject.toml"]);if(file===void 0)return[];let manifest=Bun.TOML.parse(readFileSync2(file,"utf-8")),tool=table2(manifest.tool),project=table2(manifest.project),uv=locate(dirname2(file),!0,["uv.lock"])!==void 0,poe=Object.entries(table2(table2(tool.poe).tasks)).filter(([name])=>!name.startsWith("_")).map(([name,task])=>({name,doc:field(task,"help"),body:field(task,"cmd")??field(task,"shell")??text(task)})),entryPoints=Object.entries(table2(project.scripts)).map(([name,target])=>({name,body:text(target)}));return[...build({kind:"poe",tag:"poe",runner:uv?["uv","run","poe"]:["poe"],separated:!1,dir:dirname2(file)},poe),...build({kind:"uv",tag:"uv",runner:["uv","run"],separated:!1,dir:dirname2(file)},entryPoints)]}var READERS=[just,make,packageScripts,composer,deno,taskfile,mise,pyproject],READER_OF={just,make,package:packageScripts,composer,deno,task:taskfile,mise,poe:pyproject,uv:pyproject},MANIFEST_OF=new Map([[just,"justfile"],[make,"Makefile"],[packageScripts,"package.json"],[composer,"composer.json"],[deno,"deno.json"],[taskfile,"Taskfile.yml"],[mise,"mise.toml"],[pyproject,"pyproject.toml"]]);function readOr(read,fallback){try{return read()}catch{return fallback}}function workspaces(){let manifest=readOr(()=>JSON.parse(readFileSync2("package.json","utf-8")),{}),declared=Array.isArray(manifest.workspaces)?manifest.workspaces:table2(manifest.workspaces).packages,pnpm=readOr(()=>table2(Bun.YAML.parse(readFileSync2("pnpm-workspace.yaml","utf-8"))).packages,void 0),patterns=[declared,pnpm].flatMap((value)=>Array.isArray(value)?value.filter((pattern)=>typeof pattern==="string"):[]),excluded=patterns.filter((pattern)=>pattern.startsWith("!")).map((pattern)=>new Bun.Glob(pattern.slice(1)));return patterns.filter((pattern)=>!pattern.startsWith("!")).flatMap((pattern)=>[...new Bun.Glob(`${pattern.replace(TRAILING_SLASHES,"")}/package.json`).scanSync({cwd:"."})].map((file)=>dirname2(file))).filter((dir)=>!dir.split("/").includes("node_modules")&&!excluded.some((glob)=>glob.match(dir)))}function folders(){return[...new Set([...children(),...workspaces()])].filter((dir)=>dir!==".")}function guarded(reader,dir,here,isWarned=!1){try{return reader(dir,here)}catch(error){if(isWarned)warn(`j: skipped ${join2(dir,MANIFEST_OF.get(reader)??"a manifest")}, it does not parse (${error instanceof Error?error.message:String(error)})`);return[]}}function everything(){let here=READERS.flatMap((reader)=>guarded(reader,".",!0,!0)),below=folders().flatMap((dir)=>READERS.flatMap((reader)=>guarded(reader,dir,!1,!0))),seen=new Set;return[...here,...below].filter((entry)=>{let id=`${entry.kind} ${entry.dir} ${entry.name}`,fresh=!seen.has(id);return seen.add(id),fresh})}function readKind(kind,dir){return guarded(READER_OF[kind],dir,dir===".").filter((entry)=>entry.kind===kind)}function key(entry){return entry.dir==="."?entry.name:`${entry.dir}/${entry.name}`}function id(entry){return`${entry.tag}:${key(entry)}`}function resolve(entries,named){let qualified=QUALIFIED.exec(named),tagged=qualified&&entries.some((entry)=>entry.tag===qualified[1])?qualified:void 0,pool=tagged?entries.filter((entry)=>entry.tag===tagged[1]):entries,rest=tagged?tagged[2]:named,exact=pool.filter((entry)=>key(entry)===rest);return exact.length>0?exact:pool.filter((entry)=>entry.name===rest)}function shortest(entries,entry){let found=resolve(entries,key(entry));return found.length===1&&found[0]===entry?key(entry):id(entry)}function signature(entry){return entry.parameters.map((parameter)=>parameter.default===null&¶meter.kind==="singular"?`<${parameter.name}>`:`[${parameter.name}]`).join(" ")}var TINTS={just:"yellow",make:"blue",package:"magenta",composer:"cyan",deno:"green",task:"cyan",mise:"red",poe:"green",uv:"green"};function labelled(entries){return new Set(entries.map((entry)=>entry.tag)).size>1}function row(entry,labels,signed){let colors=paint(process4.stderr),keyed=entry.dir==="."?entry.name:`${colors.dim(`${entry.dir}/`)}${entry.name}`;return{hidden:[entry.kind,entry.dir,entry.name,id(entry)],cells:[...labels?[colors[TINTS[entry.kind]](entry.tag)]:[],keyed,...signed?[colors.cyan(signature(entry))]:[],colors.dim(entry.doc??"")]}}async function pickJob(entries,narrowed=!1){let labels=labelled(entries),signed=entries.some((entry)=>signature(entry)!==""),picked=await pick(entries.map((entry)=>row(entry,labels,signed)),{prompt:`${[...new Set(entries.map((entry)=>entry.tag))].join("/")}> `,searched:labels?2:1,...narrowed?{height:heightFor(entries.length)}:{},preview:`${process4.execPath} ${process4.argv[1]} --show {1} {2} {3}`});return entries.find((candidate)=>id(candidate)===picked?.hidden[3])}var usage="j [name] [args...]\nj -\n\nWithout a name, picks a recipe, script or task of this folder, its parents and its child folders and runs it, the ones run last first; without a terminal it lists them instead.\n`j -` runs the last one again with the same arguments, `j <name> [args...]` runs without the picker, the words after the name filling the parameters in order.\nThe sources are a Justfile, a Makefile, package.json and composer.json scripts, deno tasks, a Taskfile, mise tasks and a pyproject; a name several share offers them, unless qualified by its runner (`just:check`).",EXITS=[["its own","the code of the command it ran"],[1,"there is nothing to run here or nothing by that name"]],options={json:jsonOption("[{ id, key, runner, dir, name, doc, parameters }]")};function preview(kind,dir,name){let entry=readKind(kind,dir).find((candidate)=>candidate.name===name);if(entry===void 0)return;let colors=paint(process5.stdout);if(console.log(`${colors.dim(`$ ${dir==="."?"":`env -C ${dir} `}`)}${colors.bold([...entry.runner,entry.name].join(" "))}
|
|
18
|
+
`),entry.body!==void 0)console.log(entry.body);else Bun.spawnSync(["just",...justFlags(dir,dir===".")??[],"--show",name],{stdout:"inherit",stderr:"inherit"})}function names(found){let described=(entry)=>entry.doc===null||entry.doc===""?entry.tag:entry.doc;return[...new Set(found.map(key))].flatMap((name)=>{let same=resolve(found,name);return same.length===1?[[name,described(same[0])]]:[[name,same.map((entry)=>entry.tag).join(", ")],...same.map((entry)=>[id(entry),described(entry)])]})}function completions(){try{return[...names(everything()),["-","the last one again, with its arguments"]]}catch{return[]}}function listed(found){let labels=labelled(found);return byRecency(found,runs("j"),id).map((entry)=>({label:[labels?entry.tag:"",key(entry),signature(entry)].filter(Boolean).join(" "),hint:entry.doc??"",typed:shortest(found,entry),preview:["--show",entry.kind,entry.dir,entry.name],editsTyped:!0}))}function listing(found){let colors=paint(process5.stdout),labels=labelled(found);return table(found.map((entry)=>[...labels?[entry.tag]:[],key(entry),signature(entry),colors.dim(entry.doc??"")]))}function missing(entry,given){return entry.parameters.slice(given.length).filter((parameter)=>parameter.default===null&¶meter.kind==="singular").map((parameter)=>parameter.name)}function commandOf(entry,args){let separated=entry.separated&&args.length>0?["--"]:[];return[...entry.dir==="."?[]:["env","-C",entry.dir],...entry.runner,entry.name,...separated,...args]}async function j(argv){let[flag=""]=argv;if(flag==="--show"){let[kind="just",dir=".",name=""]=argv.slice(1);return preview(kind,dir,name),0}if(flag==="--record")return record("j",{id:argv[1]??"",args:argv.slice(2)}),0;if(flag==="--list"||flag==="--names"){let found=everything();if(found.length===0)fail("nothing to run here: no recipe, target, script or task",1);if(flag==="--list")list(listed(found));else console.log(names(found).map(([name,description])=>`${name} ${description}`).join(`
|
|
19
|
+
`));return 0}let emitting=flag==="--emit",args=emitting?argv.slice(1):argv,parsed=args[0]==="-"?{values:{},positionals:["-"],rest:args.slice(1)}:parse(args,usage,options,{exits:EXITS,positionals:["[name]"],candidates:{"[name]":completions},trailing:!0,replaces:"reading the Justfile, Makefile, package.json scripts or composer scripts to find what to run, then retyping it",examples:["j",["j test","run the test recipe, script or task"],["j api/test --watch","a child folder's, with an argument"],["j just:check","the one of a runner, when several share the name"],["j -","the last one again"]]}),[named]=parsed.positionals,given=parsed.rest??[],found=everything();if(found.length===0)fail("nothing to run here: no recipe, target, script or task",1);let previous=runs("j"),interactive=isInteractive()&&parsed.values.json!==!0,entry,words=given;if(named==="-"){let earlier=previous[0];if(entry=earlier&&found.find((candidate)=>id(candidate)===earlier.id),entry===void 0)fail(earlier?`${earlier.id} is gone`:"nothing run here yet",1);words=[...earlier.args,...given]}else if(named===void 0){if(!interactive){if(emitting)fail("the picker needs a terminal",1);if(parsed.values.json===!0)printJson(found.map((each)=>({id:id(each),key:key(each),runner:each.tag,dir:each.dir,name:each.name,doc:each.doc,parameters:each.parameters})));else console.log(listing(found));return 0}entry=await pickJob(byRecency(found,previous,id))}else{let matching=resolve(found,named);if(matching.length===0){let nearest=closest(named,found.map(key));fail(`nothing named ${named}${nearest===void 0?"":`, did you mean ${nearest}?`}`,1)}if(matching.length>1&&!interactive)fail(`${named} is several: ${matching.map(id).join(", ")}`,1,"qualify it with its runner");entry=matching.length===1?matching[0]:await pickJob(matching,!0)}if(entry===void 0)return 1;let typed=shortest(found,entry),asks=missing(entry,words);if(emitting)return emit("run",typed,id(entry),commandOf(entry,[...words.map((word)=>({given:word})),...asks.map((ask)=>({ask}))])),0;let answers=[];for(let ask of asks){let answer=await input2(ask,{history:`j ${id(entry)} ${ask}`});if(answer===void 0)return 1;answers.push(answer)}let all=[...words,...answers];return record("j",{id:id(entry),args:all}),Bun.spawn(commandOf(entry,all),{stdio:["inherit","inherit","inherit"]}).exited}process6.exitCode=await runMain({name:"j",version,run:j});
|