@kaynooo/cli-dl 0.0.3 → 0.0.5
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/README.md +10 -2
- package/dist/cli.js +946 -173
- package/package.json +3 -3
package/dist/cli.js
CHANGED
|
@@ -159,11 +159,14 @@ var init_config = __esm(() => {
|
|
|
159
159
|
|
|
160
160
|
// ../kit/src/user-config.ts
|
|
161
161
|
import { homedir } from "os";
|
|
162
|
-
import { join as join2 } from "path";
|
|
162
|
+
import { isAbsolute, join as join2 } from "path";
|
|
163
163
|
import process4 from "process";
|
|
164
|
+
function xdgFolder(value, fallback) {
|
|
165
|
+
return value !== undefined && isAbsolute(value) ? value : fallback;
|
|
166
|
+
}
|
|
164
167
|
function configBase(where = {}) {
|
|
165
168
|
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
166
|
-
return xdg
|
|
169
|
+
return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
|
|
167
170
|
}
|
|
168
171
|
function userConfigPath(bin, where = {}) {
|
|
169
172
|
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
@@ -409,6 +412,9 @@ function marked(mark, text, stream, detail, env = process6.env) {
|
|
|
409
412
|
}
|
|
410
413
|
return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
|
|
411
414
|
}
|
|
415
|
+
function warn(text, detail) {
|
|
416
|
+
console.error(marked("warn", text, process6.stderr, detail));
|
|
417
|
+
}
|
|
412
418
|
var MARK_WORDS, STATUS_WORDS, STATUS_OF;
|
|
413
419
|
var init_style = __esm(() => {
|
|
414
420
|
init_colors();
|
|
@@ -601,6 +607,14 @@ var init_help = __esm(() => {
|
|
|
601
607
|
});
|
|
602
608
|
|
|
603
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
|
+
}
|
|
604
618
|
function distance(a, b) {
|
|
605
619
|
const left = [...a];
|
|
606
620
|
const right = [...b];
|
|
@@ -626,7 +640,10 @@ function closest(name, names) {
|
|
|
626
640
|
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
627
641
|
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
628
642
|
}
|
|
629
|
-
var
|
|
643
|
+
var CONTROLS;
|
|
644
|
+
var init_text2 = __esm(() => {
|
|
645
|
+
CONTROLS = /[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;
|
|
646
|
+
});
|
|
630
647
|
|
|
631
648
|
// ../kit/src/input.ts
|
|
632
649
|
var init_input = __esm(() => {
|
|
@@ -901,7 +918,31 @@ var init_chart = __esm(() => {
|
|
|
901
918
|
});
|
|
902
919
|
|
|
903
920
|
// ../kit/src/process.ts
|
|
921
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
922
|
+
import { constants } from "os";
|
|
904
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
|
+
}
|
|
905
946
|
function holdSignals(cleanup) {
|
|
906
947
|
let received;
|
|
907
948
|
let child;
|
|
@@ -920,7 +961,8 @@ function holdSignals(cleanup) {
|
|
|
920
961
|
function onSignal(signal) {
|
|
921
962
|
received = signal;
|
|
922
963
|
if (child !== undefined) {
|
|
923
|
-
|
|
964
|
+
if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
|
|
965
|
+
child.kill(signal);
|
|
924
966
|
return;
|
|
925
967
|
}
|
|
926
968
|
if (cleanup === undefined)
|
|
@@ -933,9 +975,99 @@ function holdSignals(cleanup) {
|
|
|
933
975
|
process11.on(signal, onSignal);
|
|
934
976
|
return held;
|
|
935
977
|
}
|
|
936
|
-
|
|
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;
|
|
937
1068
|
var init_process = __esm(() => {
|
|
938
1069
|
SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
1070
|
+
GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
|
|
939
1071
|
});
|
|
940
1072
|
|
|
941
1073
|
// ../kit/src/progress.ts
|
|
@@ -1160,9 +1292,48 @@ var init_progress = __esm(() => {
|
|
|
1160
1292
|
});
|
|
1161
1293
|
|
|
1162
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;
|
|
1163
1327
|
var init_tool = __esm(() => {
|
|
1164
1328
|
init_format();
|
|
1165
1329
|
init_process();
|
|
1330
|
+
SpawnError = class SpawnError extends Error {
|
|
1331
|
+
missing;
|
|
1332
|
+
constructor(message, missing) {
|
|
1333
|
+
super(message);
|
|
1334
|
+
this.missing = missing;
|
|
1335
|
+
}
|
|
1336
|
+
};
|
|
1166
1337
|
});
|
|
1167
1338
|
|
|
1168
1339
|
// ../kit/src/ci.ts
|
|
@@ -1175,12 +1346,12 @@ var init_ci = __esm(() => {
|
|
|
1175
1346
|
});
|
|
1176
1347
|
|
|
1177
1348
|
// ../kit/src/askpass.ts
|
|
1178
|
-
import
|
|
1349
|
+
import process14 from "process";
|
|
1179
1350
|
async function askpassClient(argv) {
|
|
1180
|
-
const socketPath =
|
|
1351
|
+
const socketPath = process14.env[SOCKET_VARIABLE];
|
|
1181
1352
|
if (socketPath === undefined)
|
|
1182
1353
|
return;
|
|
1183
|
-
const request = { prompt: argv[0] ?? "", ...
|
|
1354
|
+
const request = { prompt: argv[0] ?? "", ...process14.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
|
|
1184
1355
|
const { promise, resolve } = Promise.withResolvers();
|
|
1185
1356
|
let received = "";
|
|
1186
1357
|
try {
|
|
@@ -1207,7 +1378,7 @@ async function askpassClient(argv) {
|
|
|
1207
1378
|
return 0;
|
|
1208
1379
|
if (answer === undefined)
|
|
1209
1380
|
return 1;
|
|
1210
|
-
|
|
1381
|
+
process14.stdout.write(`${answer}
|
|
1211
1382
|
`);
|
|
1212
1383
|
return 0;
|
|
1213
1384
|
}
|
|
@@ -1275,16 +1446,16 @@ var init_completions = __esm(() => {
|
|
|
1275
1446
|
});
|
|
1276
1447
|
|
|
1277
1448
|
// ../kit/src/notify.ts
|
|
1278
|
-
import
|
|
1449
|
+
import process15 from "process";
|
|
1279
1450
|
function base64(text) {
|
|
1280
1451
|
return Buffer.from(text).toString("base64");
|
|
1281
1452
|
}
|
|
1282
|
-
function notification(title, body, env =
|
|
1283
|
-
const id = `kit${
|
|
1453
|
+
function notification(title, body, env = process15.env) {
|
|
1454
|
+
const id = `kit${process15.pid}`;
|
|
1284
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\\`];
|
|
1285
1456
|
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
1286
1457
|
}
|
|
1287
|
-
function notifyEnd(command, code, ms, { stream =
|
|
1458
|
+
function notifyEnd(command, code, ms, { stream = process15.stderr, env = process15.env } = {}) {
|
|
1288
1459
|
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
1289
1460
|
return;
|
|
1290
1461
|
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
@@ -1298,25 +1469,25 @@ var init_notify = __esm(() => {
|
|
|
1298
1469
|
// ../kit/src/logs.ts
|
|
1299
1470
|
var DAY_MS, CLI_FOLDER = "kaynooo-cli";
|
|
1300
1471
|
var init_logs = __esm(() => {
|
|
1472
|
+
init_user_config();
|
|
1301
1473
|
DAY_MS = 24 * 60 * 60 * 1000;
|
|
1302
1474
|
});
|
|
1303
1475
|
|
|
1304
1476
|
// ../kit/src/usage.ts
|
|
1305
1477
|
import { appendFileSync, mkdirSync } from "fs";
|
|
1306
1478
|
import { homedir as homedir3 } from "os";
|
|
1307
|
-
import { dirname as dirname2,
|
|
1308
|
-
import
|
|
1479
|
+
import { dirname as dirname2, join as join4 } from "path";
|
|
1480
|
+
import process16 from "process";
|
|
1309
1481
|
function noteUsageError(message) {
|
|
1310
1482
|
usageError = message;
|
|
1311
1483
|
}
|
|
1312
|
-
function stateHome(env =
|
|
1313
|
-
|
|
1314
|
-
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
1484
|
+
function stateHome(env = process16.env) {
|
|
1485
|
+
return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
|
|
1315
1486
|
}
|
|
1316
|
-
function usagePath(env =
|
|
1487
|
+
function usagePath(env = process16.env) {
|
|
1317
1488
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1318
1489
|
}
|
|
1319
|
-
function usageRecorded(env =
|
|
1490
|
+
function usageRecorded(env = process16.env) {
|
|
1320
1491
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1321
1492
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1322
1493
|
}
|
|
@@ -1330,7 +1501,7 @@ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
|
|
|
1330
1501
|
usageError = undefined;
|
|
1331
1502
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
|
|
1332
1503
|
}
|
|
1333
|
-
function recordUsage(entry, env =
|
|
1504
|
+
function recordUsage(entry, env = process16.env) {
|
|
1334
1505
|
if (!usageRecorded(env))
|
|
1335
1506
|
return;
|
|
1336
1507
|
try {
|
|
@@ -1343,14 +1514,15 @@ function recordUsage(entry, env = process15.env) {
|
|
|
1343
1514
|
var UNKNOWN_OPTION2, FLAG_NAME, LONGEST_NAME = 40, usageError;
|
|
1344
1515
|
var init_usage = __esm(() => {
|
|
1345
1516
|
init_logs();
|
|
1517
|
+
init_user_config();
|
|
1346
1518
|
UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
1347
1519
|
FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
1348
1520
|
});
|
|
1349
1521
|
|
|
1350
1522
|
// ../kit/src/cli.ts
|
|
1351
|
-
import { readFileSync as
|
|
1523
|
+
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
1352
1524
|
import { dirname as dirname3, join as join5 } from "path";
|
|
1353
|
-
import
|
|
1525
|
+
import process17 from "process";
|
|
1354
1526
|
async function commandRows(all, colors) {
|
|
1355
1527
|
const commands = shown(all);
|
|
1356
1528
|
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
@@ -1385,6 +1557,10 @@ function takeOutputFlags(argv) {
|
|
|
1385
1557
|
async function resolveSummary(summary) {
|
|
1386
1558
|
return typeof summary === "string" ? summary : summary();
|
|
1387
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
|
+
}
|
|
1388
1564
|
function scopeOf(commands, extra, aliases) {
|
|
1389
1565
|
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
1390
1566
|
}
|
|
@@ -1424,8 +1600,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
1424
1600
|
`);
|
|
1425
1601
|
}
|
|
1426
1602
|
function printError(prefix, message, hint, cause) {
|
|
1427
|
-
const colors = paint(
|
|
1428
|
-
const styled = takesControlCodes(
|
|
1603
|
+
const colors = paint(process17.stderr);
|
|
1604
|
+
const styled = takesControlCodes(process17.stderr);
|
|
1429
1605
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1430
1606
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1431
1607
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -1468,23 +1644,23 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
1468
1644
|
}
|
|
1469
1645
|
}
|
|
1470
1646
|
if (name === undefined && level.path.length > 1) {
|
|
1471
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1647
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process17.stderr));
|
|
1472
1648
|
return 2;
|
|
1473
1649
|
}
|
|
1474
1650
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1475
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1651
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process17.stdout));
|
|
1476
1652
|
return 0;
|
|
1477
1653
|
}
|
|
1478
1654
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
1479
1655
|
console.log(version);
|
|
1480
1656
|
return 0;
|
|
1481
1657
|
}
|
|
1482
|
-
let command = level
|
|
1658
|
+
let command = lookup(level, name);
|
|
1483
1659
|
let rest = args;
|
|
1484
1660
|
let ran = name;
|
|
1485
1661
|
if (command === undefined && level.lazy.length > 0) {
|
|
1486
1662
|
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
1487
|
-
command = level
|
|
1663
|
+
command = lookup(level, name);
|
|
1488
1664
|
}
|
|
1489
1665
|
if (command === undefined && level.defaultCommand !== undefined) {
|
|
1490
1666
|
command = level.commands[level.defaultCommand];
|
|
@@ -1562,18 +1738,19 @@ async function leafCandidates(run, words) {
|
|
|
1562
1738
|
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1563
1739
|
const [word = "", ...rest] = words;
|
|
1564
1740
|
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1565
|
-
let { commands
|
|
1566
|
-
let command =
|
|
1741
|
+
let { commands } = scope;
|
|
1742
|
+
let command = lookup(scope, word);
|
|
1567
1743
|
if (listing || command === undefined) {
|
|
1568
|
-
|
|
1569
|
-
|
|
1744
|
+
const expanded = await expand(scope, [...before, ...words]);
|
|
1745
|
+
commands = expanded.commands;
|
|
1746
|
+
command = lookup(expanded, word);
|
|
1570
1747
|
}
|
|
1571
1748
|
if (listing) {
|
|
1572
1749
|
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1573
1750
|
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1574
1751
|
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1575
1752
|
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1576
|
-
return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line)
|
|
1753
|
+
return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
|
|
1577
1754
|
}
|
|
1578
1755
|
if (command === undefined) {
|
|
1579
1756
|
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
@@ -1605,7 +1782,7 @@ function packageVersion(entry = Bun.main) {
|
|
|
1605
1782
|
} catch {}
|
|
1606
1783
|
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1607
1784
|
try {
|
|
1608
|
-
const { version } = JSON.parse(
|
|
1785
|
+
const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
|
|
1609
1786
|
if (typeof version === "string")
|
|
1610
1787
|
return version;
|
|
1611
1788
|
} catch {}
|
|
@@ -1637,8 +1814,7 @@ function commandPath(scope, argv) {
|
|
|
1637
1814
|
const path = [];
|
|
1638
1815
|
let level = scope;
|
|
1639
1816
|
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1640
|
-
const
|
|
1641
|
-
const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
|
|
1817
|
+
const command = lookup(level, word);
|
|
1642
1818
|
if (command === undefined)
|
|
1643
1819
|
break;
|
|
1644
1820
|
path.push(word);
|
|
@@ -1698,9 +1874,10 @@ var init_report = __esm(() => {
|
|
|
1698
1874
|
});
|
|
1699
1875
|
|
|
1700
1876
|
// ../kit/src/secrets.ts
|
|
1701
|
-
var SECRET_WORDS;
|
|
1877
|
+
var SECRET_WORDS, NOT_PASSWORDS;
|
|
1702
1878
|
var init_secrets = __esm(() => {
|
|
1703
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"]);
|
|
1704
1881
|
});
|
|
1705
1882
|
|
|
1706
1883
|
// ../kit/src/sessions.ts
|
|
@@ -1716,8 +1893,13 @@ function parseSize(text, bareUnit = 1) {
|
|
|
1716
1893
|
const match = SIZE.exec(text.trim());
|
|
1717
1894
|
if (match === null)
|
|
1718
1895
|
return;
|
|
1719
|
-
const suffix = match[2]
|
|
1720
|
-
|
|
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);
|
|
1721
1903
|
}
|
|
1722
1904
|
function formatSize(bytes) {
|
|
1723
1905
|
let value = bytes;
|
|
@@ -1726,11 +1908,17 @@ function formatSize(bytes) {
|
|
|
1726
1908
|
value /= 1024;
|
|
1727
1909
|
unit++;
|
|
1728
1910
|
}
|
|
1729
|
-
|
|
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]}`;
|
|
1730
1918
|
}
|
|
1731
1919
|
var SIZE, POWERS, UNITS2;
|
|
1732
1920
|
var init_size = __esm(() => {
|
|
1733
|
-
SIZE = /^(\d+(?:\.\d+)?)\s*([kmgt]
|
|
1921
|
+
SIZE = /^(\d+(?:\.\d+)?)\s*(?:([kmgt])i?b?|(b))?$/i;
|
|
1734
1922
|
POWERS = { "": 0, k: 1, m: 2, g: 3, t: 4 };
|
|
1735
1923
|
UNITS2 = ["B", "K", "M", "G", "T"];
|
|
1736
1924
|
});
|
|
@@ -1780,8 +1968,8 @@ var init_src = __esm(() => {
|
|
|
1780
1968
|
});
|
|
1781
1969
|
|
|
1782
1970
|
// ../arc/src/proc.ts
|
|
1783
|
-
import
|
|
1784
|
-
async function interactive(argv, cwd =
|
|
1971
|
+
import process19 from "process";
|
|
1972
|
+
async function interactive(argv, cwd = process19.cwd()) {
|
|
1785
1973
|
return Bun.spawn(argv, { cwd, stdin: "inherit", stdout: "inherit", stderr: "inherit" }).exited;
|
|
1786
1974
|
}
|
|
1787
1975
|
var init_proc = __esm(() => {
|
|
@@ -1850,47 +2038,173 @@ var init_extract = __esm(() => {
|
|
|
1850
2038
|
LONE = new Set([".bz2", ".gz", ".xz", ".zst", ".z"]);
|
|
1851
2039
|
});
|
|
1852
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
|
+
|
|
1853
2119
|
// src/download.ts
|
|
1854
|
-
import { existsSync as
|
|
1855
|
-
import {
|
|
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
|
+
}
|
|
1856
2150
|
async function download(url, dir, maxSize) {
|
|
1857
|
-
|
|
1858
|
-
const
|
|
1859
|
-
const
|
|
1860
|
-
|
|
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();
|
|
1861
2158
|
return fail(`'${path}' already exists`, 1, "download into another folder with -o, or none to get a new one");
|
|
2159
|
+
}
|
|
1862
2160
|
const length = Number(response.headers.get("content-length") ?? Number.NaN);
|
|
1863
|
-
const total = Number.isFinite(length) && length > 0 ? length : undefined;
|
|
1864
|
-
if (total !== undefined && total > maxSize)
|
|
2161
|
+
const total = Number.isFinite(length) && length > 0 ? offset + length : undefined;
|
|
2162
|
+
if (total !== undefined && total > maxSize) {
|
|
2163
|
+
await response.body?.cancel();
|
|
1865
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);
|
|
1866
2172
|
const line = progressLine();
|
|
1867
2173
|
const hasher = new Bun.CryptoHasher("sha256");
|
|
1868
|
-
const
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
let
|
|
1872
|
-
|
|
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) });
|
|
1873
2181
|
try {
|
|
1874
2182
|
for await (const chunk of response.body ?? new ReadableStream) {
|
|
1875
2183
|
size += chunk.length;
|
|
1876
|
-
|
|
2184
|
+
overSize = size > maxSize;
|
|
2185
|
+
if (overSize)
|
|
1877
2186
|
fail(`${url} goes over --max-size ${formatSize(maxSize)}`, 1);
|
|
1878
2187
|
if (headSize < HEAD_BYTES) {
|
|
1879
2188
|
head.push(chunk.subarray(0, HEAD_BYTES - headSize));
|
|
1880
2189
|
headSize += head.at(-1).length;
|
|
1881
2190
|
}
|
|
1882
2191
|
hasher.update(chunk);
|
|
1883
|
-
await
|
|
2192
|
+
await handle.write(chunk);
|
|
1884
2193
|
line.update({ step: name, ...counted(size, total) });
|
|
1885
2194
|
}
|
|
1886
|
-
await writer.end();
|
|
1887
2195
|
} catch (error) {
|
|
1888
|
-
await
|
|
1889
|
-
rmSync2(path, { force: true });
|
|
2196
|
+
await handle.close();
|
|
1890
2197
|
line.failed(name);
|
|
1891
|
-
|
|
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");
|
|
1892
2203
|
}
|
|
1893
|
-
|
|
2204
|
+
await handle.close();
|
|
2205
|
+
moveInto(partFile, path);
|
|
2206
|
+
dropPart(url);
|
|
2207
|
+
line.done(`${name} ${formatSize(size)}${offset > 0 ? `, resumed at ${formatSize(offset)}` : ""}`);
|
|
1894
2208
|
const start = Buffer.concat(head);
|
|
1895
2209
|
return {
|
|
1896
2210
|
path,
|
|
@@ -1900,17 +2214,35 @@ async function download(url, dir, maxSize) {
|
|
|
1900
2214
|
type: response.headers.get("content-type") ?? "",
|
|
1901
2215
|
sha256: hasher.digest("hex"),
|
|
1902
2216
|
html: HTML_START.test(start.toString("utf8")),
|
|
1903
|
-
text: !start.includes(0)
|
|
2217
|
+
text: !start.includes(0),
|
|
2218
|
+
...validators(part)
|
|
1904
2219
|
};
|
|
1905
2220
|
}
|
|
1906
|
-
|
|
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 = []) {
|
|
1907
2239
|
let response;
|
|
1908
2240
|
try {
|
|
1909
|
-
response = await fetch(url);
|
|
2241
|
+
response = await fetch(url, init);
|
|
1910
2242
|
} catch (error) {
|
|
1911
2243
|
return fail(`cannot reach ${url}: ${error instanceof Error ? error.message : String(error)}`, 1);
|
|
1912
2244
|
}
|
|
1913
|
-
return response.ok ? response : fail(`${url} answered ${response.status} ${response.statusText}`.trimEnd(), 1);
|
|
2245
|
+
return response.ok || allowed.includes(response.status) ? response : fail(`${url} answered ${response.status} ${response.statusText}`.trimEnd(), 1);
|
|
1914
2246
|
}
|
|
1915
2247
|
function fileName(response, requested) {
|
|
1916
2248
|
const disposition = DISPOSITION_NAME.exec(response.headers.get("content-disposition") ?? "")?.[1];
|
|
@@ -1931,29 +2263,32 @@ function counted(done, total) {
|
|
|
1931
2263
|
const [unit, scale] = total >= 1024 ** 2 ? ["MiB", 1024 ** 2] : ["KiB", 1024];
|
|
1932
2264
|
return { done: Math.floor(done / scale), total: Math.ceil(total / scale), unit };
|
|
1933
2265
|
}
|
|
1934
|
-
var HEAD_BYTES = 8192, HTML_START, DISPOSITION_NAME;
|
|
2266
|
+
var HEAD_BYTES = 8192, HTML_START, DISPOSITION_NAME, CONTENT_RANGE, RANGE_NOT_SATISFIABLE = 416, SMALL_FILE;
|
|
1935
2267
|
var init_download = __esm(() => {
|
|
1936
2268
|
init_src();
|
|
1937
2269
|
init_progress();
|
|
2270
|
+
init_state();
|
|
1938
2271
|
HTML_START = /^\s*<(?:!doctype html|html)[\s>]/i;
|
|
1939
2272
|
DISPOSITION_NAME = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i;
|
|
2273
|
+
CONTENT_RANGE = /^bytes (\d+)-\d+\/(?:\d+|\*)$/;
|
|
2274
|
+
SMALL_FILE = 16 * 1024 * 1024;
|
|
1940
2275
|
});
|
|
1941
2276
|
|
|
1942
2277
|
// src/install.ts
|
|
1943
|
-
import { chmodSync, closeSync, copyFileSync, existsSync as
|
|
2278
|
+
import { chmodSync, closeSync, copyFileSync as copyFileSync3, existsSync as existsSync6, mkdirSync as mkdirSync4, openSync, readSync, renameSync as renameSync4, statSync as statSync4 } from "fs";
|
|
1944
2279
|
import { homedir as homedir4 } from "os";
|
|
1945
|
-
import { basename as basename3, delimiter, join as
|
|
1946
|
-
import
|
|
2280
|
+
import { basename as basename3, delimiter, join as join9, relative } from "path";
|
|
2281
|
+
import process20 from "process";
|
|
1947
2282
|
function binDir() {
|
|
1948
|
-
return
|
|
2283
|
+
return join9(homedir4(), ".local", "bin");
|
|
1949
2284
|
}
|
|
1950
2285
|
function binDirOnPath() {
|
|
1951
|
-
return (
|
|
2286
|
+
return (process20.env.PATH ?? "").split(delimiter).includes(binDir());
|
|
1952
2287
|
}
|
|
1953
2288
|
async function pickBinary(root, wanted) {
|
|
1954
2289
|
const found = [];
|
|
1955
2290
|
for await (const file of new Bun.Glob("**/*").scan({ cwd: root, onlyFiles: true, dot: true }))
|
|
1956
|
-
found.push(
|
|
2291
|
+
found.push(join9(root, file));
|
|
1957
2292
|
const executables = found.filter(isExecutable).sort();
|
|
1958
2293
|
const matching = wanted === undefined ? executables : executables.filter((file) => basename3(file) === wanted);
|
|
1959
2294
|
const listed = executables.map((file) => relative(root, file)).join(", ");
|
|
@@ -1966,17 +2301,17 @@ async function pickBinary(root, wanted) {
|
|
|
1966
2301
|
return fail(`the archive holds several executables: ${listed}`, 1, "name the one to install: --bin <name>");
|
|
1967
2302
|
}
|
|
1968
2303
|
function installBinary(source, name, force) {
|
|
1969
|
-
const target =
|
|
1970
|
-
if (
|
|
2304
|
+
const target = join9(binDir(), name);
|
|
2305
|
+
if (existsSync6(target) && !force)
|
|
1971
2306
|
return fail(`'${target}' already exists`, 1, "pass --force to replace it");
|
|
1972
|
-
|
|
1973
|
-
|
|
2307
|
+
mkdirSync4(binDir(), { recursive: true });
|
|
2308
|
+
copyFileSync3(source, `${target}.dl-tmp`);
|
|
1974
2309
|
chmodSync(`${target}.dl-tmp`, 493);
|
|
1975
|
-
|
|
2310
|
+
renameSync4(`${target}.dl-tmp`, target);
|
|
1976
2311
|
return target;
|
|
1977
2312
|
}
|
|
1978
2313
|
function isExecutable(file) {
|
|
1979
|
-
if ((
|
|
2314
|
+
if ((statSync4(file).mode & 73) !== 0)
|
|
1980
2315
|
return true;
|
|
1981
2316
|
const start = Buffer.alloc(4);
|
|
1982
2317
|
const fd = openSync(file, "r");
|
|
@@ -1990,6 +2325,172 @@ var init_install = __esm(() => {
|
|
|
1990
2325
|
ELF = Buffer.from([127, 69, 76, 70]);
|
|
1991
2326
|
});
|
|
1992
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
|
+
|
|
1993
2494
|
// src/script.ts
|
|
1994
2495
|
function summarize(script) {
|
|
1995
2496
|
const findings = [];
|
|
@@ -2024,57 +2525,114 @@ var init_script = __esm(() => {
|
|
|
2024
2525
|
SHELL_OWN = new Set(["HOME", "PATH", "PWD", "OLDPWD", "SHELL", "USER", "IFS", "TERM", "LINENO", "RANDOM", "UID", "EUID", "BASH_SOURCE", "BASH_VERSION", "ZSH_VERSION"]);
|
|
2025
2526
|
});
|
|
2026
2527
|
|
|
2027
|
-
// src/
|
|
2028
|
-
import {
|
|
2029
|
-
import {
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
const
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
}
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
}
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
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
|
+
}
|
|
2068
2605
|
}
|
|
2069
|
-
var
|
|
2070
|
-
var
|
|
2606
|
+
var FINGERPRINT, SPACES2, MINISIGN_KEY, GET;
|
|
2607
|
+
var init_signature = __esm(() => {
|
|
2071
2608
|
init_src();
|
|
2072
|
-
|
|
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
|
+
};
|
|
2073
2618
|
});
|
|
2074
2619
|
|
|
2075
2620
|
// src/sums.ts
|
|
2076
2621
|
import { basename as basename4 } from "path";
|
|
2077
|
-
function
|
|
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) {
|
|
2078
2636
|
const entries = [];
|
|
2079
2637
|
for (const line of text.split(`
|
|
2080
2638
|
`).map((line) => line.trim())) {
|
|
@@ -2085,34 +2643,45 @@ function sumFor(text, name) {
|
|
|
2085
2643
|
else if (bsd !== null)
|
|
2086
2644
|
entries.push([bsd[2], bsd[1]]);
|
|
2087
2645
|
}
|
|
2088
|
-
const
|
|
2089
|
-
if (
|
|
2090
|
-
return
|
|
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();
|
|
2091
2655
|
const [only] = entries;
|
|
2092
2656
|
return entries.length === 1 && only[1] === undefined ? only[0].toLowerCase() : undefined;
|
|
2093
2657
|
}
|
|
2094
|
-
async function
|
|
2095
|
-
return
|
|
2658
|
+
async function fetchSums(url) {
|
|
2659
|
+
return smallFile(url);
|
|
2096
2660
|
}
|
|
2097
|
-
|
|
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;
|
|
2098
2665
|
var init_sums = __esm(() => {
|
|
2099
2666
|
init_src();
|
|
2100
2667
|
init_download();
|
|
2101
2668
|
GNU_LINE = /^([0-9a-f]{64})(?:\s+\*?(\S.*))?$/i;
|
|
2102
2669
|
BSD_LINE = /^SHA256 \((.+)\) = ([0-9a-f]{64})$/i;
|
|
2670
|
+
DOT_SLASH = /^\.\//;
|
|
2103
2671
|
});
|
|
2104
2672
|
|
|
2105
2673
|
// src/get.ts
|
|
2106
2674
|
var exports_get = {};
|
|
2107
2675
|
__export(exports_get, {
|
|
2676
|
+
DEFAULT_MAX_SIZE: () => DEFAULT_MAX_SIZE,
|
|
2108
2677
|
get: () => get
|
|
2109
2678
|
});
|
|
2110
|
-
import { chmodSync as chmodSync2, existsSync as
|
|
2111
|
-
import { tmpdir } from "os";
|
|
2112
|
-
import { basename as basename5, extname, join as
|
|
2113
|
-
import
|
|
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";
|
|
2114
2683
|
async function get(args) {
|
|
2115
|
-
const { values, positionals: [
|
|
2684
|
+
const { values, positionals: [given], rest = [] } = parse(args, USAGE, OPTIONS, {
|
|
2116
2685
|
positionals: ["<url>"],
|
|
2117
2686
|
rest: true,
|
|
2118
2687
|
exits: EXITS,
|
|
@@ -2121,11 +2690,15 @@ async function get(args) {
|
|
|
2121
2690
|
["dl https://bun.sh/install", "download it to read it"],
|
|
2122
2691
|
["dl https://bun.sh/install --exec --sha256 <sha>", "run the script that was read"],
|
|
2123
2692
|
["dl https://example.com/releases/tool-linux-amd64 --sums https://example.com/releases/SHA256SUMS --bin tool", "a checked binary, installed"],
|
|
2124
|
-
["dl https://example.com/tool.tar.gz -x", "download and unpack"]
|
|
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"]
|
|
2125
2696
|
]
|
|
2126
2697
|
});
|
|
2127
|
-
|
|
2128
|
-
|
|
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`);
|
|
2129
2702
|
if (values.sha256 !== undefined && !SHA256.test(values.sha256))
|
|
2130
2703
|
badUsage(`--sha256 takes 64 hex digits, not '${values.sha256}'`);
|
|
2131
2704
|
if (values.yes === true && values.exec !== true)
|
|
@@ -2136,20 +2709,35 @@ async function get(args) {
|
|
|
2136
2709
|
badUsage("arguments after -- go to an --exec script");
|
|
2137
2710
|
if (values.bin !== undefined && (values.bin.includes("/") || values.bin === "." || values.bin === ".."))
|
|
2138
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);
|
|
2139
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;
|
|
2140
2726
|
const created = values.output === undefined;
|
|
2141
|
-
const dir = created ?
|
|
2142
|
-
|
|
2143
|
-
const expectsFile = values.exec === true || values.bin !== undefined || values.extract === true;
|
|
2144
|
-
const { file, verified } = await fetchChecked(url, dir, created, { maxSize, expectsFile, sha256: values.sha256?.toLowerCase(), sums
|
|
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`);
|
|
2145
2733
|
const last = lastSeen(url);
|
|
2146
|
-
const report = { path: file.path, size: file.size, url: file.url, type: file.type, sha256: file.sha256, verified, seen: "first download" };
|
|
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" };
|
|
2147
2735
|
if (last !== undefined && last.seen.sha256 === file.sha256)
|
|
2148
2736
|
report.seen = `same as the download of ${formatAge(last.seen.at)}`;
|
|
2149
2737
|
else if (last !== undefined)
|
|
2150
2738
|
report.seen = `changed since the download of ${formatAge(last.seen.at)}, was ${last.seen.sha256.slice(0, 12)}`;
|
|
2151
2739
|
if (last?.content !== undefined && last.seen.sha256 !== file.sha256 && file.text)
|
|
2152
|
-
report.diff = await diff(last.content, file
|
|
2740
|
+
report.diff = await diff(last.content, file);
|
|
2153
2741
|
remember(url, file);
|
|
2154
2742
|
const extracted = values.extract === true || values.bin !== undefined && archiveSuffix(file.name) !== undefined;
|
|
2155
2743
|
if (extracted)
|
|
@@ -2158,16 +2746,33 @@ async function get(args) {
|
|
|
2158
2746
|
const source = report.extracted === undefined ? file.path : await pickBinary(report.extracted, values.bin === "" ? undefined : values.bin);
|
|
2159
2747
|
const name = values.bin === "" ? basename5(source) : values.bin;
|
|
2160
2748
|
report.installed = installBinary(source, name, values.force === true);
|
|
2161
|
-
record({ kind: "bin", name, url, sha256: file.sha256, path: report.installed, at: new Date().toISOString() });
|
|
2749
|
+
record({ kind: "bin", name, url, sha256: file.sha256, path: report.installed, at: new Date().toISOString(), ...release === undefined ? checkedBy(file, values) : fromRelease(release, values) });
|
|
2162
2750
|
}
|
|
2163
2751
|
if (values.exec === true)
|
|
2164
2752
|
report.script = summarize(await Bun.file(file.path).text());
|
|
2165
|
-
print(report,
|
|
2753
|
+
print(report, given, values.json === true);
|
|
2166
2754
|
if (values.exec !== true)
|
|
2167
2755
|
return 0;
|
|
2168
2756
|
if (!verified && values.yes !== true)
|
|
2169
|
-
return fail("not run: no --sha256 or --
|
|
2170
|
-
return runScript(file, url, rest);
|
|
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);
|
|
2171
2776
|
}
|
|
2172
2777
|
async function fetchChecked(url, dir, created, checks) {
|
|
2173
2778
|
let file;
|
|
@@ -2175,36 +2780,52 @@ async function fetchChecked(url, dir, created, checks) {
|
|
|
2175
2780
|
file = await download(url, dir, checks.maxSize);
|
|
2176
2781
|
if (file.html && (checks.expectsFile || !HTML_EXTENSIONS.has(extname(file.name).toLowerCase())))
|
|
2177
2782
|
fail(`${url} answered an HTML page, not a file`, 1);
|
|
2178
|
-
const
|
|
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;
|
|
2179
2786
|
if (expected !== undefined && expected !== file.sha256)
|
|
2180
2787
|
fail(`sha256 mismatch for ${file.name}: expected ${expected}, got ${file.sha256}; the file was deleted`, 1);
|
|
2181
|
-
return { file, verified: expected !== undefined };
|
|
2788
|
+
return { file, verified: expected !== undefined || signed !== undefined, ...signed === undefined ? {} : { signature: signed } };
|
|
2182
2789
|
} catch (error) {
|
|
2183
2790
|
if (file !== undefined)
|
|
2184
|
-
|
|
2791
|
+
rmSync5(file.path, { force: true });
|
|
2185
2792
|
if (created)
|
|
2186
|
-
|
|
2793
|
+
rmSync5(dir, { recursive: true, force: true });
|
|
2187
2794
|
throw error;
|
|
2188
2795
|
}
|
|
2189
2796
|
}
|
|
2190
|
-
async function diff(last, file
|
|
2797
|
+
async function diff(last, file) {
|
|
2191
2798
|
if (Bun.which("git") === null)
|
|
2192
2799
|
return "";
|
|
2193
|
-
const
|
|
2194
|
-
const child = Bun.spawn(["git", "diff", "--no-index", color, "--", last, file.path], { stdin: "ignore", stdout: "pipe", stderr: "ignore" });
|
|
2800
|
+
const child = Bun.spawn(["git", "diff", "--no-index", "--no-color", "--", last, file.path], { stdin: "ignore", stdout: "pipe", stderr: "ignore" });
|
|
2195
2801
|
const lines = (await child.stdout.text()).trimEnd().split(`
|
|
2196
2802
|
`);
|
|
2197
2803
|
await child.exited;
|
|
2198
|
-
const hunks = lines.findIndex((line) =>
|
|
2804
|
+
const hunks = lines.findIndex((line) => line.startsWith("@@"));
|
|
2199
2805
|
return hunks === -1 ? "" : ["--- last", `+++ ${file.name}`, ...lines.slice(hunks)].join(`
|
|
2200
2806
|
`);
|
|
2201
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
|
+
}
|
|
2202
2823
|
async function extract(file) {
|
|
2203
2824
|
const suffix = archiveSuffix(file.name) ?? fail(`${file.name} is no archive arc can extract`, 1);
|
|
2204
|
-
const folder =
|
|
2205
|
-
if (
|
|
2825
|
+
const folder = join11(file.path, "..", file.name.slice(0, -suffix.length) || "extracted");
|
|
2826
|
+
if (existsSync8(folder))
|
|
2206
2827
|
return fail(`'${folder}' already exists`, 1);
|
|
2207
|
-
|
|
2828
|
+
mkdirSync6(folder);
|
|
2208
2829
|
return await extractArchive(file.path, folder) !== 0 ? fail(`extracting ${file.name} failed`, 1) : folder;
|
|
2209
2830
|
}
|
|
2210
2831
|
function print(report, url, json) {
|
|
@@ -2217,65 +2838,75 @@ function print(report, url, json) {
|
|
|
2217
2838
|
["size", formatSize(report.size)],
|
|
2218
2839
|
...report.url === url ? [] : [["url", report.url]],
|
|
2219
2840
|
["type", report.type === "" ? "-" : report.type],
|
|
2841
|
+
...report.release === undefined ? [] : [["release", report.release]],
|
|
2220
2842
|
["sha256", `${report.sha256}${report.verified ? " verified" : ""}`],
|
|
2843
|
+
...report.signature === undefined ? [] : [["signature", `${report.signature}, verified`]],
|
|
2221
2844
|
["seen", report.seen],
|
|
2222
2845
|
...report.extracted === undefined ? [] : [["extracted", report.extracted]],
|
|
2223
2846
|
...report.installed === undefined ? [] : [["installed", report.installed]],
|
|
2224
2847
|
...report.installed === undefined || binDirOnPath() ? [] : [["note", `${binDir()} is not on PATH`]]
|
|
2225
2848
|
];
|
|
2226
|
-
console.log(table(rows));
|
|
2849
|
+
console.log(table(rows.map(([name = "", value = ""]) => [name, escapeControls(value)])));
|
|
2227
2850
|
if (report.diff !== undefined && report.diff !== "")
|
|
2228
2851
|
console.log(`
|
|
2229
|
-
${report.diff}`);
|
|
2852
|
+
${coloredDiff(report.diff)}`);
|
|
2230
2853
|
if (report.script === undefined)
|
|
2231
2854
|
return;
|
|
2232
2855
|
const { findings, env } = report.script;
|
|
2233
2856
|
console.log(findings.length === 0 ? `
|
|
2234
2857
|
script: fetches, sudo, removes, profile, system and runs found nowhere` : `
|
|
2235
2858
|
script:
|
|
2236
|
-
${table(findings.map(({ line, does, text }) => [`line ${line}`, does, truncate(text, LINE_WIDTH)]))}`);
|
|
2859
|
+
${table(findings.map(({ line, does, text }) => [`line ${line}`, does, truncate(escapeControls(text), LINE_WIDTH)]))}`);
|
|
2237
2860
|
if (env.length > 0)
|
|
2238
2861
|
console.log(`reads: ${env.join(", ")}`);
|
|
2239
2862
|
}
|
|
2240
|
-
async function runScript(file, url, args) {
|
|
2863
|
+
async function runScript(file, url, args, checked) {
|
|
2241
2864
|
const shebang = (await Bun.file(file.path).text()).startsWith("#!");
|
|
2242
2865
|
chmodSync2(file.path, 448);
|
|
2243
2866
|
const code = await Bun.spawn(shebang ? [file.path, ...args] : ["sh", file.path, ...args], { stdin: "inherit", stdout: "inherit", stderr: "inherit" }).exited;
|
|
2244
2867
|
if (code !== 0)
|
|
2245
2868
|
return fail(`the script exited ${code}`, 1);
|
|
2246
2869
|
const { host, pathname } = new URL(url);
|
|
2247
|
-
record({ kind: "script", name: `${host}${pathname}`, url, sha256: file.sha256, at: new Date().toISOString() });
|
|
2870
|
+
record({ kind: "script", name: `${host}${pathname}`, url, sha256: file.sha256, at: new Date().toISOString(), ...checked, ...args.length > 0 ? { args } : {} });
|
|
2248
2871
|
return 0;
|
|
2249
2872
|
}
|
|
2250
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
|
|
2251
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.
|
|
2252
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).
|
|
2253
2877
|
An HTML page arriving where a file was expected fails, as does a download over --max-size.
|
|
2254
|
-
--
|
|
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.
|
|
2255
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;
|
|
2256
2881
|
var init_get = __esm(() => {
|
|
2257
2882
|
init_extract();
|
|
2258
2883
|
init_src();
|
|
2259
2884
|
init_download();
|
|
2260
2885
|
init_install();
|
|
2886
|
+
init_release();
|
|
2261
2887
|
init_script();
|
|
2888
|
+
init_signature();
|
|
2262
2889
|
init_state();
|
|
2263
2890
|
init_sums();
|
|
2264
2891
|
EXITS = [
|
|
2265
2892
|
[0, "downloaded, and extracted, installed or run as asked"],
|
|
2266
|
-
[1, "an unreachable URL, an error status, a sha256 mismatch, an HTML page in place of a file, a download over --max-size, a script nothing pins, or one that failed"],
|
|
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"],
|
|
2267
2894
|
[2, "a usage error"]
|
|
2268
2895
|
];
|
|
2269
2896
|
OPTIONS = {
|
|
2270
2897
|
output: { type: "string", short: "o", description: "the folder to download into, created if missing, instead of a new one under the temp folder" },
|
|
2271
2898
|
sha256: { type: "string", description: "the sha256 the file must have", conflicts: ["sums"] },
|
|
2272
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" },
|
|
2273
2902
|
extract: { type: "boolean", short: "x", description: "unpack the archive into a new folder beside it" },
|
|
2274
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"] },
|
|
2275
2904
|
force: { type: "boolean", description: "let --bin replace a command of the same name" },
|
|
2276
|
-
exec: { type: "boolean", description: "run the file as a script, once --sha256 or --
|
|
2905
|
+
exec: { type: "boolean", description: "run the file as a script, once --sha256, --sums or --sig pins it, or with --yes" },
|
|
2277
2906
|
yes: { type: "boolean", description: "run an --exec script that nothing pins" },
|
|
2278
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" },
|
|
2279
2910
|
json: jsonOption()
|
|
2280
2911
|
};
|
|
2281
2912
|
SHA256 = /^[0-9a-f]{64}$/i;
|
|
@@ -2311,17 +2942,159 @@ var init_ls = __esm(() => {
|
|
|
2311
2942
|
EXITS2 = [[0, "listed, even nothing"], [2, "a usage error"]];
|
|
2312
2943
|
});
|
|
2313
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
|
+
|
|
2314
3085
|
// src/cli.ts
|
|
2315
3086
|
init_src();
|
|
2316
|
-
import
|
|
2317
|
-
|
|
3087
|
+
import process23 from "process";
|
|
3088
|
+
process23.exitCode = await runCli({
|
|
2318
3089
|
name: "dl",
|
|
2319
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",
|
|
2320
3091
|
replaces: "curl -fsSL <url> | sh, curl -LO then sha256sum -c by hand, and unpacking a release to copy its binary into ~/.local/bin",
|
|
2321
|
-
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"]],
|
|
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"]],
|
|
2322
3093
|
defaultCommand: "get",
|
|
2323
3094
|
commands: {
|
|
2324
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) },
|
|
2325
|
-
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) }
|
|
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) }
|
|
2326
3099
|
}
|
|
2327
3100
|
});
|