@kaynooo/cli-dl 0.0.0-stage → 0.0.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/LICENSE +21 -0
- package/README.md +47 -2
- package/dist/cli.js +3100 -0
- package/package.json +39 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,3100 @@
|
|
|
1
|
+
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
2
|
+
// @bun
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __returnValue = (v) => v;
|
|
5
|
+
function __exportSetter(name, newValue) {
|
|
6
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
7
|
+
}
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, {
|
|
11
|
+
get: all[name],
|
|
12
|
+
enumerable: true,
|
|
13
|
+
configurable: true,
|
|
14
|
+
set: __exportSetter.bind(all, name)
|
|
15
|
+
});
|
|
16
|
+
};
|
|
17
|
+
var __esm = (fn, res, err) => () => {
|
|
18
|
+
if (fn)
|
|
19
|
+
try {
|
|
20
|
+
res = fn(fn = 0);
|
|
21
|
+
} catch (e) {
|
|
22
|
+
err = [e];
|
|
23
|
+
}
|
|
24
|
+
if (err)
|
|
25
|
+
throw err[0];
|
|
26
|
+
return res;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
// ../kit/src/advisory.ts
|
|
30
|
+
var init_advisory = () => {};
|
|
31
|
+
|
|
32
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
|
|
33
|
+
function Ao(t, e, r = "...") {
|
|
34
|
+
let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
|
|
35
|
+
if (t.length <= e)
|
|
36
|
+
return t;
|
|
37
|
+
let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
|
|
38
|
+
if (o && !Y.test(t[c.length] ?? " "))
|
|
39
|
+
c = c.replace(Nt, "") || c;
|
|
40
|
+
if (o)
|
|
41
|
+
c = c.trimEnd();
|
|
42
|
+
return s ? (c + n).slice(0, l) : c + n;
|
|
43
|
+
}
|
|
44
|
+
var N, Nt, Y, be, W;
|
|
45
|
+
var init_chunk_rkhsft4a = __esm(() => {
|
|
46
|
+
N = new Map;
|
|
47
|
+
Nt = /\s+\S*$/;
|
|
48
|
+
Y = /\s/;
|
|
49
|
+
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));
|
|
50
|
+
W = new Map;
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
|
|
54
|
+
var init_text = __esm(() => {
|
|
55
|
+
init_chunk_rkhsft4a();
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
// ../kit/src/mode.ts
|
|
59
|
+
import process2 from "process";
|
|
60
|
+
function isSet(value) {
|
|
61
|
+
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
62
|
+
}
|
|
63
|
+
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
64
|
+
const chosen = env.KIT_MODE;
|
|
65
|
+
if (chosen !== undefined && MODES.has(chosen))
|
|
66
|
+
return chosen;
|
|
67
|
+
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
68
|
+
return "agent";
|
|
69
|
+
if (stream.isTTY === true)
|
|
70
|
+
return "terminal";
|
|
71
|
+
return isSet(env.CI) ? "ci" : "pipe";
|
|
72
|
+
}
|
|
73
|
+
var MODES, AGENT_VARIABLES;
|
|
74
|
+
var init_mode = __esm(() => {
|
|
75
|
+
MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
76
|
+
AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
80
|
+
function b(r) {
|
|
81
|
+
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
82
|
+
if (!G2.test(e))
|
|
83
|
+
return [0, 0, 0];
|
|
84
|
+
if (e.length === 3 || e.length === 4)
|
|
85
|
+
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
86
|
+
if (e.length !== 6 && e.length !== 8)
|
|
87
|
+
throw Error(`Invalid hex color length: ${e.length}`);
|
|
88
|
+
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
89
|
+
}
|
|
90
|
+
function C(r, e = globalThis.process?.env ?? {}) {
|
|
91
|
+
if (e.FORCE_COLOR !== undefined)
|
|
92
|
+
return h.has(e.FORCE_COLOR);
|
|
93
|
+
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
94
|
+
return false;
|
|
95
|
+
return r?.isTTY === true;
|
|
96
|
+
}
|
|
97
|
+
function f(r, e = []) {
|
|
98
|
+
let l = "", n = "";
|
|
99
|
+
for (let t = 0, i = e.length;t < i; t++)
|
|
100
|
+
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
101
|
+
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
102
|
+
return new Proxy(c, { get(t, i) {
|
|
103
|
+
let a = B[i];
|
|
104
|
+
if (Array.isArray(a)) {
|
|
105
|
+
let s = g.get(i);
|
|
106
|
+
if (s === undefined)
|
|
107
|
+
s = f(r, [...e, a]), g.set(i, s);
|
|
108
|
+
return s;
|
|
109
|
+
}
|
|
110
|
+
if (typeof a === "function")
|
|
111
|
+
return (...s) => {
|
|
112
|
+
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
113
|
+
if (u === undefined) {
|
|
114
|
+
if (g.size >= 64)
|
|
115
|
+
g.clear();
|
|
116
|
+
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
117
|
+
}
|
|
118
|
+
return u;
|
|
119
|
+
};
|
|
120
|
+
throw Error(`Unknown style: ${String(i)}`);
|
|
121
|
+
} });
|
|
122
|
+
}
|
|
123
|
+
function Fe(r = {}) {
|
|
124
|
+
return f(r);
|
|
125
|
+
}
|
|
126
|
+
var G2, B, h, o;
|
|
127
|
+
var init_chunk_x450vn3m = __esm(() => {
|
|
128
|
+
G2 = /^[a-f0-9]+$/i;
|
|
129
|
+
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") => {
|
|
130
|
+
let [l, n, c] = b(r);
|
|
131
|
+
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
132
|
+
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
133
|
+
h = new Set(["", "1", "2", "3", "true"]);
|
|
134
|
+
o = Fe();
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
|
|
138
|
+
var init_colors = __esm(() => {
|
|
139
|
+
init_chunk_x450vn3m();
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
// ../kit/src/config.ts
|
|
143
|
+
import { existsSync } from "fs";
|
|
144
|
+
import { dirname, join, resolve } from "path";
|
|
145
|
+
import process3 from "process";
|
|
146
|
+
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
147
|
+
const wanted = typeof names === "string" ? [names] : names;
|
|
148
|
+
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
149
|
+
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
150
|
+
if (found !== undefined)
|
|
151
|
+
return found;
|
|
152
|
+
if (stop(dir) || dirname(dir) === dir)
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
var init_config = __esm(() => {
|
|
157
|
+
init_args();
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
// ../kit/src/user-config.ts
|
|
161
|
+
import { homedir } from "os";
|
|
162
|
+
import { isAbsolute, join as join2 } from "path";
|
|
163
|
+
import process4 from "process";
|
|
164
|
+
function xdgFolder(value, fallback) {
|
|
165
|
+
return value !== undefined && isAbsolute(value) ? value : fallback;
|
|
166
|
+
}
|
|
167
|
+
function configBase(where = {}) {
|
|
168
|
+
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
169
|
+
return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
|
|
170
|
+
}
|
|
171
|
+
function userConfigPath(bin, where = {}) {
|
|
172
|
+
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
173
|
+
}
|
|
174
|
+
var init_user_config = () => {};
|
|
175
|
+
|
|
176
|
+
// ../kit/src/theme.ts
|
|
177
|
+
import { existsSync as existsSync2, readFileSync, statSync } from "fs";
|
|
178
|
+
import { homedir as homedir2 } from "os";
|
|
179
|
+
import { join as join3, resolve as resolve2 } from "path";
|
|
180
|
+
import process5 from "process";
|
|
181
|
+
function toLinear(channel) {
|
|
182
|
+
const value = channel / 255;
|
|
183
|
+
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
|
|
184
|
+
}
|
|
185
|
+
function toOklab(hex) {
|
|
186
|
+
const [r, g, b] = [1, 3, 5].map((at) => toLinear(Number.parseInt(hex.slice(at, at + 2), 16)));
|
|
187
|
+
const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
|
|
188
|
+
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
|
|
189
|
+
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
|
|
190
|
+
return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];
|
|
191
|
+
}
|
|
192
|
+
function fromOklab([lightness, a, b]) {
|
|
193
|
+
const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;
|
|
194
|
+
const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;
|
|
195
|
+
const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;
|
|
196
|
+
const channels = [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s];
|
|
197
|
+
return `#${channels.map((channel) => fromLinear(channel).toString(16).padStart(2, "0")).join("")}`;
|
|
198
|
+
}
|
|
199
|
+
function gradientAt(theme, ratio) {
|
|
200
|
+
if (theme.gradient === undefined)
|
|
201
|
+
return;
|
|
202
|
+
const key = theme.gradient.join();
|
|
203
|
+
let ends = ENDS.get(key);
|
|
204
|
+
if (ends === undefined) {
|
|
205
|
+
ends = [toOklab(theme.gradient[0]), toOklab(theme.gradient[1])];
|
|
206
|
+
ENDS.set(key, ends);
|
|
207
|
+
}
|
|
208
|
+
const at = Math.min(1, Math.max(0, ratio));
|
|
209
|
+
const [from, to] = ends;
|
|
210
|
+
return fromOklab(from.map((start, index) => start + (to[index] - start) * at));
|
|
211
|
+
}
|
|
212
|
+
function isColorSpec(spec) {
|
|
213
|
+
if (typeof spec === "number")
|
|
214
|
+
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
215
|
+
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
216
|
+
}
|
|
217
|
+
function cubeLevel(channel) {
|
|
218
|
+
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
219
|
+
}
|
|
220
|
+
function nearest256(hex) {
|
|
221
|
+
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
222
|
+
const levels = rgb.map(cubeLevel);
|
|
223
|
+
const cube = levels.map((level) => CUBE[level]);
|
|
224
|
+
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
225
|
+
const greyValue = 8 + grey * 10;
|
|
226
|
+
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
227
|
+
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
228
|
+
}
|
|
229
|
+
function hasTrueColor(env) {
|
|
230
|
+
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
231
|
+
}
|
|
232
|
+
function tinted(colors, spec, env = process5.env) {
|
|
233
|
+
if (typeof spec === "number")
|
|
234
|
+
return colors.ansi256(spec);
|
|
235
|
+
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
236
|
+
if (HEX.test(token))
|
|
237
|
+
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
238
|
+
return chain[token] ?? chain;
|
|
239
|
+
}, colors);
|
|
240
|
+
}
|
|
241
|
+
function shaded(theme, colors, glyph, cells, width, env = process5.env) {
|
|
242
|
+
return Array.from({ length: cells }, (_, index) => tinted(colors, gradientAt(theme, width <= 1 ? 0 : index / (width - 1)) ?? theme.colors.accent, env)(glyph)).join("");
|
|
243
|
+
}
|
|
244
|
+
function isRecord(value) {
|
|
245
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
246
|
+
}
|
|
247
|
+
function readThemeFile(path, warn) {
|
|
248
|
+
try {
|
|
249
|
+
const stat = statSync(path, { throwIfNoEntry: false });
|
|
250
|
+
if (stat === undefined)
|
|
251
|
+
return;
|
|
252
|
+
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
253
|
+
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
257
|
+
if (isRecord(parsed))
|
|
258
|
+
return parsed;
|
|
259
|
+
warn(`${path} is not a JSON object, theme ignored`);
|
|
260
|
+
} catch (error) {
|
|
261
|
+
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
262
|
+
}
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
function applyPreset(theme, name, warn, where) {
|
|
266
|
+
if (name === undefined)
|
|
267
|
+
return;
|
|
268
|
+
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
269
|
+
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const preset = PRESETS[name];
|
|
273
|
+
Object.assign(theme.colors, preset.colors);
|
|
274
|
+
Object.assign(theme.glyphs, preset.glyphs);
|
|
275
|
+
if (preset.accents !== undefined)
|
|
276
|
+
theme.accents = [...preset.accents];
|
|
277
|
+
if (Object.hasOwn(preset, "gradient"))
|
|
278
|
+
theme.gradient = preset.gradient;
|
|
279
|
+
return name;
|
|
280
|
+
}
|
|
281
|
+
function applyFile(theme, file, where, warn) {
|
|
282
|
+
if (isRecord(file.colors)) {
|
|
283
|
+
for (const [key, value] of Object.entries(file.colors)) {
|
|
284
|
+
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
285
|
+
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
286
|
+
else if (!isColorSpec(value))
|
|
287
|
+
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
288
|
+
else
|
|
289
|
+
theme.colors[key] = value;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if (isRecord(file.glyphs)) {
|
|
293
|
+
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
294
|
+
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
295
|
+
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
296
|
+
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
297
|
+
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
298
|
+
else
|
|
299
|
+
theme.glyphs[key] = value;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
303
|
+
theme.accents = [...file.accents];
|
|
304
|
+
else if (file.accents !== undefined)
|
|
305
|
+
warn(`${where}: accents must be a non-empty list of colours`);
|
|
306
|
+
if (file.gradient === null)
|
|
307
|
+
theme.gradient = undefined;
|
|
308
|
+
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
309
|
+
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
310
|
+
else if (file.gradient !== undefined)
|
|
311
|
+
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
312
|
+
if (isRecord(file.bins)) {
|
|
313
|
+
for (const [bin, value] of Object.entries(file.bins)) {
|
|
314
|
+
if (isColorSpec(value))
|
|
315
|
+
theme.bins[bin] = value;
|
|
316
|
+
else
|
|
317
|
+
warn(`${where}: bin ${bin} has no valid colour`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
function endsWalk(home) {
|
|
322
|
+
return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
|
|
323
|
+
}
|
|
324
|
+
function warnOnce(message) {
|
|
325
|
+
if (warned.has(message))
|
|
326
|
+
return;
|
|
327
|
+
warned.add(message);
|
|
328
|
+
console.error(`warning: theme ${message}`);
|
|
329
|
+
}
|
|
330
|
+
function isPath(chosen) {
|
|
331
|
+
return chosen.includes("/") || chosen.endsWith(".json");
|
|
332
|
+
}
|
|
333
|
+
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
334
|
+
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
335
|
+
const sources = [];
|
|
336
|
+
const chosen = env.KIT_THEME ?? "";
|
|
337
|
+
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
338
|
+
if (isPath(chosen))
|
|
339
|
+
wanted.push(resolve2(from, chosen));
|
|
340
|
+
const files = [];
|
|
341
|
+
for (const path of wanted) {
|
|
342
|
+
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
343
|
+
if (path !== undefined && file !== undefined)
|
|
344
|
+
files.push({ path, file });
|
|
345
|
+
}
|
|
346
|
+
let preset = "default";
|
|
347
|
+
if (chosen !== "" && !isPath(chosen)) {
|
|
348
|
+
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
349
|
+
} else {
|
|
350
|
+
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
351
|
+
if (named !== undefined)
|
|
352
|
+
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
353
|
+
}
|
|
354
|
+
for (const { path, file } of files) {
|
|
355
|
+
applyFile(theme, file, path, warn);
|
|
356
|
+
sources.push(path);
|
|
357
|
+
}
|
|
358
|
+
return { theme, sources, preset };
|
|
359
|
+
}
|
|
360
|
+
function activeTheme() {
|
|
361
|
+
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
362
|
+
if (current === undefined || key !== currentKey) {
|
|
363
|
+
current = loadTheme();
|
|
364
|
+
currentKey = key;
|
|
365
|
+
}
|
|
366
|
+
return current;
|
|
367
|
+
}
|
|
368
|
+
var fromLinear = (value) => Math.round(255 * Math.min(1, Math.max(0, value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055))), ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
|
|
369
|
+
var init_theme = __esm(() => {
|
|
370
|
+
init_config();
|
|
371
|
+
init_user_config();
|
|
372
|
+
ENDS = new Map;
|
|
373
|
+
DEFAULT = {
|
|
374
|
+
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" },
|
|
375
|
+
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" },
|
|
376
|
+
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
377
|
+
bins: {},
|
|
378
|
+
gradient: ["#c084fc", "#67e8f9"]
|
|
379
|
+
};
|
|
380
|
+
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" };
|
|
381
|
+
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" };
|
|
382
|
+
ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
383
|
+
PRESETS = {
|
|
384
|
+
default: {},
|
|
385
|
+
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
386
|
+
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
387
|
+
ascii: { glyphs: ASCII }
|
|
388
|
+
};
|
|
389
|
+
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"]);
|
|
390
|
+
HEX = /^#[0-9a-f]{6}$/i;
|
|
391
|
+
CONTROL = /\p{Cc}/u;
|
|
392
|
+
MAX_FILE_BYTES = 64 * 1024;
|
|
393
|
+
SPACES = /\s+/;
|
|
394
|
+
CUBE = [0, 95, 135, 175, 215, 255];
|
|
395
|
+
warned = new Set;
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
// ../kit/src/style.ts
|
|
399
|
+
import process6 from "process";
|
|
400
|
+
function takesControlCodes(stream, env = process6.env) {
|
|
401
|
+
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
402
|
+
}
|
|
403
|
+
function paint(stream, env = process6.env) {
|
|
404
|
+
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
405
|
+
}
|
|
406
|
+
function marked(mark, text, stream, detail, env = process6.env) {
|
|
407
|
+
const colors = paint(stream, env);
|
|
408
|
+
let head = MARK_WORDS[mark];
|
|
409
|
+
if (takesControlCodes(stream, env)) {
|
|
410
|
+
const { theme } = activeTheme();
|
|
411
|
+
head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
|
|
412
|
+
}
|
|
413
|
+
return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
|
|
414
|
+
}
|
|
415
|
+
function warn(text, detail) {
|
|
416
|
+
console.error(marked("warn", text, process6.stderr, detail));
|
|
417
|
+
}
|
|
418
|
+
var MARK_WORDS, STATUS_WORDS, STATUS_OF;
|
|
419
|
+
var init_style = __esm(() => {
|
|
420
|
+
init_colors();
|
|
421
|
+
init_mode();
|
|
422
|
+
init_theme();
|
|
423
|
+
MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
|
|
424
|
+
STATUS_WORDS = {
|
|
425
|
+
passed: ["passed", "success", "succeeded", "ok"],
|
|
426
|
+
failed: ["failed", "failure", "error", "errored"],
|
|
427
|
+
running: ["running", "in_progress", "started", "holding"],
|
|
428
|
+
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
429
|
+
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
430
|
+
};
|
|
431
|
+
STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
// ../kit/src/format.ts
|
|
435
|
+
import process7 from "process";
|
|
436
|
+
function formatSeconds(total) {
|
|
437
|
+
let rest = Math.max(0, Math.round(total));
|
|
438
|
+
const amounts = UNITS.map(([unit, size]) => {
|
|
439
|
+
const amount = Math.floor(rest / size);
|
|
440
|
+
rest -= amount * size;
|
|
441
|
+
return `${amount}${unit}`;
|
|
442
|
+
});
|
|
443
|
+
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
444
|
+
if (first === -1)
|
|
445
|
+
return "0s";
|
|
446
|
+
const next = amounts[first + 1];
|
|
447
|
+
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
448
|
+
}
|
|
449
|
+
function formatDuration(ms) {
|
|
450
|
+
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
451
|
+
}
|
|
452
|
+
function formatElapsed(ms) {
|
|
453
|
+
return formatSeconds(Math.floor(Math.max(0, ms) / 1000));
|
|
454
|
+
}
|
|
455
|
+
function upTo(text, separator) {
|
|
456
|
+
const end = text.indexOf(separator);
|
|
457
|
+
return end === -1 ? text : text.slice(0, end);
|
|
458
|
+
}
|
|
459
|
+
function formatAge(date, now = Date.now()) {
|
|
460
|
+
const at = typeof date === "number" ? date : Date.parse(date);
|
|
461
|
+
if (Number.isNaN(at))
|
|
462
|
+
return "-";
|
|
463
|
+
const seconds = (now - at) / 1000;
|
|
464
|
+
return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
|
|
465
|
+
}
|
|
466
|
+
function truncate(text, width) {
|
|
467
|
+
return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
|
|
468
|
+
}
|
|
469
|
+
function textWidth(text) {
|
|
470
|
+
return Bun.stringWidth(text);
|
|
471
|
+
}
|
|
472
|
+
function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
|
|
473
|
+
const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
|
|
474
|
+
if (outputMode(stream, env) === "agent")
|
|
475
|
+
return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
|
|
476
|
+
`);
|
|
477
|
+
const widths = [];
|
|
478
|
+
for (const row of cells) {
|
|
479
|
+
for (const [index, cell] of row.entries())
|
|
480
|
+
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
481
|
+
}
|
|
482
|
+
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
483
|
+
const colors = paint(stream);
|
|
484
|
+
const lines = shown.map((row) => row.map((cell, index) => {
|
|
485
|
+
const width = widths[index] ?? 0;
|
|
486
|
+
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
487
|
+
if (align[index] === "right")
|
|
488
|
+
return `${gap}${cell}`;
|
|
489
|
+
return index === row.length - 1 ? cell : `${cell}${gap}`;
|
|
490
|
+
}).join(" ").trimEnd());
|
|
491
|
+
const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
|
|
492
|
+
return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
|
|
493
|
+
`);
|
|
494
|
+
}
|
|
495
|
+
function narrow(rows, widths, limit) {
|
|
496
|
+
const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
|
|
497
|
+
const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
|
|
498
|
+
const floor = 8;
|
|
499
|
+
while (used() > limit) {
|
|
500
|
+
let widest = -1;
|
|
501
|
+
for (const [index, width] of widths.entries()) {
|
|
502
|
+
if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
|
|
503
|
+
widest = index;
|
|
504
|
+
}
|
|
505
|
+
if (widest === -1)
|
|
506
|
+
break;
|
|
507
|
+
widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
|
|
508
|
+
}
|
|
509
|
+
return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
|
|
510
|
+
}
|
|
511
|
+
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
512
|
+
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
513
|
+
}
|
|
514
|
+
function printJson(value) {
|
|
515
|
+
console.log(jsonText(value));
|
|
516
|
+
}
|
|
517
|
+
var UNITS, LINE_BREAKS, ESCAPE;
|
|
518
|
+
var init_format = __esm(() => {
|
|
519
|
+
init_text();
|
|
520
|
+
init_mode();
|
|
521
|
+
init_style();
|
|
522
|
+
UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
523
|
+
LINE_BREAKS = /\s*\n\s*/g;
|
|
524
|
+
ESCAPE = String.fromCharCode(27);
|
|
525
|
+
});
|
|
526
|
+
|
|
527
|
+
// ../kit/src/help.ts
|
|
528
|
+
import process8 from "process";
|
|
529
|
+
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
530
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
531
|
+
`);
|
|
532
|
+
const blank = lines.indexOf("");
|
|
533
|
+
const synopses = blank === -1 ? lines : lines.slice(0, blank);
|
|
534
|
+
const details = blank === -1 ? [] : lines.slice(blank + 1);
|
|
535
|
+
const colon = synopses[0].indexOf(": ");
|
|
536
|
+
const inline = synopses[0].slice(colon + 2);
|
|
537
|
+
const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
|
|
538
|
+
if (colon !== -1)
|
|
539
|
+
synopses[0] = synopses[0].slice(0, colon);
|
|
540
|
+
const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
|
|
541
|
+
`)}`;
|
|
542
|
+
const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
|
|
543
|
+
const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
|
|
544
|
+
return [head, ...lead, ...rest].join(`
|
|
545
|
+
`);
|
|
546
|
+
}
|
|
547
|
+
function prose(line, colors) {
|
|
548
|
+
if (colors.cyan("x") === "x")
|
|
549
|
+
return line;
|
|
550
|
+
return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
|
|
551
|
+
}
|
|
552
|
+
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
553
|
+
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
554
|
+
`);
|
|
555
|
+
}
|
|
556
|
+
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
557
|
+
if (exits.length === 0)
|
|
558
|
+
return [];
|
|
559
|
+
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
560
|
+
}
|
|
561
|
+
function wantsHelpJson(env = process8.env) {
|
|
562
|
+
return env.KIT_HELP === "json";
|
|
563
|
+
}
|
|
564
|
+
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
565
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
566
|
+
`);
|
|
567
|
+
const first = lines[0];
|
|
568
|
+
const colon = first.indexOf(": ");
|
|
569
|
+
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
570
|
+
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
571
|
+
return {
|
|
572
|
+
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
573
|
+
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
574
|
+
...replaces === undefined ? {} : { replaces },
|
|
575
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
576
|
+
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
577
|
+
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
581
|
+
if (examples.length === 0 || outputMode() === "agent")
|
|
582
|
+
return [];
|
|
583
|
+
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
584
|
+
}
|
|
585
|
+
function optionRows(options, colors = paint(process8.stdout)) {
|
|
586
|
+
const rows = Object.entries(options).map(([name, option]) => {
|
|
587
|
+
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
588
|
+
const choices = option.choices?.join("|");
|
|
589
|
+
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
590
|
+
const named = inline ? `<${choices}>` : "<value>";
|
|
591
|
+
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
592
|
+
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
593
|
+
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
594
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
595
|
+
});
|
|
596
|
+
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
597
|
+
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
598
|
+
}
|
|
599
|
+
var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
|
|
600
|
+
var init_help = __esm(() => {
|
|
601
|
+
init_mode();
|
|
602
|
+
init_style();
|
|
603
|
+
OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
604
|
+
USAGE_PREFIX = /^usage:\s*/i;
|
|
605
|
+
FULL_STOP = /\.$/;
|
|
606
|
+
PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
// ../kit/src/text.ts
|
|
610
|
+
function escapeControls(text) {
|
|
611
|
+
return text.replace(CONTROLS, (char) => {
|
|
612
|
+
const code = char.charCodeAt(0);
|
|
613
|
+
if (code === 127)
|
|
614
|
+
return "^?";
|
|
615
|
+
return code < 128 ? `^${String.fromCharCode(code + 64)}` : `M-^${String.fromCharCode(code - 64)}`;
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
function distance(a, b) {
|
|
619
|
+
const left = [...a];
|
|
620
|
+
const right = [...b];
|
|
621
|
+
let before = [];
|
|
622
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
623
|
+
for (const [i, x] of left.entries()) {
|
|
624
|
+
const current = [i + 1];
|
|
625
|
+
for (const [j, y] of right.entries()) {
|
|
626
|
+
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
627
|
+
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
628
|
+
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
629
|
+
current.push(cost);
|
|
630
|
+
}
|
|
631
|
+
before = previous;
|
|
632
|
+
previous = current;
|
|
633
|
+
}
|
|
634
|
+
return previous[right.length] ?? 0;
|
|
635
|
+
}
|
|
636
|
+
function closest(name, names) {
|
|
637
|
+
const started = names.find((known) => known.startsWith(name));
|
|
638
|
+
if (started !== undefined)
|
|
639
|
+
return started;
|
|
640
|
+
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
641
|
+
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
642
|
+
}
|
|
643
|
+
var CONTROLS;
|
|
644
|
+
var init_text2 = __esm(() => {
|
|
645
|
+
CONTROLS = /[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;
|
|
646
|
+
});
|
|
647
|
+
|
|
648
|
+
// ../kit/src/input.ts
|
|
649
|
+
var init_input = __esm(() => {
|
|
650
|
+
init_args();
|
|
651
|
+
});
|
|
652
|
+
|
|
653
|
+
// ../kit/src/args.ts
|
|
654
|
+
import process9 from "process";
|
|
655
|
+
import { parseArgs } from "util";
|
|
656
|
+
function jsonOption(holds) {
|
|
657
|
+
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
658
|
+
}
|
|
659
|
+
function fail(message, code = 2, hint) {
|
|
660
|
+
throw new Exit(message, code, hint);
|
|
661
|
+
}
|
|
662
|
+
function badUsage(message) {
|
|
663
|
+
throw new UsageError(message);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
class Completing {
|
|
667
|
+
options;
|
|
668
|
+
positionals;
|
|
669
|
+
candidates;
|
|
670
|
+
constructor(options, positionals = [], candidates = {}) {
|
|
671
|
+
this.options = options;
|
|
672
|
+
this.positionals = positionals;
|
|
673
|
+
this.candidates = candidates;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
function applyOutput(color, plain, env = process9.env) {
|
|
677
|
+
const when = plain === true ? "never" : color ?? "auto";
|
|
678
|
+
if (when === "auto")
|
|
679
|
+
return;
|
|
680
|
+
if (when !== "always" && when !== "never")
|
|
681
|
+
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
682
|
+
if (when === "always") {
|
|
683
|
+
env.FORCE_COLOR = "1";
|
|
684
|
+
delete env.NO_COLOR;
|
|
685
|
+
} else {
|
|
686
|
+
env.NO_COLOR = "1";
|
|
687
|
+
delete env.FORCE_COLOR;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
function parse(args, usage, options, settings = {}) {
|
|
691
|
+
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
692
|
+
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
693
|
+
const listing = listed(all, settings.allowNegative === true);
|
|
694
|
+
if (completion.active)
|
|
695
|
+
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
696
|
+
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
697
|
+
let parsed;
|
|
698
|
+
try {
|
|
699
|
+
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
700
|
+
} catch (error) {
|
|
701
|
+
const message = parseError(error);
|
|
702
|
+
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
703
|
+
}
|
|
704
|
+
const values = parsed.values;
|
|
705
|
+
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
706
|
+
if (values.help === true) {
|
|
707
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
708
|
+
throw new HelpShown;
|
|
709
|
+
}
|
|
710
|
+
checkChoices(parsed.values, all);
|
|
711
|
+
checkConflicts(parsed.values, all);
|
|
712
|
+
if (settings.positionals !== undefined)
|
|
713
|
+
checkPositionals(parsed.positionals, settings.positionals);
|
|
714
|
+
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
715
|
+
}
|
|
716
|
+
function splitRest(args, passes) {
|
|
717
|
+
const separator = passes ? args.indexOf("--") : -1;
|
|
718
|
+
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
719
|
+
}
|
|
720
|
+
function splitTrailing(args, options, count) {
|
|
721
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
722
|
+
let seen = 0;
|
|
723
|
+
if (count === 0)
|
|
724
|
+
return { own: args, rest: undefined };
|
|
725
|
+
for (let at = 0;at < args.length; at++) {
|
|
726
|
+
const word = args[at];
|
|
727
|
+
if (word === "--")
|
|
728
|
+
break;
|
|
729
|
+
if (word.startsWith("-")) {
|
|
730
|
+
if (takesValue(word))
|
|
731
|
+
at++;
|
|
732
|
+
continue;
|
|
733
|
+
}
|
|
734
|
+
seen++;
|
|
735
|
+
if (seen === count)
|
|
736
|
+
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
737
|
+
}
|
|
738
|
+
return { own: args, rest: undefined };
|
|
739
|
+
}
|
|
740
|
+
function listed(options, allowNegative) {
|
|
741
|
+
if (!allowNegative)
|
|
742
|
+
return options;
|
|
743
|
+
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
744
|
+
if (option.type !== "boolean" || option.negative === undefined)
|
|
745
|
+
return [[name, option]];
|
|
746
|
+
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
747
|
+
}));
|
|
748
|
+
}
|
|
749
|
+
function withAliases(args, options) {
|
|
750
|
+
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
751
|
+
if (named.size === 0)
|
|
752
|
+
return args;
|
|
753
|
+
const separator = args.indexOf("--");
|
|
754
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
755
|
+
return [...own.map((arg) => {
|
|
756
|
+
const at = arg.indexOf("=");
|
|
757
|
+
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
758
|
+
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
759
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
760
|
+
}
|
|
761
|
+
function withBare(args, options) {
|
|
762
|
+
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
763
|
+
if (bare.size === 0)
|
|
764
|
+
return args;
|
|
765
|
+
const separator = args.indexOf("--");
|
|
766
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
767
|
+
return [...own.flatMap((arg, index) => {
|
|
768
|
+
const optional = bare.get(arg);
|
|
769
|
+
const next = own[index + 1];
|
|
770
|
+
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
771
|
+
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
772
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
773
|
+
}
|
|
774
|
+
function checkConflicts(values, options) {
|
|
775
|
+
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
776
|
+
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
777
|
+
const other = given(name) ? conflicts.find(given) : undefined;
|
|
778
|
+
if (other !== undefined)
|
|
779
|
+
badUsage(`--${name} cannot be used with --${other}`);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
function checkChoices(values, options) {
|
|
783
|
+
for (const [name, option] of Object.entries(options)) {
|
|
784
|
+
if (option.choices === undefined)
|
|
785
|
+
continue;
|
|
786
|
+
const given = values[name];
|
|
787
|
+
for (const value of Array.isArray(given) ? given : [given]) {
|
|
788
|
+
if (typeof value === "string")
|
|
789
|
+
oneOf(value, name, option.choices);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
function oneOf(value, name, choices) {
|
|
794
|
+
if (!choices.includes(value))
|
|
795
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
796
|
+
return value;
|
|
797
|
+
}
|
|
798
|
+
function checkPositionals(given, names) {
|
|
799
|
+
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
800
|
+
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
801
|
+
if (given.length < required)
|
|
802
|
+
badUsage(`missing ${names[given.length]}`);
|
|
803
|
+
if (!variadic && given.length > names.length)
|
|
804
|
+
badUsage(`unexpected argument ${given[names.length]}`);
|
|
805
|
+
}
|
|
806
|
+
function joinDashValues(args, options) {
|
|
807
|
+
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
808
|
+
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
809
|
+
const joined = [];
|
|
810
|
+
for (let i = 0;i < args.length; i++) {
|
|
811
|
+
const arg = args[i] ?? "";
|
|
812
|
+
if (arg === "--")
|
|
813
|
+
return [...joined, ...args.slice(i)];
|
|
814
|
+
const name = longOf.get(arg);
|
|
815
|
+
const next = args[i + 1];
|
|
816
|
+
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
817
|
+
joined.push(`--${name}=${next}`);
|
|
818
|
+
i++;
|
|
819
|
+
} else {
|
|
820
|
+
joined.push(arg);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
return joined;
|
|
824
|
+
}
|
|
825
|
+
function parseError(error) {
|
|
826
|
+
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
827
|
+
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
828
|
+
}
|
|
829
|
+
function nearestOption(message, options, allowNegative) {
|
|
830
|
+
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
831
|
+
if (typed === undefined)
|
|
832
|
+
return;
|
|
833
|
+
const word = typed.replace(DASHES, "");
|
|
834
|
+
if (word.length < 2 && !typed.startsWith("--"))
|
|
835
|
+
return;
|
|
836
|
+
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
837
|
+
...option.short === undefined ? [] : [`-${option.short}`],
|
|
838
|
+
`--${name}`,
|
|
839
|
+
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
840
|
+
]);
|
|
841
|
+
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
842
|
+
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
843
|
+
}
|
|
844
|
+
var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
|
|
845
|
+
var init_args = __esm(() => {
|
|
846
|
+
init_format();
|
|
847
|
+
init_help();
|
|
848
|
+
init_text2();
|
|
849
|
+
init_help();
|
|
850
|
+
init_input();
|
|
851
|
+
DASHES = /^-+/;
|
|
852
|
+
EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
|
|
853
|
+
Exit = class Exit extends Error {
|
|
854
|
+
code;
|
|
855
|
+
hint;
|
|
856
|
+
[EXIT] = true;
|
|
857
|
+
constructor(message, code, hint) {
|
|
858
|
+
super(message);
|
|
859
|
+
this.code = code;
|
|
860
|
+
this.hint = hint;
|
|
861
|
+
}
|
|
862
|
+
static [Symbol.hasInstance](value) {
|
|
863
|
+
if (this !== Exit)
|
|
864
|
+
return Function.prototype[Symbol.hasInstance].call(this, value);
|
|
865
|
+
return typeof value === "object" && value !== null && value[EXIT] === true;
|
|
866
|
+
}
|
|
867
|
+
};
|
|
868
|
+
UsageError = class UsageError extends Exit {
|
|
869
|
+
constructor(message, hint) {
|
|
870
|
+
super(message, 2, hint);
|
|
871
|
+
}
|
|
872
|
+
};
|
|
873
|
+
HelpShown = class HelpShown extends Exit {
|
|
874
|
+
constructor() {
|
|
875
|
+
super("help shown", 0);
|
|
876
|
+
}
|
|
877
|
+
};
|
|
878
|
+
completion = { active: false };
|
|
879
|
+
OUTPUT_OPTIONS = {
|
|
880
|
+
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
881
|
+
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
882
|
+
};
|
|
883
|
+
UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
884
|
+
});
|
|
885
|
+
|
|
886
|
+
// ../kit/src/argv.ts
|
|
887
|
+
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
888
|
+
import { resolve as resolve3 } from "path";
|
|
889
|
+
import process10 from "process";
|
|
890
|
+
function commandLine() {
|
|
891
|
+
try {
|
|
892
|
+
return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
893
|
+
} catch {
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
function realPath(word) {
|
|
898
|
+
try {
|
|
899
|
+
return realpathSync(resolve3(word));
|
|
900
|
+
} catch {
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
905
|
+
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
906
|
+
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
907
|
+
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
908
|
+
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
909
|
+
}
|
|
910
|
+
var init_argv = () => {};
|
|
911
|
+
|
|
912
|
+
// ../kit/src/chart.ts
|
|
913
|
+
var init_chart = __esm(() => {
|
|
914
|
+
init_format();
|
|
915
|
+
init_mode();
|
|
916
|
+
init_style();
|
|
917
|
+
init_theme();
|
|
918
|
+
});
|
|
919
|
+
|
|
920
|
+
// ../kit/src/process.ts
|
|
921
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
922
|
+
import { constants } from "os";
|
|
923
|
+
import process11 from "process";
|
|
924
|
+
function exitCodeOf(code, signal) {
|
|
925
|
+
if (code !== null)
|
|
926
|
+
return code;
|
|
927
|
+
if (typeof signal === "number")
|
|
928
|
+
return 128 + signal;
|
|
929
|
+
return signal === null ? 129 : 128 + constants.signals[signal];
|
|
930
|
+
}
|
|
931
|
+
function groupsOf(pid) {
|
|
932
|
+
try {
|
|
933
|
+
const stat = readFileSync3(`/proc/${pid}/stat`, "utf8");
|
|
934
|
+
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
935
|
+
return { group: Number(fields[2]), foreground: Number(fields[5]) };
|
|
936
|
+
} catch {
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
function heardTheTerminal(child) {
|
|
941
|
+
if (child.pid === undefined)
|
|
942
|
+
return false;
|
|
943
|
+
const own = groupsOf("self");
|
|
944
|
+
return own !== undefined && own.group === own.foreground && groupsOf(child.pid)?.group === own.group;
|
|
945
|
+
}
|
|
946
|
+
function holdSignals(cleanup) {
|
|
947
|
+
let received;
|
|
948
|
+
let child;
|
|
949
|
+
const held = {
|
|
950
|
+
get signal() {
|
|
951
|
+
return received;
|
|
952
|
+
},
|
|
953
|
+
forward: (to) => {
|
|
954
|
+
child = to;
|
|
955
|
+
},
|
|
956
|
+
release: () => {
|
|
957
|
+
for (const signal of SIGNALS)
|
|
958
|
+
process11.off(signal, onSignal);
|
|
959
|
+
}
|
|
960
|
+
};
|
|
961
|
+
function onSignal(signal) {
|
|
962
|
+
received = signal;
|
|
963
|
+
if (child !== undefined) {
|
|
964
|
+
if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
|
|
965
|
+
child.kill(signal);
|
|
966
|
+
return;
|
|
967
|
+
}
|
|
968
|
+
if (cleanup === undefined)
|
|
969
|
+
return;
|
|
970
|
+
held.release();
|
|
971
|
+
cleanup(signal);
|
|
972
|
+
process11.kill(process11.pid, signal);
|
|
973
|
+
}
|
|
974
|
+
for (const signal of SIGNALS)
|
|
975
|
+
process11.on(signal, onSignal);
|
|
976
|
+
return held;
|
|
977
|
+
}
|
|
978
|
+
async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
979
|
+
const chunks = [];
|
|
980
|
+
const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
|
|
981
|
+
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 } : {} });
|
|
982
|
+
const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
|
|
983
|
+
const timers = [];
|
|
984
|
+
const killGroup = (killing) => {
|
|
985
|
+
if (state.done)
|
|
986
|
+
return;
|
|
987
|
+
try {
|
|
988
|
+
if (grouped)
|
|
989
|
+
process11.kill(-proc.pid, killing);
|
|
990
|
+
else
|
|
991
|
+
proc.kill(killing);
|
|
992
|
+
} catch {}
|
|
993
|
+
};
|
|
994
|
+
const stop = () => {
|
|
995
|
+
killGroup("SIGTERM");
|
|
996
|
+
timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
|
|
997
|
+
};
|
|
998
|
+
const onAbort = () => stop();
|
|
999
|
+
if (timeoutMs !== undefined) {
|
|
1000
|
+
timers.push(setTimeout(() => {
|
|
1001
|
+
state.timedOut = true;
|
|
1002
|
+
stop();
|
|
1003
|
+
}, timeoutMs));
|
|
1004
|
+
}
|
|
1005
|
+
if (signal?.aborted === true)
|
|
1006
|
+
onAbort();
|
|
1007
|
+
else
|
|
1008
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1009
|
+
onStart?.({ kill: (killing) => killGroup(killing) });
|
|
1010
|
+
const drain = async (stream, name) => {
|
|
1011
|
+
for await (const data of stream) {
|
|
1012
|
+
if (state.failure !== undefined)
|
|
1013
|
+
continue;
|
|
1014
|
+
try {
|
|
1015
|
+
onChunk?.({ stream: name, data });
|
|
1016
|
+
} catch (error) {
|
|
1017
|
+
state.failure = error;
|
|
1018
|
+
stop();
|
|
1019
|
+
continue;
|
|
1020
|
+
}
|
|
1021
|
+
if (state.truncated)
|
|
1022
|
+
continue;
|
|
1023
|
+
let kept = data;
|
|
1024
|
+
if (state.kept + data.length > maxBytes) {
|
|
1025
|
+
let cut = maxBytes - state.kept;
|
|
1026
|
+
while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
|
|
1027
|
+
cut--;
|
|
1028
|
+
kept = data.subarray(0, cut);
|
|
1029
|
+
state.truncated = true;
|
|
1030
|
+
}
|
|
1031
|
+
state.kept += kept.length;
|
|
1032
|
+
if (kept.length > 0)
|
|
1033
|
+
chunks.push({ stream: name, data: kept });
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
try {
|
|
1037
|
+
await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
|
|
1038
|
+
await proc.exited;
|
|
1039
|
+
} finally {
|
|
1040
|
+
state.done = true;
|
|
1041
|
+
for (const timer of timers)
|
|
1042
|
+
clearTimeout(timer);
|
|
1043
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1044
|
+
}
|
|
1045
|
+
if (state.failure !== undefined)
|
|
1046
|
+
throw state.failure;
|
|
1047
|
+
const joined = () => Buffer.concat(chunks.map(({ data }) => data));
|
|
1048
|
+
let output;
|
|
1049
|
+
let text;
|
|
1050
|
+
let stdout;
|
|
1051
|
+
return {
|
|
1052
|
+
code: exitCodeOf(proc.exitCode, proc.signalCode),
|
|
1053
|
+
chunks,
|
|
1054
|
+
timedOut: state.timedOut,
|
|
1055
|
+
truncated: state.truncated,
|
|
1056
|
+
get output() {
|
|
1057
|
+
return output ??= joined();
|
|
1058
|
+
},
|
|
1059
|
+
get text() {
|
|
1060
|
+
return text ??= (output ??= joined()).toString();
|
|
1061
|
+
},
|
|
1062
|
+
get stdout() {
|
|
1063
|
+
return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
|
|
1064
|
+
}
|
|
1065
|
+
};
|
|
1066
|
+
}
|
|
1067
|
+
var KILL_GRACE_MS = 2000, SIGNALS, GROUP_SIGNALS;
|
|
1068
|
+
var init_process = __esm(() => {
|
|
1069
|
+
SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
1070
|
+
GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
|
|
1071
|
+
});
|
|
1072
|
+
|
|
1073
|
+
// ../kit/src/progress.ts
|
|
1074
|
+
import process12 from "process";
|
|
1075
|
+
function liveRegion(render, stream = process12.stderr, env = process12.env) {
|
|
1076
|
+
if (!takesControlCodes(stream, env))
|
|
1077
|
+
return { redraw: () => {
|
|
1078
|
+
return;
|
|
1079
|
+
}, print: (text) => void stream.write(`${text}
|
|
1080
|
+
`), stop: () => {
|
|
1081
|
+
return;
|
|
1082
|
+
}, pause: () => () => {
|
|
1083
|
+
return;
|
|
1084
|
+
} };
|
|
1085
|
+
const write = stream.write.bind(stream);
|
|
1086
|
+
let frame = 0;
|
|
1087
|
+
let drawn = false;
|
|
1088
|
+
let paused = false;
|
|
1089
|
+
let stopped = false;
|
|
1090
|
+
const columns = () => {
|
|
1091
|
+
const now = stream.getWindowSize?.()[0] ?? stream.columns;
|
|
1092
|
+
return now === undefined || now === 0 ? 80 : now;
|
|
1093
|
+
};
|
|
1094
|
+
const clear = () => {
|
|
1095
|
+
if (drawn)
|
|
1096
|
+
write(CLEAR_BELOW);
|
|
1097
|
+
drawn = false;
|
|
1098
|
+
};
|
|
1099
|
+
const draw = () => {
|
|
1100
|
+
if (paused)
|
|
1101
|
+
return;
|
|
1102
|
+
const width = columns() - 1;
|
|
1103
|
+
const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
|
|
1104
|
+
const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
|
|
1105
|
+
if (lines.length === 0) {
|
|
1106
|
+
clear();
|
|
1107
|
+
return;
|
|
1108
|
+
}
|
|
1109
|
+
write(`${CLEAR_BELOW}${lines.join(`
|
|
1110
|
+
`)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
|
|
1111
|
+
drawn = true;
|
|
1112
|
+
};
|
|
1113
|
+
let timer = setInterval(draw, FRAME_MS);
|
|
1114
|
+
stream.on?.("resize", draw);
|
|
1115
|
+
let restore = interceptOutput(clear);
|
|
1116
|
+
let release = swallowInput();
|
|
1117
|
+
const onExit = () => {
|
|
1118
|
+
clear();
|
|
1119
|
+
release();
|
|
1120
|
+
};
|
|
1121
|
+
const signals = holdSignals(stop);
|
|
1122
|
+
function stop() {
|
|
1123
|
+
stopped = true;
|
|
1124
|
+
clearInterval(timer);
|
|
1125
|
+
stream.off?.("resize", draw);
|
|
1126
|
+
clear();
|
|
1127
|
+
restore();
|
|
1128
|
+
release();
|
|
1129
|
+
process12.off("exit", onExit);
|
|
1130
|
+
signals.release();
|
|
1131
|
+
}
|
|
1132
|
+
function pause() {
|
|
1133
|
+
if (paused || stopped)
|
|
1134
|
+
return () => {
|
|
1135
|
+
return;
|
|
1136
|
+
};
|
|
1137
|
+
paused = true;
|
|
1138
|
+
clearInterval(timer);
|
|
1139
|
+
stream.off?.("resize", draw);
|
|
1140
|
+
clear();
|
|
1141
|
+
restore();
|
|
1142
|
+
release();
|
|
1143
|
+
return () => {
|
|
1144
|
+
if (!paused || stopped)
|
|
1145
|
+
return;
|
|
1146
|
+
paused = false;
|
|
1147
|
+
timer = setInterval(draw, FRAME_MS);
|
|
1148
|
+
timer.unref();
|
|
1149
|
+
stream.on?.("resize", draw);
|
|
1150
|
+
restore = interceptOutput(clear);
|
|
1151
|
+
release = swallowInput();
|
|
1152
|
+
draw();
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
timer.unref();
|
|
1156
|
+
process12.on("exit", onExit);
|
|
1157
|
+
return {
|
|
1158
|
+
redraw: draw,
|
|
1159
|
+
print: (text) => {
|
|
1160
|
+
clear();
|
|
1161
|
+
write(`${text}
|
|
1162
|
+
`);
|
|
1163
|
+
draw();
|
|
1164
|
+
},
|
|
1165
|
+
stop,
|
|
1166
|
+
pause
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
function progressLine(stream = process12.stderr, env = process12.env) {
|
|
1170
|
+
const colors = paint(stream, env);
|
|
1171
|
+
const write = stream.write.bind(stream);
|
|
1172
|
+
const begun = performance.now();
|
|
1173
|
+
let started = begun;
|
|
1174
|
+
let current;
|
|
1175
|
+
const region = liveRegion((spinner) => current === undefined ? [] : [tintedParts(progressParts(current, spinner, performance.now() - started), colors)], stream, env);
|
|
1176
|
+
const end = (line) => {
|
|
1177
|
+
region.stop();
|
|
1178
|
+
write(`${line}
|
|
1179
|
+
`);
|
|
1180
|
+
};
|
|
1181
|
+
return {
|
|
1182
|
+
update: (progress) => {
|
|
1183
|
+
const step = current?.step;
|
|
1184
|
+
current = progress;
|
|
1185
|
+
if (progress.step !== step) {
|
|
1186
|
+
started = performance.now();
|
|
1187
|
+
region.redraw();
|
|
1188
|
+
}
|
|
1189
|
+
},
|
|
1190
|
+
stop: region.stop,
|
|
1191
|
+
pause: region.pause,
|
|
1192
|
+
done: (text) => end(marked("ok", text, stream, formatDuration(performance.now() - begun), env)),
|
|
1193
|
+
failed: (text) => end(marked("problem", text, stream, undefined, env))
|
|
1194
|
+
};
|
|
1195
|
+
}
|
|
1196
|
+
function progressParts({ step, done, total, unit }, spinner, ms) {
|
|
1197
|
+
const { theme } = activeTheme();
|
|
1198
|
+
const parts = [{ text: spinner, tint: (colors) => tinted(colors, theme.colors.accent) }, { text: ` ${step}`, tint: () => plain }];
|
|
1199
|
+
if (total !== undefined && total > 0) {
|
|
1200
|
+
const counted = Math.min(done ?? 0, total);
|
|
1201
|
+
const filled = Math.round(counted / total * BAR_WIDTH);
|
|
1202
|
+
parts.push({ text: " ", tint: () => plain }, { text: theme.glyphs.bar.repeat(filled), tint: (colors) => () => shaded(theme, colors, theme.glyphs.bar, filled, BAR_WIDTH) }, { text: theme.glyphs.bar.repeat(BAR_WIDTH - filled), tint: (colors) => colors.dim }, { text: ` ${counted}/${total}${unit === undefined ? "" : ` ${unit}`}`, tint: (colors) => colors.dim });
|
|
1203
|
+
}
|
|
1204
|
+
parts.push({ text: ` ${formatElapsed(ms)}`, tint: (colors) => colors.dim });
|
|
1205
|
+
return parts;
|
|
1206
|
+
}
|
|
1207
|
+
function plain(text) {
|
|
1208
|
+
return text;
|
|
1209
|
+
}
|
|
1210
|
+
function tintedParts(parts, colors) {
|
|
1211
|
+
return parts.map(({ text, tint }) => tint(colors)(text)).join("");
|
|
1212
|
+
}
|
|
1213
|
+
function cutToWidth(line, width) {
|
|
1214
|
+
if (Bun.stringWidth(line) <= width)
|
|
1215
|
+
return line;
|
|
1216
|
+
let room = width;
|
|
1217
|
+
let kept = "";
|
|
1218
|
+
let index = 0;
|
|
1219
|
+
let linked = false;
|
|
1220
|
+
while (index < line.length) {
|
|
1221
|
+
ESCAPE_CODE.lastIndex = index;
|
|
1222
|
+
const escape = ESCAPE_CODE.exec(line);
|
|
1223
|
+
if (escape !== null) {
|
|
1224
|
+
kept += escape[0];
|
|
1225
|
+
linked ||= escape[0].startsWith(`${ESC}]`);
|
|
1226
|
+
index = ESCAPE_CODE.lastIndex;
|
|
1227
|
+
continue;
|
|
1228
|
+
}
|
|
1229
|
+
const char = String.fromCodePoint(line.codePointAt(index));
|
|
1230
|
+
const columns = Bun.stringWidth(char);
|
|
1231
|
+
if (columns > room)
|
|
1232
|
+
break;
|
|
1233
|
+
kept += char;
|
|
1234
|
+
room -= columns;
|
|
1235
|
+
index += char.length;
|
|
1236
|
+
}
|
|
1237
|
+
return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
|
|
1238
|
+
}
|
|
1239
|
+
function swallowInput() {
|
|
1240
|
+
const input = process12.stdin;
|
|
1241
|
+
if (!input.isTTY)
|
|
1242
|
+
return () => {
|
|
1243
|
+
return;
|
|
1244
|
+
};
|
|
1245
|
+
const onData = (data) => {
|
|
1246
|
+
if (data.includes(CTRL_C))
|
|
1247
|
+
process12.kill(process12.pid, "SIGINT");
|
|
1248
|
+
};
|
|
1249
|
+
input.setRawMode(true);
|
|
1250
|
+
input.on("data", onData);
|
|
1251
|
+
input.resume();
|
|
1252
|
+
let released = false;
|
|
1253
|
+
return () => {
|
|
1254
|
+
if (released)
|
|
1255
|
+
return;
|
|
1256
|
+
released = true;
|
|
1257
|
+
input.off("data", onData);
|
|
1258
|
+
input.pause();
|
|
1259
|
+
input.setRawMode(false);
|
|
1260
|
+
};
|
|
1261
|
+
}
|
|
1262
|
+
function interceptOutput(clear) {
|
|
1263
|
+
const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
|
|
1264
|
+
const wrapped = targets.map(([target, name]) => {
|
|
1265
|
+
const original = Reflect.get(target, name);
|
|
1266
|
+
const wrapper = (...args) => {
|
|
1267
|
+
clear();
|
|
1268
|
+
return original.apply(target, args);
|
|
1269
|
+
};
|
|
1270
|
+
Reflect.set(target, name, wrapper);
|
|
1271
|
+
return { target, name, original, wrapper };
|
|
1272
|
+
});
|
|
1273
|
+
return () => {
|
|
1274
|
+
for (const { target, name, original, wrapper } of wrapped) {
|
|
1275
|
+
if (Reflect.get(target, name) === wrapper)
|
|
1276
|
+
Reflect.set(target, name, original);
|
|
1277
|
+
}
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
var FRAMES, FRAME_MS = 200, BAR_WIDTH = 20, CLEAR_BELOW = "\r\x1B[J", ESC, ESCAPE_CODE, RESET_STYLE, CTRL_C = 3, CLOSE_LINK, CONSOLE_METHODS;
|
|
1281
|
+
var init_progress = __esm(() => {
|
|
1282
|
+
init_format();
|
|
1283
|
+
init_process();
|
|
1284
|
+
init_style();
|
|
1285
|
+
init_theme();
|
|
1286
|
+
FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
1287
|
+
ESC = String.fromCharCode(27);
|
|
1288
|
+
ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
1289
|
+
RESET_STYLE = `${ESC}[0m`;
|
|
1290
|
+
CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
1291
|
+
CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
|
|
1292
|
+
});
|
|
1293
|
+
|
|
1294
|
+
// ../kit/src/tool.ts
|
|
1295
|
+
import process13 from "process";
|
|
1296
|
+
function cwdGone() {
|
|
1297
|
+
try {
|
|
1298
|
+
process13.cwd();
|
|
1299
|
+
return false;
|
|
1300
|
+
} catch {
|
|
1301
|
+
return true;
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
function spawnFailure(command, error) {
|
|
1305
|
+
const gone = cwdGone();
|
|
1306
|
+
const missing = !gone && error?.code === "ENOENT";
|
|
1307
|
+
return new SpawnError(`${command}: ${error instanceof Error ? error.message : String(error)}${gone ? " (the working directory was removed)" : ""}`, missing);
|
|
1308
|
+
}
|
|
1309
|
+
async function runTool(label, argv, { timeoutMs, cwd, onStart, env } = {}) {
|
|
1310
|
+
let ran;
|
|
1311
|
+
try {
|
|
1312
|
+
ran = await runCommand(argv, { env: { ...process13.env, ...env }, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
|
|
1313
|
+
} catch (error) {
|
|
1314
|
+
throw spawnFailure(label, error);
|
|
1315
|
+
}
|
|
1316
|
+
if (ran.timedOut)
|
|
1317
|
+
throw new Error(`${label}: no answer in ${formatDuration(timeoutMs ?? 0)}`);
|
|
1318
|
+
const decoders = { stdout: new TextDecoder, stderr: new TextDecoder };
|
|
1319
|
+
const streams = { stdout: "", stderr: "" };
|
|
1320
|
+
for (const { stream, data } of ran.chunks)
|
|
1321
|
+
streams[stream] += decoders[stream].decode(data, { stream: true });
|
|
1322
|
+
streams.stdout += decoders.stdout.decode();
|
|
1323
|
+
streams.stderr += decoders.stderr.decode();
|
|
1324
|
+
return { code: ran.code, ...streams };
|
|
1325
|
+
}
|
|
1326
|
+
var SpawnError;
|
|
1327
|
+
var init_tool = __esm(() => {
|
|
1328
|
+
init_format();
|
|
1329
|
+
init_process();
|
|
1330
|
+
SpawnError = class SpawnError extends Error {
|
|
1331
|
+
missing;
|
|
1332
|
+
constructor(message, missing) {
|
|
1333
|
+
super(message);
|
|
1334
|
+
this.missing = missing;
|
|
1335
|
+
}
|
|
1336
|
+
};
|
|
1337
|
+
});
|
|
1338
|
+
|
|
1339
|
+
// ../kit/src/ci.ts
|
|
1340
|
+
var init_ci = __esm(() => {
|
|
1341
|
+
init_args();
|
|
1342
|
+
init_format();
|
|
1343
|
+
init_progress();
|
|
1344
|
+
init_style();
|
|
1345
|
+
init_tool();
|
|
1346
|
+
});
|
|
1347
|
+
|
|
1348
|
+
// ../kit/src/askpass.ts
|
|
1349
|
+
import process14 from "process";
|
|
1350
|
+
async function askpassClient(argv) {
|
|
1351
|
+
const socketPath = process14.env[SOCKET_VARIABLE];
|
|
1352
|
+
if (socketPath === undefined)
|
|
1353
|
+
return;
|
|
1354
|
+
const request = { prompt: argv[0] ?? "", ...process14.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
|
|
1355
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
1356
|
+
let received = "";
|
|
1357
|
+
try {
|
|
1358
|
+
await Bun.connect({
|
|
1359
|
+
unix: socketPath,
|
|
1360
|
+
socket: {
|
|
1361
|
+
open: (socket) => void socket.write(`${JSON.stringify(request)}
|
|
1362
|
+
`),
|
|
1363
|
+
data: (_, chunk) => {
|
|
1364
|
+
received += chunk.toString();
|
|
1365
|
+
},
|
|
1366
|
+
close: () => resolve(received),
|
|
1367
|
+
error: () => resolve("")
|
|
1368
|
+
}
|
|
1369
|
+
});
|
|
1370
|
+
} catch {
|
|
1371
|
+
return 1;
|
|
1372
|
+
}
|
|
1373
|
+
const reply = await promise;
|
|
1374
|
+
if (reply === "")
|
|
1375
|
+
return 1;
|
|
1376
|
+
const { answer } = JSON.parse(reply);
|
|
1377
|
+
if (request.notice === true)
|
|
1378
|
+
return 0;
|
|
1379
|
+
if (answer === undefined)
|
|
1380
|
+
return 1;
|
|
1381
|
+
process14.stdout.write(`${answer}
|
|
1382
|
+
`);
|
|
1383
|
+
return 0;
|
|
1384
|
+
}
|
|
1385
|
+
var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
|
|
1386
|
+
var init_askpass = () => {};
|
|
1387
|
+
|
|
1388
|
+
// ../kit/src/completions.ts
|
|
1389
|
+
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
1390
|
+
if (shell === "fish")
|
|
1391
|
+
return `${header}
|
|
1392
|
+
${FISH_FUNCTION}
|
|
1393
|
+
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
1394
|
+
`).join("")}`;
|
|
1395
|
+
if (shell === "bash")
|
|
1396
|
+
return `${header}
|
|
1397
|
+
${BASH_FUNCTION}
|
|
1398
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
1399
|
+
`;
|
|
1400
|
+
return `${header}
|
|
1401
|
+
${ZSH_FUNCTION}
|
|
1402
|
+
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
1403
|
+
`;
|
|
1404
|
+
}
|
|
1405
|
+
var COMPLETION_SHELLS, 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'
|
|
1406
|
+
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
1407
|
+
set -l current (commandline -ct)
|
|
1408
|
+
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
1409
|
+
if test "$line" = __files__
|
|
1410
|
+
__fish_complete_path $current
|
|
1411
|
+
else
|
|
1412
|
+
echo $line
|
|
1413
|
+
end
|
|
1414
|
+
end
|
|
1415
|
+
end`, BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1416
|
+
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
1417
|
+
local -a lines
|
|
1418
|
+
COMPREPLY=()
|
|
1419
|
+
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
1420
|
+
for line in "\${lines[@]}"; do
|
|
1421
|
+
if [[ $line == __files__ ]]; then
|
|
1422
|
+
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
1423
|
+
else
|
|
1424
|
+
words+="\${line%%$'\\t'*}"$'\\n'
|
|
1425
|
+
fi
|
|
1426
|
+
done
|
|
1427
|
+
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
1428
|
+
}`, ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1429
|
+
local line
|
|
1430
|
+
local -a described plain
|
|
1431
|
+
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
1432
|
+
if [[ $line == __files__ ]]; then
|
|
1433
|
+
_files
|
|
1434
|
+
elif [[ $line == *$'\\t'* ]]; then
|
|
1435
|
+
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
1436
|
+
else
|
|
1437
|
+
plain+=("$line")
|
|
1438
|
+
fi
|
|
1439
|
+
done
|
|
1440
|
+
(( \${#described} )) && _describe -V value described
|
|
1441
|
+
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
1442
|
+
return 0
|
|
1443
|
+
}`;
|
|
1444
|
+
var init_completions = __esm(() => {
|
|
1445
|
+
COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
1446
|
+
});
|
|
1447
|
+
|
|
1448
|
+
// ../kit/src/notify.ts
|
|
1449
|
+
import process15 from "process";
|
|
1450
|
+
function base64(text) {
|
|
1451
|
+
return Buffer.from(text).toString("base64");
|
|
1452
|
+
}
|
|
1453
|
+
function notification(title, body, env = process15.env) {
|
|
1454
|
+
const id = `kit${process15.pid}`;
|
|
1455
|
+
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\\`];
|
|
1456
|
+
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
1457
|
+
}
|
|
1458
|
+
function notifyEnd(command, code, ms, { stream = process15.stderr, env = process15.env } = {}) {
|
|
1459
|
+
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
1460
|
+
return;
|
|
1461
|
+
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
1462
|
+
}
|
|
1463
|
+
var NOTIFY_AFTER_MS = 1e4, CANCELLED = 130;
|
|
1464
|
+
var init_notify = __esm(() => {
|
|
1465
|
+
init_format();
|
|
1466
|
+
init_mode();
|
|
1467
|
+
});
|
|
1468
|
+
|
|
1469
|
+
// ../kit/src/logs.ts
|
|
1470
|
+
var DAY_MS, CLI_FOLDER = "kaynooo-cli";
|
|
1471
|
+
var init_logs = __esm(() => {
|
|
1472
|
+
init_user_config();
|
|
1473
|
+
DAY_MS = 24 * 60 * 60 * 1000;
|
|
1474
|
+
});
|
|
1475
|
+
|
|
1476
|
+
// ../kit/src/usage.ts
|
|
1477
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
1478
|
+
import { homedir as homedir3 } from "os";
|
|
1479
|
+
import { dirname as dirname2, join as join4 } from "path";
|
|
1480
|
+
import process16 from "process";
|
|
1481
|
+
function noteUsageError(message) {
|
|
1482
|
+
usageError = message;
|
|
1483
|
+
}
|
|
1484
|
+
function stateHome(env = process16.env) {
|
|
1485
|
+
return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
|
|
1486
|
+
}
|
|
1487
|
+
function usagePath(env = process16.env) {
|
|
1488
|
+
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1489
|
+
}
|
|
1490
|
+
function usageRecorded(env = process16.env) {
|
|
1491
|
+
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1492
|
+
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1493
|
+
}
|
|
1494
|
+
function flagNames(argv) {
|
|
1495
|
+
const end = argv.indexOf("--");
|
|
1496
|
+
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
1497
|
+
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
1498
|
+
}
|
|
1499
|
+
function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
|
|
1500
|
+
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
1501
|
+
usageError = undefined;
|
|
1502
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
|
|
1503
|
+
}
|
|
1504
|
+
function recordUsage(entry, env = process16.env) {
|
|
1505
|
+
if (!usageRecorded(env))
|
|
1506
|
+
return;
|
|
1507
|
+
try {
|
|
1508
|
+
const path = usagePath(env);
|
|
1509
|
+
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
1510
|
+
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1511
|
+
`, { mode: 384 });
|
|
1512
|
+
} catch {}
|
|
1513
|
+
}
|
|
1514
|
+
var UNKNOWN_OPTION2, FLAG_NAME, LONGEST_NAME = 40, usageError;
|
|
1515
|
+
var init_usage = __esm(() => {
|
|
1516
|
+
init_logs();
|
|
1517
|
+
init_user_config();
|
|
1518
|
+
UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
1519
|
+
FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
1520
|
+
});
|
|
1521
|
+
|
|
1522
|
+
// ../kit/src/cli.ts
|
|
1523
|
+
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
1524
|
+
import { dirname as dirname3, join as join5 } from "path";
|
|
1525
|
+
import process17 from "process";
|
|
1526
|
+
async function commandRows(all, colors) {
|
|
1527
|
+
const commands = shown(all);
|
|
1528
|
+
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
1529
|
+
const groups = new Map([["Commands:", []]]);
|
|
1530
|
+
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
1531
|
+
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
1532
|
+
const heading = group === undefined ? "Commands:" : `${group}:`;
|
|
1533
|
+
const rows = groups.get(heading) ?? [];
|
|
1534
|
+
rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
|
|
1535
|
+
groups.set(heading, rows);
|
|
1536
|
+
}
|
|
1537
|
+
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
1538
|
+
}
|
|
1539
|
+
function shown(commands) {
|
|
1540
|
+
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
1541
|
+
}
|
|
1542
|
+
function takeOutputFlags(argv) {
|
|
1543
|
+
let index = 0;
|
|
1544
|
+
for (;index < argv.length; index++) {
|
|
1545
|
+
const word = argv[index];
|
|
1546
|
+
if (word === "--plain")
|
|
1547
|
+
applyOutput(undefined, true);
|
|
1548
|
+
else if (word.startsWith("--color="))
|
|
1549
|
+
applyOutput(word.slice("--color=".length), undefined);
|
|
1550
|
+
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
1551
|
+
applyOutput(argv[++index], undefined);
|
|
1552
|
+
else
|
|
1553
|
+
break;
|
|
1554
|
+
}
|
|
1555
|
+
return argv.slice(index);
|
|
1556
|
+
}
|
|
1557
|
+
async function resolveSummary(summary) {
|
|
1558
|
+
return typeof summary === "string" ? summary : summary();
|
|
1559
|
+
}
|
|
1560
|
+
function lookup({ commands, aliases }, word) {
|
|
1561
|
+
const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
|
|
1562
|
+
return Object.hasOwn(commands, name) ? commands[name] : undefined;
|
|
1563
|
+
}
|
|
1564
|
+
function scopeOf(commands, extra, aliases) {
|
|
1565
|
+
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
1566
|
+
}
|
|
1567
|
+
async function expand(scope, words) {
|
|
1568
|
+
if (scope.lazy.length === 0)
|
|
1569
|
+
return scope;
|
|
1570
|
+
const commands = { ...scope.commands };
|
|
1571
|
+
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
1572
|
+
for (const [name, command] of Object.entries(added))
|
|
1573
|
+
commands[name] ??= command;
|
|
1574
|
+
}
|
|
1575
|
+
return { ...scope, commands, lazy: [] };
|
|
1576
|
+
}
|
|
1577
|
+
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
1578
|
+
const colors = paint(stream);
|
|
1579
|
+
const prefix = path.join(" ");
|
|
1580
|
+
const summary = await resolveSummary(lazySummary);
|
|
1581
|
+
if (wantsHelpJson())
|
|
1582
|
+
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
1583
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1584
|
+
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
1585
|
+
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
1586
|
+
return [
|
|
1587
|
+
header(colors, summary),
|
|
1588
|
+
"",
|
|
1589
|
+
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
1590
|
+
"",
|
|
1591
|
+
...await commandRows(commands, colors),
|
|
1592
|
+
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
1593
|
+
"",
|
|
1594
|
+
colors.bold("Options:"),
|
|
1595
|
+
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
1596
|
+
...exampleRows(examples ?? [], colors),
|
|
1597
|
+
"",
|
|
1598
|
+
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
1599
|
+
].join(`
|
|
1600
|
+
`);
|
|
1601
|
+
}
|
|
1602
|
+
function printError(prefix, message, hint, cause) {
|
|
1603
|
+
const colors = paint(process17.stderr);
|
|
1604
|
+
const styled = takesControlCodes(process17.stderr);
|
|
1605
|
+
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1606
|
+
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1607
|
+
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1608
|
+
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1609
|
+
}
|
|
1610
|
+
function printJsonError(message, hint, cause) {
|
|
1611
|
+
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1612
|
+
}
|
|
1613
|
+
function wantsJson(argv) {
|
|
1614
|
+
const end = argv.indexOf("--");
|
|
1615
|
+
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1616
|
+
}
|
|
1617
|
+
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1618
|
+
if (error instanceof HelpShown)
|
|
1619
|
+
return 0;
|
|
1620
|
+
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1621
|
+
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1622
|
+
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1623
|
+
if (error instanceof Exit && error.code === 2)
|
|
1624
|
+
noteUsageError(error.message);
|
|
1625
|
+
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1626
|
+
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
1627
|
+
return error instanceof Exit ? error.code : 1;
|
|
1628
|
+
}
|
|
1629
|
+
async function dispatch(level, typed, { version, redact }) {
|
|
1630
|
+
const prefix = level.path.join(" ");
|
|
1631
|
+
let argv;
|
|
1632
|
+
try {
|
|
1633
|
+
argv = takeOutputFlags(typed);
|
|
1634
|
+
} catch (error) {
|
|
1635
|
+
return reportThrown(prefix, error);
|
|
1636
|
+
}
|
|
1637
|
+
const [name, ...args] = argv;
|
|
1638
|
+
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
1639
|
+
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
1640
|
+
try {
|
|
1641
|
+
return await fallback.run([]);
|
|
1642
|
+
} catch (error) {
|
|
1643
|
+
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
if (name === undefined && level.path.length > 1) {
|
|
1647
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process17.stderr));
|
|
1648
|
+
return 2;
|
|
1649
|
+
}
|
|
1650
|
+
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1651
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process17.stdout));
|
|
1652
|
+
return 0;
|
|
1653
|
+
}
|
|
1654
|
+
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
1655
|
+
console.log(version);
|
|
1656
|
+
return 0;
|
|
1657
|
+
}
|
|
1658
|
+
let command = lookup(level, name);
|
|
1659
|
+
let rest = args;
|
|
1660
|
+
let ran = name;
|
|
1661
|
+
if (command === undefined && level.lazy.length > 0) {
|
|
1662
|
+
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
1663
|
+
command = lookup(level, name);
|
|
1664
|
+
}
|
|
1665
|
+
if (command === undefined && level.defaultCommand !== undefined) {
|
|
1666
|
+
command = level.commands[level.defaultCommand];
|
|
1667
|
+
rest = argv;
|
|
1668
|
+
ran = level.defaultCommand;
|
|
1669
|
+
}
|
|
1670
|
+
if (command === undefined) {
|
|
1671
|
+
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
1672
|
+
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
1673
|
+
return 2;
|
|
1674
|
+
}
|
|
1675
|
+
if ("commands" in command) {
|
|
1676
|
+
const { summary } = command;
|
|
1677
|
+
return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
|
|
1678
|
+
}
|
|
1679
|
+
try {
|
|
1680
|
+
return await command.run(rest);
|
|
1681
|
+
} catch (error) {
|
|
1682
|
+
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
async function completingOf(run) {
|
|
1686
|
+
completion.active = true;
|
|
1687
|
+
try {
|
|
1688
|
+
await run([]);
|
|
1689
|
+
} catch (error) {
|
|
1690
|
+
if (error instanceof Completing)
|
|
1691
|
+
return error;
|
|
1692
|
+
} finally {
|
|
1693
|
+
completion.active = false;
|
|
1694
|
+
}
|
|
1695
|
+
return new Completing({});
|
|
1696
|
+
}
|
|
1697
|
+
async function optionsOf(run) {
|
|
1698
|
+
return (await completingOf(run)).options;
|
|
1699
|
+
}
|
|
1700
|
+
function candidateLine(candidate) {
|
|
1701
|
+
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
1702
|
+
}
|
|
1703
|
+
function positionalBeingTyped(before, { options, positionals }) {
|
|
1704
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1705
|
+
const typed = [];
|
|
1706
|
+
let at = 0;
|
|
1707
|
+
while (at < before.length) {
|
|
1708
|
+
const word = before[at];
|
|
1709
|
+
if (word === "--") {
|
|
1710
|
+
typed.push(...before.slice(at + 1));
|
|
1711
|
+
break;
|
|
1712
|
+
}
|
|
1713
|
+
if (!word.startsWith("-"))
|
|
1714
|
+
typed.push(word);
|
|
1715
|
+
else if (takesValue(word))
|
|
1716
|
+
at++;
|
|
1717
|
+
at++;
|
|
1718
|
+
}
|
|
1719
|
+
const last = positionals.at(-1);
|
|
1720
|
+
if (typed.length < positionals.length)
|
|
1721
|
+
return { name: positionals[typed.length], typed };
|
|
1722
|
+
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1723
|
+
}
|
|
1724
|
+
async function leafCandidates(run, words) {
|
|
1725
|
+
const completing = await completingOf(run);
|
|
1726
|
+
if ((words.at(-1) ?? "").startsWith("-"))
|
|
1727
|
+
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1728
|
+
const flag = words.at(-2);
|
|
1729
|
+
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1730
|
+
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1731
|
+
if (option?.type === "string") {
|
|
1732
|
+
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1733
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1734
|
+
}
|
|
1735
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1736
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1737
|
+
}
|
|
1738
|
+
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1739
|
+
const [word = "", ...rest] = words;
|
|
1740
|
+
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1741
|
+
let { commands } = scope;
|
|
1742
|
+
let command = lookup(scope, word);
|
|
1743
|
+
if (listing || command === undefined) {
|
|
1744
|
+
const expanded = await expand(scope, [...before, ...words]);
|
|
1745
|
+
commands = expanded.commands;
|
|
1746
|
+
command = lookup(expanded, word);
|
|
1747
|
+
}
|
|
1748
|
+
if (listing) {
|
|
1749
|
+
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1750
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1751
|
+
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1752
|
+
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1753
|
+
return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
|
|
1754
|
+
}
|
|
1755
|
+
if (command === undefined) {
|
|
1756
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1757
|
+
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
1758
|
+
}
|
|
1759
|
+
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1760
|
+
}
|
|
1761
|
+
function flagValue([flag = "", ...rest]) {
|
|
1762
|
+
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1763
|
+
}
|
|
1764
|
+
function printCompletionScript(name, args) {
|
|
1765
|
+
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1766
|
+
if (shell === undefined || args.length !== 1) {
|
|
1767
|
+
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1768
|
+
return 2;
|
|
1769
|
+
}
|
|
1770
|
+
console.log(completionScript(shell, [name]).trimEnd());
|
|
1771
|
+
return 0;
|
|
1772
|
+
}
|
|
1773
|
+
async function printCandidates(found) {
|
|
1774
|
+
for (const line of await found)
|
|
1775
|
+
console.log(line);
|
|
1776
|
+
return 0;
|
|
1777
|
+
}
|
|
1778
|
+
function packageVersion(entry = Bun.main) {
|
|
1779
|
+
let resolved = entry;
|
|
1780
|
+
try {
|
|
1781
|
+
resolved = realpathSync2(entry);
|
|
1782
|
+
} catch {}
|
|
1783
|
+
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1784
|
+
try {
|
|
1785
|
+
const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
|
|
1786
|
+
if (typeof version === "string")
|
|
1787
|
+
return version;
|
|
1788
|
+
} catch {}
|
|
1789
|
+
if (dirname3(dir) === dir)
|
|
1790
|
+
return "0.0.0";
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
async function runCli(cli, argv = scriptArgs()) {
|
|
1794
|
+
const version = cli.version ?? packageVersion();
|
|
1795
|
+
const answered = await askpassClient(argv);
|
|
1796
|
+
if (answered !== undefined)
|
|
1797
|
+
return answered;
|
|
1798
|
+
if (argv[0] === COMPLETE)
|
|
1799
|
+
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1800
|
+
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1801
|
+
return printCompletionScript(cli.name, flagValue(argv));
|
|
1802
|
+
const started = performance.now();
|
|
1803
|
+
const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
|
|
1804
|
+
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1805
|
+
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1806
|
+
if (cli.usage !== false) {
|
|
1807
|
+
try {
|
|
1808
|
+
recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
|
|
1809
|
+
} catch {}
|
|
1810
|
+
}
|
|
1811
|
+
return code;
|
|
1812
|
+
}
|
|
1813
|
+
function commandPath(scope, argv) {
|
|
1814
|
+
const path = [];
|
|
1815
|
+
let level = scope;
|
|
1816
|
+
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1817
|
+
const command = lookup(level, word);
|
|
1818
|
+
if (command === undefined)
|
|
1819
|
+
break;
|
|
1820
|
+
path.push(word);
|
|
1821
|
+
if (!("commands" in command))
|
|
1822
|
+
break;
|
|
1823
|
+
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
1824
|
+
}
|
|
1825
|
+
return path.length === 0 ? undefined : path.join(" ");
|
|
1826
|
+
}
|
|
1827
|
+
var LEVEL_OPTIONS, TOP_OPTIONS, COMPLETE = "__complete", FILES = "__files__", COMPLETIONS = "--completions";
|
|
1828
|
+
var init_cli = __esm(() => {
|
|
1829
|
+
init_args();
|
|
1830
|
+
init_argv();
|
|
1831
|
+
init_askpass();
|
|
1832
|
+
init_completions();
|
|
1833
|
+
init_notify();
|
|
1834
|
+
init_style();
|
|
1835
|
+
init_text2();
|
|
1836
|
+
init_usage();
|
|
1837
|
+
LEVEL_OPTIONS = {
|
|
1838
|
+
...OUTPUT_OPTIONS,
|
|
1839
|
+
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1840
|
+
};
|
|
1841
|
+
TOP_OPTIONS = {
|
|
1842
|
+
...LEVEL_OPTIONS,
|
|
1843
|
+
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1844
|
+
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1845
|
+
};
|
|
1846
|
+
});
|
|
1847
|
+
// ../kit/src/excerpt.ts
|
|
1848
|
+
var init_excerpt = __esm(() => {
|
|
1849
|
+
init_text2();
|
|
1850
|
+
});
|
|
1851
|
+
|
|
1852
|
+
// ../kit/src/folders.ts
|
|
1853
|
+
var SKIPPED_FOLDERS;
|
|
1854
|
+
var init_folders = __esm(() => {
|
|
1855
|
+
init_user_config();
|
|
1856
|
+
SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
1857
|
+
});
|
|
1858
|
+
|
|
1859
|
+
// ../kit/src/git.ts
|
|
1860
|
+
var init_git = __esm(() => {
|
|
1861
|
+
init_args();
|
|
1862
|
+
init_tool();
|
|
1863
|
+
});
|
|
1864
|
+
|
|
1865
|
+
// ../kit/src/limit.ts
|
|
1866
|
+
var init_limit = __esm(() => {
|
|
1867
|
+
init_args();
|
|
1868
|
+
});
|
|
1869
|
+
// ../kit/src/report.ts
|
|
1870
|
+
var init_report = __esm(() => {
|
|
1871
|
+
init_cli();
|
|
1872
|
+
init_style();
|
|
1873
|
+
init_text2();
|
|
1874
|
+
});
|
|
1875
|
+
|
|
1876
|
+
// ../kit/src/secrets.ts
|
|
1877
|
+
var SECRET_WORDS, NOT_PASSWORDS;
|
|
1878
|
+
var init_secrets = __esm(() => {
|
|
1879
|
+
SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1880
|
+
NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
|
|
1881
|
+
});
|
|
1882
|
+
|
|
1883
|
+
// ../kit/src/sessions.ts
|
|
1884
|
+
var {Glob } = globalThis.Bun;
|
|
1885
|
+
var SESSION_FILES, ACCOUNT_DIRS;
|
|
1886
|
+
var init_sessions = __esm(() => {
|
|
1887
|
+
SESSION_FILES = new Glob("*.json");
|
|
1888
|
+
ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1889
|
+
});
|
|
1890
|
+
|
|
1891
|
+
// ../kit/src/size.ts
|
|
1892
|
+
function parseSize(text, bareUnit = 1) {
|
|
1893
|
+
const match = SIZE.exec(text.trim());
|
|
1894
|
+
if (match === null)
|
|
1895
|
+
return;
|
|
1896
|
+
const suffix = match[2]?.toLowerCase();
|
|
1897
|
+
let unit = bareUnit;
|
|
1898
|
+
if (match[3] !== undefined)
|
|
1899
|
+
unit = 1;
|
|
1900
|
+
else if (suffix !== undefined)
|
|
1901
|
+
unit = 1024 ** POWERS[suffix];
|
|
1902
|
+
return Math.round(Number(match[1]) * unit);
|
|
1903
|
+
}
|
|
1904
|
+
function formatSize(bytes) {
|
|
1905
|
+
let value = bytes;
|
|
1906
|
+
let unit = 0;
|
|
1907
|
+
while (value >= 1024 && unit < UNITS2.length - 1) {
|
|
1908
|
+
value /= 1024;
|
|
1909
|
+
unit++;
|
|
1910
|
+
}
|
|
1911
|
+
if (unit === 0)
|
|
1912
|
+
return `${value}B`;
|
|
1913
|
+
if (Number(value.toFixed(value < 10 ? 1 : 0)) >= 1024 && unit < UNITS2.length - 1) {
|
|
1914
|
+
value /= 1024;
|
|
1915
|
+
unit++;
|
|
1916
|
+
}
|
|
1917
|
+
return `${value.toFixed(value < 10 ? 1 : 0)}${UNITS2[unit]}`;
|
|
1918
|
+
}
|
|
1919
|
+
var SIZE, POWERS, UNITS2;
|
|
1920
|
+
var init_size = __esm(() => {
|
|
1921
|
+
SIZE = /^(\d+(?:\.\d+)?)\s*(?:([kmgt])i?b?|(b))?$/i;
|
|
1922
|
+
POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
|
|
1923
|
+
UNITS2 = ["B", "K", "M", "G", "T"];
|
|
1924
|
+
});
|
|
1925
|
+
|
|
1926
|
+
// ../kit/src/watch.ts
|
|
1927
|
+
var init_watch = __esm(() => {
|
|
1928
|
+
init_args();
|
|
1929
|
+
init_input();
|
|
1930
|
+
init_style();
|
|
1931
|
+
});
|
|
1932
|
+
|
|
1933
|
+
// ../kit/src/workspace-root.ts
|
|
1934
|
+
var init_workspace_root = __esm(() => {
|
|
1935
|
+
init_user_config();
|
|
1936
|
+
});
|
|
1937
|
+
|
|
1938
|
+
// ../kit/src/index.ts
|
|
1939
|
+
var init_src = __esm(() => {
|
|
1940
|
+
init_excerpt();
|
|
1941
|
+
init_advisory();
|
|
1942
|
+
init_args();
|
|
1943
|
+
init_argv();
|
|
1944
|
+
init_chart();
|
|
1945
|
+
init_ci();
|
|
1946
|
+
init_cli();
|
|
1947
|
+
init_completions();
|
|
1948
|
+
init_config();
|
|
1949
|
+
init_folders();
|
|
1950
|
+
init_format();
|
|
1951
|
+
init_git();
|
|
1952
|
+
init_limit();
|
|
1953
|
+
init_logs();
|
|
1954
|
+
init_mode();
|
|
1955
|
+
init_process();
|
|
1956
|
+
init_report();
|
|
1957
|
+
init_secrets();
|
|
1958
|
+
init_sessions();
|
|
1959
|
+
init_size();
|
|
1960
|
+
init_style();
|
|
1961
|
+
init_text2();
|
|
1962
|
+
init_theme();
|
|
1963
|
+
init_tool();
|
|
1964
|
+
init_usage();
|
|
1965
|
+
init_user_config();
|
|
1966
|
+
init_watch();
|
|
1967
|
+
init_workspace_root();
|
|
1968
|
+
});
|
|
1969
|
+
|
|
1970
|
+
// ../arc/src/proc.ts
|
|
1971
|
+
import process19 from "process";
|
|
1972
|
+
async function interactive(argv, cwd = process19.cwd()) {
|
|
1973
|
+
return Bun.spawn(argv, { cwd, stdin: "inherit", stdout: "inherit", stderr: "inherit" }).exited;
|
|
1974
|
+
}
|
|
1975
|
+
var init_proc = __esm(() => {
|
|
1976
|
+
init_src();
|
|
1977
|
+
});
|
|
1978
|
+
|
|
1979
|
+
// ../arc/src/extract.ts
|
|
1980
|
+
import { existsSync as existsSync3, renameSync, rmSync, statSync as statSync2 } from "fs";
|
|
1981
|
+
import { basename, join as join6, resolve as resolve4 } from "path";
|
|
1982
|
+
function archiveSuffix(file) {
|
|
1983
|
+
return extractorOf(file)?.[0];
|
|
1984
|
+
}
|
|
1985
|
+
function extractorOf(file) {
|
|
1986
|
+
return EXTRACTORS.find(([suffix]) => file.toLowerCase().endsWith(suffix));
|
|
1987
|
+
}
|
|
1988
|
+
async function extractArchive(file, cwd, overwrite = false) {
|
|
1989
|
+
if (!existsSync3(file) || !statSync2(file).isFile())
|
|
1990
|
+
return fail(`'${file}' is not a file`, 1);
|
|
1991
|
+
const extractor = extractorOf(file);
|
|
1992
|
+
if (extractor === undefined)
|
|
1993
|
+
return fail(`'${file}' cannot be extracted: unknown extension`, 1);
|
|
1994
|
+
const [suffix, argvOf] = extractor;
|
|
1995
|
+
const argv = argvOf(resolve4(file), overwrite);
|
|
1996
|
+
if (Bun.which(argv[0] ?? "") === null)
|
|
1997
|
+
return fail(`${argv[0]} is not on PATH`, 1);
|
|
1998
|
+
if (!LONE.has(suffix))
|
|
1999
|
+
return await interactive(argv, cwd) === 0 ? 0 : 1;
|
|
2000
|
+
const name = basename(file).slice(0, -suffix.length);
|
|
2001
|
+
if (name === "")
|
|
2002
|
+
return fail(`'${file}' has no name left once ${suffix} is taken off`, 1);
|
|
2003
|
+
const target = join6(cwd, name);
|
|
2004
|
+
if (existsSync3(target) && !overwrite)
|
|
2005
|
+
return fail(`'${target}' already exists, nothing written`, 1, "pass --overwrite to replace it");
|
|
2006
|
+
const partial = `${target}.arc-partial`;
|
|
2007
|
+
if (await Bun.spawn(argv, { stdin: "ignore", stdout: Bun.file(partial), stderr: "inherit" }).exited === 0) {
|
|
2008
|
+
renameSync(partial, target);
|
|
2009
|
+
return 0;
|
|
2010
|
+
}
|
|
2011
|
+
rmSync(partial, { force: true });
|
|
2012
|
+
return 1;
|
|
2013
|
+
}
|
|
2014
|
+
var keepOld = (overwrite) => overwrite ? [] : ["-k"], EXTRACTORS, LONE;
|
|
2015
|
+
var init_extract = __esm(() => {
|
|
2016
|
+
init_src();
|
|
2017
|
+
init_proc();
|
|
2018
|
+
EXTRACTORS = [
|
|
2019
|
+
[".tar.bz2", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xjf", file]],
|
|
2020
|
+
[".tar.gz", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xzf", file]],
|
|
2021
|
+
[".tar.xz", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xJf", file]],
|
|
2022
|
+
[".tar.zst", (file, overwrite) => ["tar", ...keepOld(overwrite), "--zstd", "-xf", file]],
|
|
2023
|
+
[".tbz2", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xjf", file]],
|
|
2024
|
+
[".tgz", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xzf", file]],
|
|
2025
|
+
[".tar", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xf", file]],
|
|
2026
|
+
[".tbz", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xjf", file]],
|
|
2027
|
+
[".txz", (file, overwrite) => ["tar", ...keepOld(overwrite), "-xJf", file]],
|
|
2028
|
+
[".tzst", (file, overwrite) => ["tar", ...keepOld(overwrite), "--zstd", "-xf", file]],
|
|
2029
|
+
[".bz2", (file) => ["bunzip2", "-c", file]],
|
|
2030
|
+
[".gz", (file) => ["gunzip", "-c", file]],
|
|
2031
|
+
[".xz", (file) => ["xz", "-dc", file]],
|
|
2032
|
+
[".zst", (file) => ["zstd", "-dc", file]],
|
|
2033
|
+
[".zip", (file, overwrite) => ["unzip", overwrite ? "-o" : "-n", file]],
|
|
2034
|
+
[".z", (file) => ["gzip", "-dc", file]],
|
|
2035
|
+
[".rar", (file, overwrite) => ["unrar", "x", overwrite ? "-o+" : "-o-", file]],
|
|
2036
|
+
[".7z", (file, overwrite) => ["7z", "x", overwrite ? "-aoa" : "-aos", file]]
|
|
2037
|
+
];
|
|
2038
|
+
LONE = new Set([".bz2", ".gz", ".xz", ".zst", ".z"]);
|
|
2039
|
+
});
|
|
2040
|
+
|
|
2041
|
+
// src/state.ts
|
|
2042
|
+
import { copyFileSync, existsSync as existsSync4, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync5, renameSync as renameSync2, rmSync as rmSync2, statSync as statSync3, writeFileSync } from "fs";
|
|
2043
|
+
import { dirname as dirname4, join as join7 } from "path";
|
|
2044
|
+
function stateDir() {
|
|
2045
|
+
return join7(stateHome(), CLI_FOLDER, "dl");
|
|
2046
|
+
}
|
|
2047
|
+
function seenDir(url) {
|
|
2048
|
+
return join7(stateDir(), "seen", new Bun.CryptoHasher("sha256").update(url).digest("hex").slice(0, 32));
|
|
2049
|
+
}
|
|
2050
|
+
function lastSeen(url) {
|
|
2051
|
+
const dir = seenDir(url);
|
|
2052
|
+
const meta = join7(dir, "seen.json");
|
|
2053
|
+
if (!existsSync4(meta))
|
|
2054
|
+
return;
|
|
2055
|
+
const content = join7(dir, "content");
|
|
2056
|
+
return { seen: JSON.parse(readFileSync5(meta, "utf8")), content: existsSync4(content) ? content : undefined };
|
|
2057
|
+
}
|
|
2058
|
+
function remember(url, file) {
|
|
2059
|
+
const dir = seenDir(url);
|
|
2060
|
+
const content = join7(dir, "content");
|
|
2061
|
+
mkdirSync2(dir, { recursive: true });
|
|
2062
|
+
rmSync2(content, { force: true });
|
|
2063
|
+
if (file.text && !file.html && file.size <= KEPT_TEXT)
|
|
2064
|
+
copyFileSync(file.path, content);
|
|
2065
|
+
writeJson(join7(dir, "seen.json"), { url, sha256: file.sha256, size: file.size, at: new Date().toISOString() });
|
|
2066
|
+
}
|
|
2067
|
+
function partOf(url) {
|
|
2068
|
+
const dir = seenDir(url);
|
|
2069
|
+
const file = join7(dir, "part");
|
|
2070
|
+
const meta = join7(dir, "part.json");
|
|
2071
|
+
if (!existsSync4(file) || !existsSync4(meta))
|
|
2072
|
+
return { file, kept: undefined };
|
|
2073
|
+
const part = JSON.parse(readFileSync5(meta, "utf8"));
|
|
2074
|
+
const size = statSync3(file).size;
|
|
2075
|
+
return { file, kept: part.url === url && size > 0 ? { ...part, size } : undefined };
|
|
2076
|
+
}
|
|
2077
|
+
function keepPart(part) {
|
|
2078
|
+
writeJson(join7(seenDir(part.url), "part.json"), part);
|
|
2079
|
+
}
|
|
2080
|
+
function dropPart(url) {
|
|
2081
|
+
rmSync2(join7(seenDir(url), "part"), { force: true });
|
|
2082
|
+
rmSync2(join7(seenDir(url), "part.json"), { force: true });
|
|
2083
|
+
}
|
|
2084
|
+
function dropStaleParts(now = Date.now()) {
|
|
2085
|
+
const seen = join7(stateDir(), "seen");
|
|
2086
|
+
if (!existsSync4(seen))
|
|
2087
|
+
return;
|
|
2088
|
+
for (const dir of readdirSync(seen)) {
|
|
2089
|
+
const file = join7(seen, dir, "part");
|
|
2090
|
+
if (existsSync4(file) && now - statSync3(file).mtimeMs > PART_LIFETIME) {
|
|
2091
|
+
rmSync2(file, { force: true });
|
|
2092
|
+
rmSync2(join7(seen, dir, "part.json"), { force: true });
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
function ledgerPath() {
|
|
2097
|
+
return join7(stateDir(), "ledger.json");
|
|
2098
|
+
}
|
|
2099
|
+
function readLedger() {
|
|
2100
|
+
const path = ledgerPath();
|
|
2101
|
+
return existsSync4(path) ? JSON.parse(readFileSync5(path, "utf8")) : [];
|
|
2102
|
+
}
|
|
2103
|
+
function record(entry) {
|
|
2104
|
+
writeJson(ledgerPath(), [...readLedger().filter((other) => other.kind !== entry.kind || other.name !== entry.name), entry]);
|
|
2105
|
+
}
|
|
2106
|
+
function writeJson(path, value) {
|
|
2107
|
+
mkdirSync2(dirname4(path), { recursive: true });
|
|
2108
|
+
writeFileSync(`${path}.tmp`, `${JSON.stringify(value, null, 2)}
|
|
2109
|
+
`);
|
|
2110
|
+
renameSync2(`${path}.tmp`, path);
|
|
2111
|
+
}
|
|
2112
|
+
var KEPT_TEXT, PART_LIFETIME;
|
|
2113
|
+
var init_state = __esm(() => {
|
|
2114
|
+
init_src();
|
|
2115
|
+
KEPT_TEXT = 1024 * 1024;
|
|
2116
|
+
PART_LIFETIME = 7 * 24 * 3600000;
|
|
2117
|
+
});
|
|
2118
|
+
|
|
2119
|
+
// src/download.ts
|
|
2120
|
+
import { copyFileSync as copyFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync3, renameSync as renameSync3, rmSync as rmSync3 } from "fs";
|
|
2121
|
+
import { open } from "fs/promises";
|
|
2122
|
+
import { basename as basename2, dirname as dirname5, join as join8 } from "path";
|
|
2123
|
+
async function request(url, kept) {
|
|
2124
|
+
const headers = { "accept-encoding": "identity" };
|
|
2125
|
+
const validator = kept?.etag !== undefined && !kept.etag.startsWith("W/") ? kept.etag : kept?.lastModified;
|
|
2126
|
+
if (kept === undefined || validator === undefined)
|
|
2127
|
+
return { response: await reach(url, { headers, decompress: false }), offset: 0 };
|
|
2128
|
+
const response = await reach(url, { headers: { ...headers, range: `bytes=${kept.size}-`, "if-range": validator }, decompress: false }, [RANGE_NOT_SATISFIABLE]);
|
|
2129
|
+
const start = CONTENT_RANGE.exec(response.headers.get("content-range") ?? "")?.[1];
|
|
2130
|
+
if (response.status === 206 && Number(start) === kept.size)
|
|
2131
|
+
return { response, offset: kept.size };
|
|
2132
|
+
if (response.status === 200)
|
|
2133
|
+
return { response, offset: 0 };
|
|
2134
|
+
await response.body?.cancel();
|
|
2135
|
+
return { response: await reach(url, { headers, decompress: false }), offset: 0 };
|
|
2136
|
+
}
|
|
2137
|
+
async function replay(file, hasher) {
|
|
2138
|
+
for await (const chunk of Bun.file(file).stream())
|
|
2139
|
+
hasher.update(chunk);
|
|
2140
|
+
return Bun.file(file).slice(0, HEAD_BYTES).bytes();
|
|
2141
|
+
}
|
|
2142
|
+
function moveInto(from, to) {
|
|
2143
|
+
try {
|
|
2144
|
+
renameSync3(from, to);
|
|
2145
|
+
} catch {
|
|
2146
|
+
copyFileSync2(from, to);
|
|
2147
|
+
rmSync3(from, { force: true });
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
async function download(url, dir, maxSize) {
|
|
2151
|
+
dropStaleParts();
|
|
2152
|
+
const { file: partFile, kept } = partOf(url);
|
|
2153
|
+
const { response, offset } = await request(url, kept);
|
|
2154
|
+
const name = offset > 0 ? kept.name : fileName(response, url);
|
|
2155
|
+
const path = join8(dir, name);
|
|
2156
|
+
if (existsSync5(path)) {
|
|
2157
|
+
await response.body?.cancel();
|
|
2158
|
+
return fail(`'${path}' already exists`, 1, "download into another folder with -o, or none to get a new one");
|
|
2159
|
+
}
|
|
2160
|
+
const length = Number(response.headers.get("content-length") ?? Number.NaN);
|
|
2161
|
+
const total = Number.isFinite(length) && length > 0 ? offset + length : undefined;
|
|
2162
|
+
if (total !== undefined && total > maxSize) {
|
|
2163
|
+
await response.body?.cancel();
|
|
2164
|
+
return fail(`${url} is ${formatSize(total)}, over --max-size ${formatSize(maxSize)}`, 1);
|
|
2165
|
+
}
|
|
2166
|
+
const part = { url, name, ...offset > 0 ? validators(kept) : {}, ...validators(response.headers) };
|
|
2167
|
+
const resumable = part.etag !== undefined || part.lastModified !== undefined;
|
|
2168
|
+
if (offset === 0)
|
|
2169
|
+
dropPart(url);
|
|
2170
|
+
if (resumable)
|
|
2171
|
+
keepPart(part);
|
|
2172
|
+
const line = progressLine();
|
|
2173
|
+
const hasher = new Bun.CryptoHasher("sha256");
|
|
2174
|
+
const head = offset > 0 ? [await replay(partFile, hasher)] : [];
|
|
2175
|
+
mkdirSync3(dirname5(partFile), { recursive: true });
|
|
2176
|
+
const handle = await open(partFile, offset > 0 ? "a" : "w");
|
|
2177
|
+
let headSize = head[0]?.length ?? 0;
|
|
2178
|
+
let size = offset;
|
|
2179
|
+
let overSize = false;
|
|
2180
|
+
line.update({ step: name, ...counted(size, total) });
|
|
2181
|
+
try {
|
|
2182
|
+
for await (const chunk of response.body ?? new ReadableStream) {
|
|
2183
|
+
size += chunk.length;
|
|
2184
|
+
overSize = size > maxSize;
|
|
2185
|
+
if (overSize)
|
|
2186
|
+
fail(`${url} goes over --max-size ${formatSize(maxSize)}`, 1);
|
|
2187
|
+
if (headSize < HEAD_BYTES) {
|
|
2188
|
+
head.push(chunk.subarray(0, HEAD_BYTES - headSize));
|
|
2189
|
+
headSize += head.at(-1).length;
|
|
2190
|
+
}
|
|
2191
|
+
hasher.update(chunk);
|
|
2192
|
+
await handle.write(chunk);
|
|
2193
|
+
line.update({ step: name, ...counted(size, total) });
|
|
2194
|
+
}
|
|
2195
|
+
} catch (error) {
|
|
2196
|
+
await handle.close();
|
|
2197
|
+
line.failed(name);
|
|
2198
|
+
if (overSize || !resumable) {
|
|
2199
|
+
dropPart(url);
|
|
2200
|
+
throw error;
|
|
2201
|
+
}
|
|
2202
|
+
return fail(`the download of ${url} broke off at ${formatSize(size)}: ${error instanceof Error ? error.message : String(error)}`, 1, "run the same dl again to resume it");
|
|
2203
|
+
}
|
|
2204
|
+
await handle.close();
|
|
2205
|
+
moveInto(partFile, path);
|
|
2206
|
+
dropPart(url);
|
|
2207
|
+
line.done(`${name} ${formatSize(size)}${offset > 0 ? `, resumed at ${formatSize(offset)}` : ""}`);
|
|
2208
|
+
const start = Buffer.concat(head);
|
|
2209
|
+
return {
|
|
2210
|
+
path,
|
|
2211
|
+
name,
|
|
2212
|
+
size,
|
|
2213
|
+
url: response.url === "" ? url : response.url,
|
|
2214
|
+
type: response.headers.get("content-type") ?? "",
|
|
2215
|
+
sha256: hasher.digest("hex"),
|
|
2216
|
+
html: HTML_START.test(start.toString("utf8")),
|
|
2217
|
+
text: !start.includes(0),
|
|
2218
|
+
...validators(part)
|
|
2219
|
+
};
|
|
2220
|
+
}
|
|
2221
|
+
function validators(from) {
|
|
2222
|
+
const etag = from instanceof Headers ? from.get("etag") ?? undefined : from.etag;
|
|
2223
|
+
const lastModified = from instanceof Headers ? from.get("last-modified") ?? undefined : from.lastModified;
|
|
2224
|
+
return { ...etag === undefined ? {} : { etag }, ...lastModified === undefined ? {} : { lastModified } };
|
|
2225
|
+
}
|
|
2226
|
+
async function smallFile(url) {
|
|
2227
|
+
const response = await reach(url);
|
|
2228
|
+
const chunks = [];
|
|
2229
|
+
let size = 0;
|
|
2230
|
+
for await (const chunk of response.body ?? new ReadableStream) {
|
|
2231
|
+
size += chunk.length;
|
|
2232
|
+
if (size > SMALL_FILE)
|
|
2233
|
+
fail(`${url} goes over ${formatSize(SMALL_FILE)}, too large for a signature or checksums file`, 1);
|
|
2234
|
+
chunks.push(chunk);
|
|
2235
|
+
}
|
|
2236
|
+
return Buffer.concat(chunks);
|
|
2237
|
+
}
|
|
2238
|
+
async function reach(url, init, allowed = []) {
|
|
2239
|
+
let response;
|
|
2240
|
+
try {
|
|
2241
|
+
response = await fetch(url, init);
|
|
2242
|
+
} catch (error) {
|
|
2243
|
+
return fail(`cannot reach ${url}: ${error instanceof Error ? error.message : String(error)}`, 1);
|
|
2244
|
+
}
|
|
2245
|
+
return response.ok || allowed.includes(response.status) ? response : fail(`${url} answered ${response.status} ${response.statusText}`.trimEnd(), 1);
|
|
2246
|
+
}
|
|
2247
|
+
function fileName(response, requested) {
|
|
2248
|
+
const disposition = DISPOSITION_NAME.exec(response.headers.get("content-disposition") ?? "")?.[1];
|
|
2249
|
+
const raw = disposition ?? new URL(response.url === "" ? requested : response.url).pathname.split("/").at(-1) ?? "";
|
|
2250
|
+
const name = basename2(decoded(raw).replaceAll("\\", "/")).replaceAll("\x00", "");
|
|
2251
|
+
return name === "" || name === "." || name === ".." ? "download" : name;
|
|
2252
|
+
}
|
|
2253
|
+
function decoded(text) {
|
|
2254
|
+
try {
|
|
2255
|
+
return decodeURIComponent(text);
|
|
2256
|
+
} catch {
|
|
2257
|
+
return text;
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
2260
|
+
function counted(done, total) {
|
|
2261
|
+
if (total === undefined)
|
|
2262
|
+
return {};
|
|
2263
|
+
const [unit, scale] = total >= 1024 ** 2 ? ["MiB", 1024 ** 2] : ["KiB", 1024];
|
|
2264
|
+
return { done: Math.floor(done / scale), total: Math.ceil(total / scale), unit };
|
|
2265
|
+
}
|
|
2266
|
+
var HEAD_BYTES = 8192, HTML_START, DISPOSITION_NAME, CONTENT_RANGE, RANGE_NOT_SATISFIABLE = 416, SMALL_FILE;
|
|
2267
|
+
var init_download = __esm(() => {
|
|
2268
|
+
init_src();
|
|
2269
|
+
init_progress();
|
|
2270
|
+
init_state();
|
|
2271
|
+
HTML_START = /^\s*<(?:!doctype html|html)[\s>]/i;
|
|
2272
|
+
DISPOSITION_NAME = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i;
|
|
2273
|
+
CONTENT_RANGE = /^bytes (\d+)-\d+\/(?:\d+|\*)$/;
|
|
2274
|
+
SMALL_FILE = 16 * 1024 * 1024;
|
|
2275
|
+
});
|
|
2276
|
+
|
|
2277
|
+
// src/install.ts
|
|
2278
|
+
import { chmodSync, closeSync, copyFileSync as copyFileSync3, existsSync as existsSync6, mkdirSync as mkdirSync4, openSync, readSync, renameSync as renameSync4, statSync as statSync4 } from "fs";
|
|
2279
|
+
import { homedir as homedir4 } from "os";
|
|
2280
|
+
import { basename as basename3, delimiter, join as join9, relative } from "path";
|
|
2281
|
+
import process20 from "process";
|
|
2282
|
+
function binDir() {
|
|
2283
|
+
return join9(homedir4(), ".local", "bin");
|
|
2284
|
+
}
|
|
2285
|
+
function binDirOnPath() {
|
|
2286
|
+
return (process20.env.PATH ?? "").split(delimiter).includes(binDir());
|
|
2287
|
+
}
|
|
2288
|
+
async function pickBinary(root, wanted) {
|
|
2289
|
+
const found = [];
|
|
2290
|
+
for await (const file of new Bun.Glob("**/*").scan({ cwd: root, onlyFiles: true, dot: true }))
|
|
2291
|
+
found.push(join9(root, file));
|
|
2292
|
+
const executables = found.filter(isExecutable).sort();
|
|
2293
|
+
const matching = wanted === undefined ? executables : executables.filter((file) => basename3(file) === wanted);
|
|
2294
|
+
const listed = executables.map((file) => relative(root, file)).join(", ");
|
|
2295
|
+
if (matching.length === 1)
|
|
2296
|
+
return matching[0];
|
|
2297
|
+
if (executables.length === 0)
|
|
2298
|
+
return fail(`the archive holds no executable`, 1);
|
|
2299
|
+
if (matching.length === 0)
|
|
2300
|
+
return fail(`the archive holds no executable named ${wanted}: ${listed}`, 1);
|
|
2301
|
+
return fail(`the archive holds several executables: ${listed}`, 1, "name the one to install: --bin <name>");
|
|
2302
|
+
}
|
|
2303
|
+
function installBinary(source, name, force) {
|
|
2304
|
+
const target = join9(binDir(), name);
|
|
2305
|
+
if (existsSync6(target) && !force)
|
|
2306
|
+
return fail(`'${target}' already exists`, 1, "pass --force to replace it");
|
|
2307
|
+
mkdirSync4(binDir(), { recursive: true });
|
|
2308
|
+
copyFileSync3(source, `${target}.dl-tmp`);
|
|
2309
|
+
chmodSync(`${target}.dl-tmp`, 493);
|
|
2310
|
+
renameSync4(`${target}.dl-tmp`, target);
|
|
2311
|
+
return target;
|
|
2312
|
+
}
|
|
2313
|
+
function isExecutable(file) {
|
|
2314
|
+
if ((statSync4(file).mode & 73) !== 0)
|
|
2315
|
+
return true;
|
|
2316
|
+
const start = Buffer.alloc(4);
|
|
2317
|
+
const fd = openSync(file, "r");
|
|
2318
|
+
readSync(fd, start, 0, 4, 0);
|
|
2319
|
+
closeSync(fd);
|
|
2320
|
+
return start.equals(ELF);
|
|
2321
|
+
}
|
|
2322
|
+
var ELF;
|
|
2323
|
+
var init_install = __esm(() => {
|
|
2324
|
+
init_src();
|
|
2325
|
+
ELF = Buffer.from([127, 69, 76, 70]);
|
|
2326
|
+
});
|
|
2327
|
+
|
|
2328
|
+
// src/release.ts
|
|
2329
|
+
import { readdirSync as readdirSync2 } from "fs";
|
|
2330
|
+
import process21 from "process";
|
|
2331
|
+
function parseSpec(arg) {
|
|
2332
|
+
const [, forge, owner = "", repo = "", tag] = SPEC.exec(arg) ?? [];
|
|
2333
|
+
if (forge === undefined)
|
|
2334
|
+
return;
|
|
2335
|
+
return { forge, owner, repo, ...tag === undefined ? {} : { tag } };
|
|
2336
|
+
}
|
|
2337
|
+
function specName(spec) {
|
|
2338
|
+
return `${spec.forge}:${spec.owner}/${spec.repo}`;
|
|
2339
|
+
}
|
|
2340
|
+
function thisPlatform() {
|
|
2341
|
+
let musl = false;
|
|
2342
|
+
try {
|
|
2343
|
+
const glibc = process21.report.getReport().header?.glibcVersionRuntime;
|
|
2344
|
+
musl = process21.platform === "linux" && glibc === undefined && readdirSync2("/lib").some((file) => file.startsWith("ld-musl-"));
|
|
2345
|
+
} catch {}
|
|
2346
|
+
return { os: process21.platform, arch: process21.arch, musl };
|
|
2347
|
+
}
|
|
2348
|
+
function releasesUrl(spec) {
|
|
2349
|
+
const path = `repos/${spec.owner}/${spec.repo}/releases`;
|
|
2350
|
+
const tagged = spec.tag === undefined ? "" : `/tags/${encodeURIComponent(spec.tag)}`;
|
|
2351
|
+
if (spec.forge === "fj")
|
|
2352
|
+
return { url: `${process21.env.DL_FORGEJO_URL ?? "https://git.kaynooo.fr"}/api/v1/${path}${tagged || "?limit=30"}`, headers: { accept: "application/json" } };
|
|
2353
|
+
const token = process21.env.GITHUB_TOKEN ?? process21.env.GH_TOKEN;
|
|
2354
|
+
const headers = { accept: "application/vnd.github+json", "x-github-api-version": "2022-11-28" };
|
|
2355
|
+
if (token !== undefined && token !== "")
|
|
2356
|
+
headers.authorization = `Bearer ${token}`;
|
|
2357
|
+
return { url: `${process21.env.DL_GITHUB_API ?? "https://api.github.com"}/${path}${tagged || "?per_page=30"}`, headers };
|
|
2358
|
+
}
|
|
2359
|
+
async function releases(spec) {
|
|
2360
|
+
const { url, headers } = releasesUrl(spec);
|
|
2361
|
+
let response;
|
|
2362
|
+
try {
|
|
2363
|
+
response = await fetch(url, { headers });
|
|
2364
|
+
} catch (error) {
|
|
2365
|
+
return fail(`cannot reach ${url}: ${error instanceof Error ? error.message : String(error)}`, 1);
|
|
2366
|
+
}
|
|
2367
|
+
if (response.status === 404)
|
|
2368
|
+
fail(`${specName(spec)} has no release${spec.tag === undefined ? "s" : ` ${spec.tag}`}`, 1);
|
|
2369
|
+
if (!response.ok) {
|
|
2370
|
+
const limited = response.headers.get("x-ratelimit-remaining") === "0";
|
|
2371
|
+
fail(`${url} answered ${response.status} ${response.statusText}`.trimEnd(), 1, limited ? "GitHub's hourly limit is reached: set GITHUB_TOKEN to a token to lift it" : undefined);
|
|
2372
|
+
}
|
|
2373
|
+
const body = await response.json();
|
|
2374
|
+
return (Array.isArray(body) ? body : [body]).filter((release) => !release.draft && (spec.tag !== undefined || !release.prerelease) && release.published_at !== null).map((release) => ({
|
|
2375
|
+
tag: release.tag_name,
|
|
2376
|
+
published: release.published_at,
|
|
2377
|
+
assets: release.assets.map((asset) => ({ name: asset.name, url: asset.browser_download_url, ...typeof asset.digest === "string" ? { digest: asset.digest } : {} }))
|
|
2378
|
+
}));
|
|
2379
|
+
}
|
|
2380
|
+
async function newestFirst(spec) {
|
|
2381
|
+
return (await releases(spec)).sort((a, b) => Date.parse(b.published) - Date.parse(a.published));
|
|
2382
|
+
}
|
|
2383
|
+
function oldEnough(release, now) {
|
|
2384
|
+
return now - Date.parse(release.published) >= MIN_AGE;
|
|
2385
|
+
}
|
|
2386
|
+
async function latestRelease(spec, now = Date.now()) {
|
|
2387
|
+
return (await newestFirst(spec)).find((release) => oldEnough(release, now));
|
|
2388
|
+
}
|
|
2389
|
+
async function pickRelease(spec, fresh, now = Date.now()) {
|
|
2390
|
+
const found = await newestFirst(spec);
|
|
2391
|
+
const newest = found[0] ?? fail(`${specName(spec)} has no published release`, 1);
|
|
2392
|
+
if (spec.tag !== undefined || fresh)
|
|
2393
|
+
return newest;
|
|
2394
|
+
const old = found.find((release) => oldEnough(release, now));
|
|
2395
|
+
const skipped = found.slice(0, old === undefined ? found.length : found.indexOf(old));
|
|
2396
|
+
const said = skipped.map((release) => `${release.tag} (${formatAge(release.published, now)})`).join(", ");
|
|
2397
|
+
if (old === undefined)
|
|
2398
|
+
return fail(`no release of ${specName(spec)} is two weeks old yet: ${said}`, 1, "--fresh takes the newest anyway");
|
|
2399
|
+
if (skipped.length > 0)
|
|
2400
|
+
warn(`${specName(spec)}: took ${old.tag}, skipped ${said} as under two weeks old; --fresh takes the newest`);
|
|
2401
|
+
return old;
|
|
2402
|
+
}
|
|
2403
|
+
function rank(items, score) {
|
|
2404
|
+
const best = Math.min(...items.map(score));
|
|
2405
|
+
return items.filter((item) => score(item) === best);
|
|
2406
|
+
}
|
|
2407
|
+
function libcRank(name, musl) {
|
|
2408
|
+
if (GNU.test(name))
|
|
2409
|
+
return 0;
|
|
2410
|
+
if (MUSL.test(name))
|
|
2411
|
+
return musl ? 0 : 2;
|
|
2412
|
+
return 1;
|
|
2413
|
+
}
|
|
2414
|
+
function pickAsset(assets, platform, wanted) {
|
|
2415
|
+
const builds = assets.filter((asset) => !NOT_A_BUILD.test(asset.name));
|
|
2416
|
+
const listed = (list) => list.map((asset) => asset.name).join(", ");
|
|
2417
|
+
if (wanted !== undefined) {
|
|
2418
|
+
const glob = new Bun.Glob(wanted);
|
|
2419
|
+
const matches = (asset) => wanted.includes("*") ? glob.match(asset.name) : asset.name.includes(wanted);
|
|
2420
|
+
const named = builds.some(matches) ? builds.filter(matches) : assets.filter(matches);
|
|
2421
|
+
if (named.length === 1)
|
|
2422
|
+
return named[0];
|
|
2423
|
+
return fail(named.length === 0 ? `no asset matches --asset ${wanted}: ${listed(builds)}` : `several assets match --asset ${wanted}: ${listed(named)}`, 1);
|
|
2424
|
+
}
|
|
2425
|
+
const osWord = OS_WORDS[platform.os];
|
|
2426
|
+
const archWord = ARCH_WORDS[platform.arch];
|
|
2427
|
+
const namesOs = builds.filter((asset) => Object.values(OS_WORDS).some((word) => word.test(asset.name)));
|
|
2428
|
+
let fit = namesOs.length === 0 ? builds : builds.filter((asset) => osWord?.test(asset.name) === true);
|
|
2429
|
+
const namesArch = fit.filter((asset) => Object.values(ARCH_WORDS).some((word) => word.test(asset.name)));
|
|
2430
|
+
fit = namesArch.length === 0 ? fit : fit.filter((asset) => archWord?.test(asset.name) === true || ANY_ARCH.test(asset.name));
|
|
2431
|
+
if (platform.musl)
|
|
2432
|
+
fit = fit.filter((asset) => !GNU.test(asset.name));
|
|
2433
|
+
if (fit.length === 0)
|
|
2434
|
+
return fail(`no asset is built for ${platform.os} ${platform.arch}${platform.musl ? " musl" : ""}: ${listed(builds)}`, 1, "pick one with --asset <part of its name>");
|
|
2435
|
+
fit = rank(fit, (asset) => libcRank(asset.name, platform.musl));
|
|
2436
|
+
fit = rank(fit, (asset) => ARCH_WORDS[platform.arch]?.test(asset.name) === true ? 0 : 1);
|
|
2437
|
+
fit = rank(fit, (asset) => {
|
|
2438
|
+
const format = FORMATS.findIndex((each) => each.test(asset.name));
|
|
2439
|
+
return format === -1 ? FORMATS.length : format;
|
|
2440
|
+
});
|
|
2441
|
+
return fit.length === 1 ? fit[0] : fail(`several assets fit ${platform.os} ${platform.arch}: ${listed(fit)}`, 1, "pick one with --asset <part of its name>");
|
|
2442
|
+
}
|
|
2443
|
+
function signatureOf(assets, target, key) {
|
|
2444
|
+
const suffixes = { gpg: [".asc", ".sig", ".gpg"], minisign: [".minisig"], cosign: [".sig"] }[key.tool];
|
|
2445
|
+
return suffixes.map((suffix) => assets.find((asset) => asset.name === `${target}${suffix}`)).find((asset) => asset !== undefined);
|
|
2446
|
+
}
|
|
2447
|
+
async function resolveRelease(spec, options) {
|
|
2448
|
+
const release = await pickRelease(spec, options.fresh);
|
|
2449
|
+
const asset = pickAsset(release.assets, options.platform ?? thisPlatform(), options.asset);
|
|
2450
|
+
const own = release.assets.find((each) => each.name.startsWith(`${asset.name}.sha256`));
|
|
2451
|
+
const sums = own ?? release.assets.find((each) => SUMS.test(each.name));
|
|
2452
|
+
const digest = DIGEST.exec(asset.digest ?? "")?.[1];
|
|
2453
|
+
const signature = options.key === undefined ? undefined : signatureOf(release.assets, (sums ?? asset).name, options.key);
|
|
2454
|
+
if (options.key !== undefined && signature === undefined)
|
|
2455
|
+
fail(`${specName(spec)} ${release.tag} ships no ${options.key.tool} signature of ${(sums ?? asset).name}`, 1);
|
|
2456
|
+
return {
|
|
2457
|
+
spec: specName(spec),
|
|
2458
|
+
...spec.tag === undefined ? {} : { pinned: `${specName(spec)}@${spec.tag}` },
|
|
2459
|
+
tag: release.tag,
|
|
2460
|
+
published: release.published,
|
|
2461
|
+
asset,
|
|
2462
|
+
...sums === undefined ? {} : { sums: sums.url },
|
|
2463
|
+
...digest === undefined ? {} : { digest },
|
|
2464
|
+
...signature === undefined ? {} : { sig: signature.url }
|
|
2465
|
+
};
|
|
2466
|
+
}
|
|
2467
|
+
function assertReleaseOptions(isRelease, values) {
|
|
2468
|
+
if (!isRelease && (values.fresh === true || values.asset !== undefined))
|
|
2469
|
+
badUsage("--fresh and --asset go with a release, gh:owner/repo or fj:owner/repo");
|
|
2470
|
+
}
|
|
2471
|
+
var SPEC, MIN_AGE, DIGEST, NOT_A_BUILD, SUMS, OS_WORDS, ARCH_WORDS, ANY_ARCH, GNU, MUSL, FORMATS;
|
|
2472
|
+
var init_release = __esm(() => {
|
|
2473
|
+
init_src();
|
|
2474
|
+
SPEC = /^(gh|fj):([\w.-]+)\/([\w.-]+)(?:@(\S+))?$/;
|
|
2475
|
+
MIN_AGE = 14 * 24 * 3600000;
|
|
2476
|
+
DIGEST = /^sha256:([0-9a-f]{64})$/;
|
|
2477
|
+
NOT_A_BUILD = /\.(?:sha256(?:sum)?|sha512(?:sum)?|md5|asc|sig|minisig|pem|crt|cert|sbom|spdx|cdx|json|jsonl|txt|deb|rpm|apk|msi|dmg|pkg|sh)$|(?:checksums?|sums?)$/i;
|
|
2478
|
+
SUMS = /(?:^|[-_.])(?:sha256sums?|checksums?)(?:\.txt)?$/i;
|
|
2479
|
+
OS_WORDS = {
|
|
2480
|
+
linux: /linux/i,
|
|
2481
|
+
darwin: /darwin|mac-?os|apple|osx/i,
|
|
2482
|
+
win32: /windows|(?<![a-z])win(?:32|64)?(?=[-_.]|$)/i
|
|
2483
|
+
};
|
|
2484
|
+
ARCH_WORDS = {
|
|
2485
|
+
x64: /x86[-_]64|amd64|x64(?!\d)/i,
|
|
2486
|
+
arm64: /aarch64|arm64/i
|
|
2487
|
+
};
|
|
2488
|
+
ANY_ARCH = /universal/i;
|
|
2489
|
+
GNU = /gnu|glibc/i;
|
|
2490
|
+
MUSL = /musl/i;
|
|
2491
|
+
FORMATS = [/\.(?:tar\.gz|tgz)$/i, /\.tar\.xz$/i, /\.tar\.(?:zst|bz2)$/i, /\.zip$/i];
|
|
2492
|
+
});
|
|
2493
|
+
|
|
2494
|
+
// src/script.ts
|
|
2495
|
+
function summarize(script) {
|
|
2496
|
+
const findings = [];
|
|
2497
|
+
const env = new Set;
|
|
2498
|
+
for (const [index, text] of script.split(`
|
|
2499
|
+
`).entries()) {
|
|
2500
|
+
if (COMMENT.test(text))
|
|
2501
|
+
continue;
|
|
2502
|
+
const does = PATTERNS.filter(([, pattern]) => pattern.test(text)).map(([word]) => word);
|
|
2503
|
+
if (does.length > 0)
|
|
2504
|
+
findings.push({ line: index + 1, does: does.join(", "), text: text.trim() });
|
|
2505
|
+
for (const [, name] of text.matchAll(VARIABLE)) {
|
|
2506
|
+
if (UPPER_CASE.test(name) && !SHELL_OWN.has(name))
|
|
2507
|
+
env.add(name);
|
|
2508
|
+
}
|
|
2509
|
+
}
|
|
2510
|
+
return { findings, env: [...env].sort() };
|
|
2511
|
+
}
|
|
2512
|
+
var PATTERNS, COMMENT, VARIABLE, UPPER_CASE, SHELL_OWN;
|
|
2513
|
+
var init_script = __esm(() => {
|
|
2514
|
+
PATTERNS = [
|
|
2515
|
+
["fetches", /\b(?:curl|wget)\b|https?:\/\//],
|
|
2516
|
+
["sudo", /\b(?:sudo|doas)\b/],
|
|
2517
|
+
["removes", /\brm\s+-[a-z]*[rf]/i],
|
|
2518
|
+
["profile", /\.(?:bashrc|bash_profile|zshrc|zprofile|zshenv|profile)\b|\.config\/fish\b/],
|
|
2519
|
+
["system", /(?:^|[\s"'=:])\/(?:usr|etc|opt|bin|sbin|lib)\//],
|
|
2520
|
+
["runs", /\|\s*(?:sudo\s+)?(?:ba|z|da)?sh\b|\beval\b/]
|
|
2521
|
+
];
|
|
2522
|
+
COMMENT = /^\s*#/;
|
|
2523
|
+
VARIABLE = /\$\{?([A-Z_]\w*)/gi;
|
|
2524
|
+
UPPER_CASE = /^[A-Z_][A-Z0-9_]*$/;
|
|
2525
|
+
SHELL_OWN = new Set(["HOME", "PATH", "PWD", "OLDPWD", "SHELL", "USER", "IFS", "TERM", "LINENO", "RANDOM", "UID", "EUID", "BASH_SOURCE", "BASH_VERSION", "ZSH_VERSION"]);
|
|
2526
|
+
});
|
|
2527
|
+
|
|
2528
|
+
// src/signature.ts
|
|
2529
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync5, mkdtempSync, readFileSync as readFileSync6, rmSync as rmSync4, statSync as statSync5, writeFileSync as writeFileSync2 } from "fs";
|
|
2530
|
+
import { tmpdir } from "os";
|
|
2531
|
+
import { join as join10 } from "path";
|
|
2532
|
+
function toolOfFile(path) {
|
|
2533
|
+
const bytes = readFileSync6(path);
|
|
2534
|
+
const text = bytes.subarray(0, 4096).toString("latin1");
|
|
2535
|
+
if (text.includes("-----BEGIN PGP PUBLIC KEY BLOCK-----") || ((bytes[0] ?? 0) & 128) !== 0)
|
|
2536
|
+
return "gpg";
|
|
2537
|
+
if (text.includes("minisign public key"))
|
|
2538
|
+
return "minisign";
|
|
2539
|
+
return text.includes("-----BEGIN PUBLIC KEY-----") ? "cosign" : undefined;
|
|
2540
|
+
}
|
|
2541
|
+
function readKey(key) {
|
|
2542
|
+
const fingerprint = key.replace(SPACES2, "").toUpperCase();
|
|
2543
|
+
let found;
|
|
2544
|
+
if (FINGERPRINT.test(fingerprint)) {
|
|
2545
|
+
found = { tool: "gpg", fingerprint };
|
|
2546
|
+
} else if (MINISIGN_KEY.test(key)) {
|
|
2547
|
+
found = { tool: "minisign", minisignKey: key };
|
|
2548
|
+
} else if (existsSync7(key) && statSync5(key).isFile()) {
|
|
2549
|
+
const tool = toolOfFile(key) ?? badUsage(`--key ${key} is no OpenPGP, minisign or cosign public key`);
|
|
2550
|
+
found = { tool, file: key };
|
|
2551
|
+
} else {
|
|
2552
|
+
return badUsage(`--key takes a gpg fingerprint, a minisign key or a public key file, not '${key}'`);
|
|
2553
|
+
}
|
|
2554
|
+
if (Bun.which(found.tool) === null)
|
|
2555
|
+
fail(`--key is a ${found.tool} key and ${found.tool} is not on PATH`, 1, `install it: ${GET[found.tool]}`);
|
|
2556
|
+
return found;
|
|
2557
|
+
}
|
|
2558
|
+
function statusFields(status, keyword) {
|
|
2559
|
+
const line = status.split(`
|
|
2560
|
+
`).find((each) => each.startsWith(`[GNUPG:] ${keyword} `));
|
|
2561
|
+
return line?.split(" ").slice(2);
|
|
2562
|
+
}
|
|
2563
|
+
async function gpgVerify(key, signature, signed, work) {
|
|
2564
|
+
const dir = join10(work, "gnupg");
|
|
2565
|
+
const home = key.file === undefined ? [] : ["--homedir", dir];
|
|
2566
|
+
if (key.file !== undefined) {
|
|
2567
|
+
mkdirSync5(dir, { mode: 448 });
|
|
2568
|
+
const imported = await runTool("gpg --import", ["gpg", "--batch", ...home, "--import", key.file]);
|
|
2569
|
+
if (imported.code !== 0)
|
|
2570
|
+
fail(`gpg could not import ${key.file}:
|
|
2571
|
+
${imported.stderr.trim()}`, 1);
|
|
2572
|
+
}
|
|
2573
|
+
const verified = await runTool("gpg --verify", ["gpg", "--batch", ...home, "--status-fd", "1", "--verify", signature, signed]);
|
|
2574
|
+
const valid = statusFields(verified.stdout, "VALIDSIG");
|
|
2575
|
+
const by = [valid?.[0], valid?.at(-1)].filter((each) => each !== undefined).map((each) => each.toUpperCase());
|
|
2576
|
+
if (verified.code !== 0 || statusFields(verified.stdout, "GOODSIG") === undefined || valid === undefined)
|
|
2577
|
+
fail(`the gpg signature does not verify:
|
|
2578
|
+
${verified.stderr.trim()}`, 1);
|
|
2579
|
+
if (key.fingerprint !== undefined && !by.includes(key.fingerprint))
|
|
2580
|
+
fail(`the gpg signature is by ${by.at(-1)}, not ${key.fingerprint}`, 1);
|
|
2581
|
+
return `gpg, by ${by.at(-1)}`;
|
|
2582
|
+
}
|
|
2583
|
+
async function toolVerify(key, signature, signed) {
|
|
2584
|
+
const argv = key.tool === "minisign" ? ["minisign", "-V", "-q", "-m", signed, "-x", signature, ...key.file === undefined ? ["-P", key.minisignKey] : ["-p", key.file]] : ["cosign", "verify-blob", "--key", key.file, "--signature", signature, signed];
|
|
2585
|
+
const verified = await runTool(`${key.tool} verify`, argv);
|
|
2586
|
+
if (verified.code !== 0)
|
|
2587
|
+
fail(`the ${key.tool} signature does not verify:
|
|
2588
|
+
${`${verified.stderr}${verified.stdout}`.trim()}`, 1);
|
|
2589
|
+
return key.tool;
|
|
2590
|
+
}
|
|
2591
|
+
async function verifySignature(signed, url, key) {
|
|
2592
|
+
const work = mkdtempSync(join10(tmpdir(), "dl-sig-"));
|
|
2593
|
+
try {
|
|
2594
|
+
const signature = join10(work, "signature");
|
|
2595
|
+
const data = typeof signed === "string" ? signed : join10(work, "signed");
|
|
2596
|
+
writeFileSync2(signature, await smallFile(url));
|
|
2597
|
+
if (typeof signed !== "string")
|
|
2598
|
+
writeFileSync2(data, signed);
|
|
2599
|
+
return key.tool === "gpg" ? await gpgVerify(key, signature, data, work) : await toolVerify(key, signature, data);
|
|
2600
|
+
} finally {
|
|
2601
|
+
if (existsSync7(join10(work, "gnupg")))
|
|
2602
|
+
await runTool("gpgconf --kill", ["gpgconf", "--homedir", join10(work, "gnupg"), "--kill", "all"]);
|
|
2603
|
+
rmSync4(work, { recursive: true, force: true });
|
|
2604
|
+
}
|
|
2605
|
+
}
|
|
2606
|
+
var FINGERPRINT, SPACES2, MINISIGN_KEY, GET;
|
|
2607
|
+
var init_signature = __esm(() => {
|
|
2608
|
+
init_src();
|
|
2609
|
+
init_download();
|
|
2610
|
+
FINGERPRINT = /^(?:[0-9A-F]{40}|[0-9A-F]{64})$/;
|
|
2611
|
+
SPACES2 = /\s+/g;
|
|
2612
|
+
MINISIGN_KEY = /^RW[A-Za-z0-9+/]{54}$/;
|
|
2613
|
+
GET = {
|
|
2614
|
+
gpg: "the gnupg package of the system",
|
|
2615
|
+
minisign: "https://jedisct1.github.io/minisign/",
|
|
2616
|
+
cosign: "https://docs.sigstore.dev/cosign/system_config/installation/"
|
|
2617
|
+
};
|
|
2618
|
+
});
|
|
2619
|
+
|
|
2620
|
+
// src/sums.ts
|
|
2621
|
+
import { basename as basename4 } from "path";
|
|
2622
|
+
function pathUnder(sumsUrl, url) {
|
|
2623
|
+
const sums = new URL(sumsUrl);
|
|
2624
|
+
const file = new URL(url);
|
|
2625
|
+
const folder = sums.pathname.slice(0, sums.pathname.lastIndexOf("/") + 1);
|
|
2626
|
+
return sums.origin === file.origin && file.pathname.startsWith(folder) ? decoded2(file.pathname.slice(folder.length)) : undefined;
|
|
2627
|
+
}
|
|
2628
|
+
function decoded2(path) {
|
|
2629
|
+
try {
|
|
2630
|
+
return decodeURIComponent(path);
|
|
2631
|
+
} catch {
|
|
2632
|
+
return path;
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
function sumFor(text, name, path) {
|
|
2636
|
+
const entries = [];
|
|
2637
|
+
for (const line of text.split(`
|
|
2638
|
+
`).map((line) => line.trim())) {
|
|
2639
|
+
const gnu = GNU_LINE.exec(line);
|
|
2640
|
+
const bsd = gnu === null ? BSD_LINE.exec(line) : null;
|
|
2641
|
+
if (gnu !== null)
|
|
2642
|
+
entries.push([gnu[1], gnu[2]]);
|
|
2643
|
+
else if (bsd !== null)
|
|
2644
|
+
entries.push([bsd[2], bsd[1]]);
|
|
2645
|
+
}
|
|
2646
|
+
const exact = path === undefined ? undefined : entries.find(([, file]) => file?.replace(DOT_SLASH, "") === path);
|
|
2647
|
+
if (exact !== undefined)
|
|
2648
|
+
return exact[0].toLowerCase();
|
|
2649
|
+
const named = entries.filter(([, file]) => file !== undefined && basename4(file) === name);
|
|
2650
|
+
const hashes = new Set(named.map(([hash]) => hash.toLowerCase()));
|
|
2651
|
+
if (hashes.size > 1)
|
|
2652
|
+
fail(`the checksums file lists ${name} as ${named.map(([, file]) => file).join(", ")}, none at the download's path`, 1);
|
|
2653
|
+
if (named[0] !== undefined)
|
|
2654
|
+
return named[0][0].toLowerCase();
|
|
2655
|
+
const [only] = entries;
|
|
2656
|
+
return entries.length === 1 && only[1] === undefined ? only[0].toLowerCase() : undefined;
|
|
2657
|
+
}
|
|
2658
|
+
async function fetchSums(url) {
|
|
2659
|
+
return smallFile(url);
|
|
2660
|
+
}
|
|
2661
|
+
function sumIn(sums, url, fileUrl, name) {
|
|
2662
|
+
return sumFor(new TextDecoder().decode(sums), name, pathUnder(url, fileUrl)) ?? fail(`${url} holds no sha256 for ${name}`, 1);
|
|
2663
|
+
}
|
|
2664
|
+
var GNU_LINE, BSD_LINE, DOT_SLASH;
|
|
2665
|
+
var init_sums = __esm(() => {
|
|
2666
|
+
init_src();
|
|
2667
|
+
init_download();
|
|
2668
|
+
GNU_LINE = /^([0-9a-f]{64})(?:\s+\*?(\S.*))?$/i;
|
|
2669
|
+
BSD_LINE = /^SHA256 \((.+)\) = ([0-9a-f]{64})$/i;
|
|
2670
|
+
DOT_SLASH = /^\.\//;
|
|
2671
|
+
});
|
|
2672
|
+
|
|
2673
|
+
// src/get.ts
|
|
2674
|
+
var exports_get = {};
|
|
2675
|
+
__export(exports_get, {
|
|
2676
|
+
DEFAULT_MAX_SIZE: () => DEFAULT_MAX_SIZE,
|
|
2677
|
+
get: () => get
|
|
2678
|
+
});
|
|
2679
|
+
import { chmodSync as chmodSync2, existsSync as existsSync8, mkdirSync as mkdirSync6, mkdtempSync as mkdtempSync2, rmSync as rmSync5 } from "fs";
|
|
2680
|
+
import { tmpdir as tmpdir2 } from "os";
|
|
2681
|
+
import { basename as basename5, extname, join as join11, resolve as resolve5 } from "path";
|
|
2682
|
+
import process22 from "process";
|
|
2683
|
+
async function get(args) {
|
|
2684
|
+
const { values, positionals: [given], rest = [] } = parse(args, USAGE, OPTIONS, {
|
|
2685
|
+
positionals: ["<url>"],
|
|
2686
|
+
rest: true,
|
|
2687
|
+
exits: EXITS,
|
|
2688
|
+
replaces: "curl -fsSL <url> | sh, curl -LO then sha256sum -c by hand, and unpacking a release to copy its binary into ~/.local/bin",
|
|
2689
|
+
examples: [
|
|
2690
|
+
["dl https://bun.sh/install", "download it to read it"],
|
|
2691
|
+
["dl https://bun.sh/install --exec --sha256 <sha>", "run the script that was read"],
|
|
2692
|
+
["dl https://example.com/releases/tool-linux-amd64 --sums https://example.com/releases/SHA256SUMS --bin tool", "a checked binary, installed"],
|
|
2693
|
+
["dl https://example.com/tool.tar.gz -x", "download and unpack"],
|
|
2694
|
+
["dl https://example.com/tool.tar.gz --sums https://example.com/SHA256SUMS --sig https://example.com/SHA256SUMS.asc --key <fingerprint>", "checked against checksums its publisher signed"],
|
|
2695
|
+
["dl gh:BurntSushi/ripgrep --bin rg", "the build of the latest release for this machine, installed"]
|
|
2696
|
+
]
|
|
2697
|
+
});
|
|
2698
|
+
const spec = parseSpec(given);
|
|
2699
|
+
assertReleaseOptions(spec !== undefined, values);
|
|
2700
|
+
if (spec === undefined && (!URL.canParse(given) || !["http:", "https:"].includes(new URL(given).protocol)))
|
|
2701
|
+
badUsage(`'${given}' is not an http or https URL, nor a release as gh:owner/repo or fj:owner/repo`);
|
|
2702
|
+
if (values.sha256 !== undefined && !SHA256.test(values.sha256))
|
|
2703
|
+
badUsage(`--sha256 takes 64 hex digits, not '${values.sha256}'`);
|
|
2704
|
+
if (values.yes === true && values.exec !== true)
|
|
2705
|
+
badUsage("--yes goes with --exec");
|
|
2706
|
+
if (values.force === true && values.bin === undefined)
|
|
2707
|
+
badUsage("--force goes with --bin");
|
|
2708
|
+
if (rest.length > 0 && values.exec !== true)
|
|
2709
|
+
badUsage("arguments after -- go to an --exec script");
|
|
2710
|
+
if (values.bin !== undefined && (values.bin.includes("/") || values.bin === "." || values.bin === ".."))
|
|
2711
|
+
badUsage(`--bin takes a command name, not '${values.bin}'`);
|
|
2712
|
+
if (spec === undefined ? values.sig === undefined !== (values.key === undefined) : values.sig !== undefined && values.key === undefined)
|
|
2713
|
+
badUsage(spec === undefined ? "--sig and --key go together" : "--sig goes with --key");
|
|
2714
|
+
if (spec !== undefined && values.key !== undefined && values.sig === undefined && (values.sha256 !== undefined || values.sums !== undefined))
|
|
2715
|
+
badUsage("--key alone checks the release's own checksums file, which --sha256 and --sums replace: give --sig with it");
|
|
2716
|
+
if (values.sig !== undefined && (!URL.canParse(values.sig) || !["http:", "https:"].includes(new URL(values.sig).protocol)))
|
|
2717
|
+
badUsage(`--sig takes an http or https URL, not '${values.sig}'`);
|
|
2718
|
+
const key = values.key === undefined ? undefined : readKey(values.key);
|
|
2719
|
+
const maxSize = parseSize(values["max-size"] ?? DEFAULT_MAX_SIZE) ?? badUsage(`--max-size takes a size such as 500M or 2G, not '${values["max-size"]}'`);
|
|
2720
|
+
const release = spec === undefined ? undefined : await resolveRelease(spec, { fresh: values.fresh === true, asset: values.asset, key });
|
|
2721
|
+
const url = release?.asset.url ?? given;
|
|
2722
|
+
const pinned = values.sha256 !== undefined || values.sums !== undefined;
|
|
2723
|
+
const sums = values.sums ?? (pinned ? undefined : release?.sums);
|
|
2724
|
+
const digest = pinned ? undefined : release?.digest;
|
|
2725
|
+
const sig = values.sig ?? release?.sig;
|
|
2726
|
+
const created = values.output === undefined;
|
|
2727
|
+
const dir = created ? mkdtempSync2(join11(tmpdir2(), "dl-")) : resolve5(values.output);
|
|
2728
|
+
mkdirSync6(dir, { recursive: true });
|
|
2729
|
+
const expectsFile = release !== undefined || values.exec === true || values.bin !== undefined || values.extract === true;
|
|
2730
|
+
const { file, verified, signature } = await fetchChecked(url, dir, created, { maxSize, expectsFile, sha256: values.sha256?.toLowerCase(), sums, digest, sig, key });
|
|
2731
|
+
if (release !== undefined && !verified)
|
|
2732
|
+
warn(`${release.spec} ${release.tag} ships no checksums file and its forge gives no sha256 of ${release.asset.name}, so nothing checked it`);
|
|
2733
|
+
const last = lastSeen(url);
|
|
2734
|
+
const report = { path: file.path, size: file.size, url: file.url, type: file.type, sha256: file.sha256, verified, ...signature === undefined ? {} : { signature }, ...release === undefined ? {} : { release: releaseLine(release) }, seen: "first download" };
|
|
2735
|
+
if (last !== undefined && last.seen.sha256 === file.sha256)
|
|
2736
|
+
report.seen = `same as the download of ${formatAge(last.seen.at)}`;
|
|
2737
|
+
else if (last !== undefined)
|
|
2738
|
+
report.seen = `changed since the download of ${formatAge(last.seen.at)}, was ${last.seen.sha256.slice(0, 12)}`;
|
|
2739
|
+
if (last?.content !== undefined && last.seen.sha256 !== file.sha256 && file.text)
|
|
2740
|
+
report.diff = await diff(last.content, file);
|
|
2741
|
+
remember(url, file);
|
|
2742
|
+
const extracted = values.extract === true || values.bin !== undefined && archiveSuffix(file.name) !== undefined;
|
|
2743
|
+
if (extracted)
|
|
2744
|
+
report.extracted = await extract(file);
|
|
2745
|
+
if (values.bin !== undefined) {
|
|
2746
|
+
const source = report.extracted === undefined ? file.path : await pickBinary(report.extracted, values.bin === "" ? undefined : values.bin);
|
|
2747
|
+
const name = values.bin === "" ? basename5(source) : values.bin;
|
|
2748
|
+
report.installed = installBinary(source, name, values.force === true);
|
|
2749
|
+
record({ kind: "bin", name, url, sha256: file.sha256, path: report.installed, at: new Date().toISOString(), ...release === undefined ? checkedBy(file, values) : fromRelease(release, values) });
|
|
2750
|
+
}
|
|
2751
|
+
if (values.exec === true)
|
|
2752
|
+
report.script = summarize(await Bun.file(file.path).text());
|
|
2753
|
+
print(report, given, values.json === true);
|
|
2754
|
+
if (values.exec !== true)
|
|
2755
|
+
return 0;
|
|
2756
|
+
if (!verified && values.yes !== true)
|
|
2757
|
+
return fail("not run: no --sha256, --sums or --sig pins this script", 1, `read ${file.path}, then: dl ${url} --exec --sha256 ${file.sha256}`);
|
|
2758
|
+
return runScript(file, url, rest, checkedBy(file, values));
|
|
2759
|
+
}
|
|
2760
|
+
function releaseLine(release) {
|
|
2761
|
+
return `${release.spec} ${release.tag}, published ${formatAge(release.published)}, ${release.asset.name}`;
|
|
2762
|
+
}
|
|
2763
|
+
function fromRelease(release, values) {
|
|
2764
|
+
const key = values.key !== undefined && existsSync8(values.key) ? resolve5(values.key) : values.key;
|
|
2765
|
+
return { release: release.pinned ?? release.spec, version: release.tag, released: release.published, ...values.asset === undefined ? {} : { asset: values.asset }, ...key === undefined ? {} : { key } };
|
|
2766
|
+
}
|
|
2767
|
+
function checkedBy(file, values) {
|
|
2768
|
+
const key = values.key !== undefined && existsSync8(values.key) ? resolve5(values.key) : values.key;
|
|
2769
|
+
const fields = { sums: values.sums, sig: values.sig, key, etag: file.etag, lastModified: file.lastModified };
|
|
2770
|
+
return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
|
|
2771
|
+
}
|
|
2772
|
+
function listedSum(sums, checks, url, name, signed) {
|
|
2773
|
+
if (sums === undefined)
|
|
2774
|
+
return;
|
|
2775
|
+
return checks.digest !== undefined && !signed ? sumFor(new TextDecoder().decode(sums), name, pathUnder(checks.sums, url)) : sumIn(sums, checks.sums, url, name);
|
|
2776
|
+
}
|
|
2777
|
+
async function fetchChecked(url, dir, created, checks) {
|
|
2778
|
+
let file;
|
|
2779
|
+
try {
|
|
2780
|
+
file = await download(url, dir, checks.maxSize);
|
|
2781
|
+
if (file.html && (checks.expectsFile || !HTML_EXTENSIONS.has(extname(file.name).toLowerCase())))
|
|
2782
|
+
fail(`${url} answered an HTML page, not a file`, 1);
|
|
2783
|
+
const sums = checks.sums === undefined ? undefined : await fetchSums(checks.sums);
|
|
2784
|
+
const signed = checks.sig === undefined || checks.key === undefined ? undefined : await verifySignature(sums ?? file.path, checks.sig, checks.key);
|
|
2785
|
+
const expected = checks.sha256 ?? listedSum(sums, checks, url, file.name, signed !== undefined) ?? checks.digest;
|
|
2786
|
+
if (expected !== undefined && expected !== file.sha256)
|
|
2787
|
+
fail(`sha256 mismatch for ${file.name}: expected ${expected}, got ${file.sha256}; the file was deleted`, 1);
|
|
2788
|
+
return { file, verified: expected !== undefined || signed !== undefined, ...signed === undefined ? {} : { signature: signed } };
|
|
2789
|
+
} catch (error) {
|
|
2790
|
+
if (file !== undefined)
|
|
2791
|
+
rmSync5(file.path, { force: true });
|
|
2792
|
+
if (created)
|
|
2793
|
+
rmSync5(dir, { recursive: true, force: true });
|
|
2794
|
+
throw error;
|
|
2795
|
+
}
|
|
2796
|
+
}
|
|
2797
|
+
async function diff(last, file) {
|
|
2798
|
+
if (Bun.which("git") === null)
|
|
2799
|
+
return "";
|
|
2800
|
+
const child = Bun.spawn(["git", "diff", "--no-index", "--no-color", "--", last, file.path], { stdin: "ignore", stdout: "pipe", stderr: "ignore" });
|
|
2801
|
+
const lines = (await child.stdout.text()).trimEnd().split(`
|
|
2802
|
+
`);
|
|
2803
|
+
await child.exited;
|
|
2804
|
+
const hunks = lines.findIndex((line) => line.startsWith("@@"));
|
|
2805
|
+
return hunks === -1 ? "" : ["--- last", `+++ ${file.name}`, ...lines.slice(hunks)].join(`
|
|
2806
|
+
`);
|
|
2807
|
+
}
|
|
2808
|
+
function coloredDiff(text) {
|
|
2809
|
+
const colors = paint(process22.stdout);
|
|
2810
|
+
return text.split(`
|
|
2811
|
+
`).map((raw, index) => {
|
|
2812
|
+
const line = escapeControls(raw);
|
|
2813
|
+
if (index < 2)
|
|
2814
|
+
return colors.bold(line);
|
|
2815
|
+
if (line.startsWith("@@"))
|
|
2816
|
+
return colors.cyan(line);
|
|
2817
|
+
if (line.startsWith("+"))
|
|
2818
|
+
return colors.green(line);
|
|
2819
|
+
return line.startsWith("-") ? colors.red(line) : line;
|
|
2820
|
+
}).join(`
|
|
2821
|
+
`);
|
|
2822
|
+
}
|
|
2823
|
+
async function extract(file) {
|
|
2824
|
+
const suffix = archiveSuffix(file.name) ?? fail(`${file.name} is no archive arc can extract`, 1);
|
|
2825
|
+
const folder = join11(file.path, "..", file.name.slice(0, -suffix.length) || "extracted");
|
|
2826
|
+
if (existsSync8(folder))
|
|
2827
|
+
return fail(`'${folder}' already exists`, 1);
|
|
2828
|
+
mkdirSync6(folder);
|
|
2829
|
+
return await extractArchive(file.path, folder) !== 0 ? fail(`extracting ${file.name} failed`, 1) : folder;
|
|
2830
|
+
}
|
|
2831
|
+
function print(report, url, json) {
|
|
2832
|
+
if (json) {
|
|
2833
|
+
printJson(report);
|
|
2834
|
+
return;
|
|
2835
|
+
}
|
|
2836
|
+
const rows = [
|
|
2837
|
+
["path", report.path],
|
|
2838
|
+
["size", formatSize(report.size)],
|
|
2839
|
+
...report.url === url ? [] : [["url", report.url]],
|
|
2840
|
+
["type", report.type === "" ? "-" : report.type],
|
|
2841
|
+
...report.release === undefined ? [] : [["release", report.release]],
|
|
2842
|
+
["sha256", `${report.sha256}${report.verified ? " verified" : ""}`],
|
|
2843
|
+
...report.signature === undefined ? [] : [["signature", `${report.signature}, verified`]],
|
|
2844
|
+
["seen", report.seen],
|
|
2845
|
+
...report.extracted === undefined ? [] : [["extracted", report.extracted]],
|
|
2846
|
+
...report.installed === undefined ? [] : [["installed", report.installed]],
|
|
2847
|
+
...report.installed === undefined || binDirOnPath() ? [] : [["note", `${binDir()} is not on PATH`]]
|
|
2848
|
+
];
|
|
2849
|
+
console.log(table(rows.map(([name = "", value = ""]) => [name, escapeControls(value)])));
|
|
2850
|
+
if (report.diff !== undefined && report.diff !== "")
|
|
2851
|
+
console.log(`
|
|
2852
|
+
${coloredDiff(report.diff)}`);
|
|
2853
|
+
if (report.script === undefined)
|
|
2854
|
+
return;
|
|
2855
|
+
const { findings, env } = report.script;
|
|
2856
|
+
console.log(findings.length === 0 ? `
|
|
2857
|
+
script: fetches, sudo, removes, profile, system and runs found nowhere` : `
|
|
2858
|
+
script:
|
|
2859
|
+
${table(findings.map(({ line, does, text }) => [`line ${line}`, does, truncate(escapeControls(text), LINE_WIDTH)]))}`);
|
|
2860
|
+
if (env.length > 0)
|
|
2861
|
+
console.log(`reads: ${env.join(", ")}`);
|
|
2862
|
+
}
|
|
2863
|
+
async function runScript(file, url, args, checked) {
|
|
2864
|
+
const shebang = (await Bun.file(file.path).text()).startsWith("#!");
|
|
2865
|
+
chmodSync2(file.path, 448);
|
|
2866
|
+
const code = await Bun.spawn(shebang ? [file.path, ...args] : ["sh", file.path, ...args], { stdin: "inherit", stdout: "inherit", stderr: "inherit" }).exited;
|
|
2867
|
+
if (code !== 0)
|
|
2868
|
+
return fail(`the script exited ${code}`, 1);
|
|
2869
|
+
const { host, pathname } = new URL(url);
|
|
2870
|
+
record({ kind: "script", name: `${host}${pathname}`, url, sha256: file.sha256, at: new Date().toISOString(), ...checked, ...args.length > 0 ? { args } : {} });
|
|
2871
|
+
return 0;
|
|
2872
|
+
}
|
|
2873
|
+
var USAGE = `dl [options] <url> [-- <script args>]: downloads a file into a new folder of its own, checks its sha256, then extracts it, installs it as a command or runs it as a script
|
|
2874
|
+
|
|
2875
|
+
<url> is an http or https URL, or a release: gh:owner/repo on GitHub, fj:owner/repo on git.kaynooo.fr, with @tag for one release. A release is the newest at least two weeks old unless --fresh; its asset the one built for this OS and arch, or the one --asset names; it is checked against the checksums file the release ships, else the sha256 the forge gives, and --key alone finds the signature beside it.
|
|
2876
|
+
Without -o the file lands in a new folder under the temp folder. It prints where the file went, its size, final URL, type and sha256, and how it compares with the last download of the same URL (a changed text file shows its diff).
|
|
2877
|
+
An HTML page arriving where a file was expected fails, as does a download over --max-size.
|
|
2878
|
+
--sig checks a detached signature with --key: of the file, or of the checksums file when --sums names one. A gpg key is a fingerprint of your keyring or a key file, a minisign key its string or file, a cosign key its PEM file; the tool has to be on PATH.
|
|
2879
|
+
--exec lists what the script does and runs it only when --sha256, --sums or --sig pins it, or with --yes; arguments after -- go to the script.
|
|
2880
|
+
--bin and --exec record what they installed or ran in the ledger dl ls lists.`, EXITS, OPTIONS, SHA256, DEFAULT_MAX_SIZE = "2G", HTML_EXTENSIONS, LINE_WIDTH = 120;
|
|
2881
|
+
var init_get = __esm(() => {
|
|
2882
|
+
init_extract();
|
|
2883
|
+
init_src();
|
|
2884
|
+
init_download();
|
|
2885
|
+
init_install();
|
|
2886
|
+
init_release();
|
|
2887
|
+
init_script();
|
|
2888
|
+
init_signature();
|
|
2889
|
+
init_state();
|
|
2890
|
+
init_sums();
|
|
2891
|
+
EXITS = [
|
|
2892
|
+
[0, "downloaded, and extracted, installed or run as asked"],
|
|
2893
|
+
[1, "an unreachable URL, an error status, a release with no asset for this machine, a sha256 mismatch, a signature that does not verify or a missing tool to check it, an HTML page in place of a file, a download over --max-size, a script nothing pins, or one that failed"],
|
|
2894
|
+
[2, "a usage error"]
|
|
2895
|
+
];
|
|
2896
|
+
OPTIONS = {
|
|
2897
|
+
output: { type: "string", short: "o", description: "the folder to download into, created if missing, instead of a new one under the temp folder" },
|
|
2898
|
+
sha256: { type: "string", description: "the sha256 the file must have", conflicts: ["sums"] },
|
|
2899
|
+
sums: { type: "string", description: "the URL of a checksums file (SHA256SUMS) giving the file's sha256" },
|
|
2900
|
+
sig: { type: "string", description: "the URL of a detached signature of the file, or of the --sums file when there is one" },
|
|
2901
|
+
key: { type: "string", description: "the key --sig is checked with: a gpg fingerprint or key file, a minisign key or key file, a cosign PEM file" },
|
|
2902
|
+
extract: { type: "boolean", short: "x", description: "unpack the archive into a new folder beside it" },
|
|
2903
|
+
bin: { type: "string", optional: { bare: "" }, description: "install the file, or the one executable its archive holds, in ~/.local/bin, under the name given or its own", conflicts: ["exec"] },
|
|
2904
|
+
force: { type: "boolean", description: "let --bin replace a command of the same name" },
|
|
2905
|
+
exec: { type: "boolean", description: "run the file as a script, once --sha256, --sums or --sig pins it, or with --yes" },
|
|
2906
|
+
yes: { type: "boolean", description: "run an --exec script that nothing pins" },
|
|
2907
|
+
"max-size": { type: "string", description: "the largest download taken, 2G by default" },
|
|
2908
|
+
fresh: { type: "boolean", description: "take a release under two weeks old" },
|
|
2909
|
+
asset: { type: "string", description: "the release asset to take, a part of its name or a glob, when the one for this machine cannot be told" },
|
|
2910
|
+
json: jsonOption()
|
|
2911
|
+
};
|
|
2912
|
+
SHA256 = /^[0-9a-f]{64}$/i;
|
|
2913
|
+
HTML_EXTENSIONS = new Set(["", ".html", ".htm"]);
|
|
2914
|
+
});
|
|
2915
|
+
|
|
2916
|
+
// src/ls.ts
|
|
2917
|
+
var exports_ls = {};
|
|
2918
|
+
__export(exports_ls, {
|
|
2919
|
+
ls: () => ls
|
|
2920
|
+
});
|
|
2921
|
+
function ls(args) {
|
|
2922
|
+
const { values } = parse(args, USAGE2, { json: jsonOption() }, {
|
|
2923
|
+
exits: EXITS2,
|
|
2924
|
+
replaces: "remembering which tools came from a curl and from where",
|
|
2925
|
+
examples: ["dl ls", "dl ls --json"]
|
|
2926
|
+
});
|
|
2927
|
+
const entries = readLedger().sort((a, b) => a.name.localeCompare(b.name));
|
|
2928
|
+
if (values.json === true)
|
|
2929
|
+
printJson(entries);
|
|
2930
|
+
else if (entries.length === 0)
|
|
2931
|
+
console.log("nothing installed or run through dl yet");
|
|
2932
|
+
else
|
|
2933
|
+
console.log(table([["name", "kind", "when", "sha256", "from"], ...entries.map((entry) => [entry.name, entry.kind, formatAge(entry.at), entry.sha256.slice(0, 12), entry.url])], { header: true }));
|
|
2934
|
+
return 0;
|
|
2935
|
+
}
|
|
2936
|
+
var USAGE2 = `dl ls [options]: lists the commands dl installed with --bin and the scripts it ran with --exec, with where each came from and when
|
|
2937
|
+
|
|
2938
|
+
A command installed again, or a script run again, keeps one line, the latest.`, EXITS2;
|
|
2939
|
+
var init_ls = __esm(() => {
|
|
2940
|
+
init_src();
|
|
2941
|
+
init_state();
|
|
2942
|
+
EXITS2 = [[0, "listed, even nothing"], [2, "a usage error"]];
|
|
2943
|
+
});
|
|
2944
|
+
|
|
2945
|
+
// src/update.ts
|
|
2946
|
+
var exports_update = {};
|
|
2947
|
+
__export(exports_update, {
|
|
2948
|
+
outdated: () => outdated,
|
|
2949
|
+
update: () => update
|
|
2950
|
+
});
|
|
2951
|
+
async function releaseFreshness(entry, release) {
|
|
2952
|
+
try {
|
|
2953
|
+
const latest = await latestRelease(parseSpec(release));
|
|
2954
|
+
return latest !== undefined && Date.parse(latest.published) > Date.parse(entry.released ?? "") ? { state: "changed", now: latest.tag } : { state: "current" };
|
|
2955
|
+
} catch (error) {
|
|
2956
|
+
return { state: "unreachable", error: error instanceof Error ? error.message : String(error) };
|
|
2957
|
+
}
|
|
2958
|
+
}
|
|
2959
|
+
async function freshness(entry) {
|
|
2960
|
+
if (entry.release !== undefined)
|
|
2961
|
+
return releaseFreshness(entry, entry.release);
|
|
2962
|
+
const headers = { "accept-encoding": "identity" };
|
|
2963
|
+
if (entry.etag !== undefined)
|
|
2964
|
+
headers["if-none-match"] = entry.etag;
|
|
2965
|
+
else if (entry.lastModified !== undefined)
|
|
2966
|
+
headers["if-modified-since"] = entry.lastModified;
|
|
2967
|
+
try {
|
|
2968
|
+
const response = await fetch(entry.url, { headers, decompress: false });
|
|
2969
|
+
if (response.status === 304)
|
|
2970
|
+
return { state: "current" };
|
|
2971
|
+
if (!response.ok) {
|
|
2972
|
+
await response.body?.cancel();
|
|
2973
|
+
return { state: "unreachable", error: `answered ${response.status} ${response.statusText}`.trimEnd() };
|
|
2974
|
+
}
|
|
2975
|
+
const hasher = new Bun.CryptoHasher("sha256");
|
|
2976
|
+
let size = 0;
|
|
2977
|
+
for await (const chunk of response.body ?? new ReadableStream) {
|
|
2978
|
+
size += chunk.length;
|
|
2979
|
+
if (size > MAX_BYTES)
|
|
2980
|
+
return { state: "unreachable", error: `goes over ${formatSize(MAX_BYTES)}` };
|
|
2981
|
+
hasher.update(chunk);
|
|
2982
|
+
}
|
|
2983
|
+
const now = hasher.digest("hex");
|
|
2984
|
+
return now === entry.sha256 ? { state: "current" } : { state: "changed", now };
|
|
2985
|
+
} catch (error) {
|
|
2986
|
+
return { state: "unreachable", error: error instanceof Error ? error.message : String(error) };
|
|
2987
|
+
}
|
|
2988
|
+
}
|
|
2989
|
+
async function checkAll(names, bins) {
|
|
2990
|
+
const ledger = readLedger().filter((entry) => !bins || entry.kind === "bin").sort((a, b) => a.name.localeCompare(b.name));
|
|
2991
|
+
const unknown = names.filter((name) => !ledger.some((entry) => entry.name === name));
|
|
2992
|
+
if (unknown.length > 0)
|
|
2993
|
+
fail(`dl installed or ran nothing named ${unknown.join(", ")}`, 2, "dl ls lists what it did");
|
|
2994
|
+
const entries = names.length === 0 ? ledger : ledger.filter((entry) => names.includes(entry.name));
|
|
2995
|
+
const checked = [];
|
|
2996
|
+
for (let at = 0;at < entries.length; at += AT_ONCE)
|
|
2997
|
+
checked.push(...await Promise.all(entries.slice(at, at + AT_ONCE).map(async (entry) => ({ entry, freshness: await freshness(entry) }))));
|
|
2998
|
+
return checked;
|
|
2999
|
+
}
|
|
3000
|
+
function said(freshness, entry) {
|
|
3001
|
+
if (freshness.state === "changed")
|
|
3002
|
+
return entry.version === undefined ? `changed, ${entry.sha256.slice(0, 12)} now ${freshness.now.slice(0, 12)}` : `changed, ${entry.version} now ${freshness.now}`;
|
|
3003
|
+
return freshness.state === "unreachable" ? `unreachable: ${freshness.error}` : "current";
|
|
3004
|
+
}
|
|
3005
|
+
async function outdated(args) {
|
|
3006
|
+
const { values, positionals } = parse(args, OUTDATED_USAGE, { bins: { type: "boolean", description: "only the commands --bin installed" }, json: jsonOption("[{name, kind, url, at, sha256, version?, state, now?, error?}], state current, changed or unreachable, now a release's tag or a sha256") }, {
|
|
3007
|
+
positionals: ["[name...]"],
|
|
3008
|
+
exits: OUTDATED_EXITS,
|
|
3009
|
+
replaces: "checking by hand whether a tool installed from a URL has a newer build",
|
|
3010
|
+
examples: ["dl outdated", ["dl outdated --bins", "the installed commands only"]]
|
|
3011
|
+
});
|
|
3012
|
+
const checked = await checkAll(positionals, values.bins === true);
|
|
3013
|
+
const behind = checked.filter(({ freshness }) => freshness.state !== "current");
|
|
3014
|
+
if (values.json === true) {
|
|
3015
|
+
printJson(checked.map(({ entry, freshness }) => ({ name: entry.name, kind: entry.kind, url: entry.url, at: entry.at, sha256: entry.sha256, ...entry.version === undefined ? {} : { version: entry.version }, ...freshness })));
|
|
3016
|
+
return behind.length === 0 ? 0 : 1;
|
|
3017
|
+
}
|
|
3018
|
+
if (behind.length === 0) {
|
|
3019
|
+
console.log(checked.length === 0 ? "nothing installed or run through dl yet" : `all ${checked.length} current`);
|
|
3020
|
+
return 0;
|
|
3021
|
+
}
|
|
3022
|
+
const changed = behind.filter(({ freshness }) => freshness.state === "changed").map(({ entry }) => entry.name);
|
|
3023
|
+
console.log(table([["name", "kind", "installed", "source"], ...behind.map(({ entry, freshness }) => [entry.name, entry.kind, formatAge(entry.at), said(freshness, entry)])], { header: true }));
|
|
3024
|
+
if (changed.length > 0)
|
|
3025
|
+
console.log(`
|
|
3026
|
+
update them: dl update ${changed.join(" ")}`);
|
|
3027
|
+
return 1;
|
|
3028
|
+
}
|
|
3029
|
+
function argvOf(entry, yes) {
|
|
3030
|
+
if (entry.release !== undefined)
|
|
3031
|
+
return [entry.release, "--bin", entry.name, "--force", ...entry.asset === undefined ? [] : ["--asset", entry.asset], ...entry.key === undefined ? [] : ["--key", entry.key]];
|
|
3032
|
+
const checks = [...entry.sums === undefined ? [] : ["--sums", entry.sums], ...entry.sig === undefined || entry.key === undefined ? [] : ["--sig", entry.sig, "--key", entry.key]];
|
|
3033
|
+
if (entry.kind === "bin")
|
|
3034
|
+
return [entry.url, "--bin", entry.name, "--force", ...checks];
|
|
3035
|
+
return [entry.url, "--exec", ...checks, ...yes ? ["--yes"] : [], ...entry.args === undefined ? [] : ["--", ...entry.args]];
|
|
3036
|
+
}
|
|
3037
|
+
async function update(args) {
|
|
3038
|
+
const { values, positionals } = parse(args, UPDATE_USAGE, { yes: { type: "boolean", description: "run a changed script that no checksums file or signature pins" } }, {
|
|
3039
|
+
positionals: ["[name...]"],
|
|
3040
|
+
exits: UPDATE_EXITS,
|
|
3041
|
+
examples: [["dl update", "everything that changed"], ["dl update tool", "one command"]]
|
|
3042
|
+
});
|
|
3043
|
+
const checked = await checkAll(positionals, false);
|
|
3044
|
+
const changed = checked.filter(({ freshness }) => freshness.state === "changed");
|
|
3045
|
+
let code = 0;
|
|
3046
|
+
for (const { entry, freshness } of checked) {
|
|
3047
|
+
if (freshness.state === "unreachable") {
|
|
3048
|
+
printError("dl update", `${entry.name}: ${entry.release ?? entry.url} ${freshness.error}`);
|
|
3049
|
+
code = 1;
|
|
3050
|
+
}
|
|
3051
|
+
}
|
|
3052
|
+
if (changed.length === 0) {
|
|
3053
|
+
console.log("nothing changed");
|
|
3054
|
+
return code;
|
|
3055
|
+
}
|
|
3056
|
+
for (const { entry } of changed) {
|
|
3057
|
+
console.log(`
|
|
3058
|
+
updating ${entry.name}`);
|
|
3059
|
+
try {
|
|
3060
|
+
code = Math.max(code, await get(argvOf(entry, values.yes === true)));
|
|
3061
|
+
} catch (error) {
|
|
3062
|
+
if (!(error instanceof Exit))
|
|
3063
|
+
throw error;
|
|
3064
|
+
printError("dl update", `${entry.name}: ${error.message}`, error.hint);
|
|
3065
|
+
code = 1;
|
|
3066
|
+
}
|
|
3067
|
+
}
|
|
3068
|
+
return code;
|
|
3069
|
+
}
|
|
3070
|
+
var AT_ONCE = 4, MAX_BYTES, OUTDATED_USAGE = `dl outdated [name...] [options]: asks the source of each command dl installed and script it ran whether it changed since
|
|
3071
|
+
|
|
3072
|
+
A server that gives an ETag or Last-Modified answers without sending the file again; otherwise the file is downloaded and its sha256 compared. A command installed from a release is behind once a release published after it is two weeks old.`, OUTDATED_EXITS, UPDATE_USAGE = `dl update [name...] [options]: downloads again what changed of the commands dl installed and the scripts it ran, checked as it was the first time, then installs or runs it
|
|
3073
|
+
|
|
3074
|
+
Without names, every one whose source changed. A checksums file or a signature given at install is checked again; a sha256 given at install cannot pin a new file, so a script it pinned runs only with --yes. A script shows its diff and what it does, and runs with the arguments it had.`, UPDATE_EXITS;
|
|
3075
|
+
var init_update = __esm(() => {
|
|
3076
|
+
init_src();
|
|
3077
|
+
init_get();
|
|
3078
|
+
init_release();
|
|
3079
|
+
init_state();
|
|
3080
|
+
MAX_BYTES = parseSize(DEFAULT_MAX_SIZE);
|
|
3081
|
+
OUTDATED_EXITS = [[0, "every one is current"], [1, "one changed, or its source cannot be reached"], [2, "a usage error"]];
|
|
3082
|
+
UPDATE_EXITS = [[0, "every one updated, or nothing changed"], [1, "one failed to download, check, install or run"], [2, "a usage error"]];
|
|
3083
|
+
});
|
|
3084
|
+
|
|
3085
|
+
// src/cli.ts
|
|
3086
|
+
init_src();
|
|
3087
|
+
import process23 from "process";
|
|
3088
|
+
process23.exitCode = await runCli({
|
|
3089
|
+
name: "dl",
|
|
3090
|
+
about: "downloads a file into a folder of its own, checks its sha256, then extracts it, installs it as a command or runs it as a script once it is pinned",
|
|
3091
|
+
replaces: "curl -fsSL <url> | sh, curl -LO then sha256sum -c by hand, and unpacking a release to copy its binary into ~/.local/bin",
|
|
3092
|
+
examples: [["dl https://bun.sh/install", "download a script to read it"], ["dl https://bun.sh/install --exec --sha256 <sha>", "run the script that was read"], ["dl https://example.com/tool.tar.gz --sums https://example.com/SHA256SUMS --bin tool", "a checked binary, installed"], ["dl ls", "what dl installed or ran"], ["dl outdated", "what changed at its source"], ["dl update", "install it again"]],
|
|
3093
|
+
defaultCommand: "get",
|
|
3094
|
+
commands: {
|
|
3095
|
+
get: { summary: "download a file, check it, then extract, install or run it as asked", run: async (args) => (await Promise.resolve().then(() => (init_get(), exports_get))).get(args) },
|
|
3096
|
+
ls: { summary: "list the commands dl installed and the scripts it ran", run: async (args) => (await Promise.resolve().then(() => (init_ls(), exports_ls))).ls(args) },
|
|
3097
|
+
outdated: { summary: "list the commands and scripts whose source changed since", run: async (args) => (await Promise.resolve().then(() => (init_update(), exports_update))).outdated(args) },
|
|
3098
|
+
update: { summary: "download, check and install or run again what changed", run: async (args) => (await Promise.resolve().then(() => (init_update(), exports_update))).update(args) }
|
|
3099
|
+
}
|
|
3100
|
+
});
|