@kaynooo/cli-dev 0.5.1 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +629 -46
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/cli.ts
|
|
5
|
-
import
|
|
5
|
+
import process15 from "process";
|
|
6
6
|
// ../kit/src/args.ts
|
|
7
7
|
import process6 from "process";
|
|
8
8
|
import { parseArgs } from "util";
|
|
@@ -10,6 +10,24 @@ import { parseArgs } from "util";
|
|
|
10
10
|
// ../kit/src/format.ts
|
|
11
11
|
import process4 from "process";
|
|
12
12
|
|
|
13
|
+
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
|
|
14
|
+
var N = new Map;
|
|
15
|
+
var Nt = /\s+\S*$/;
|
|
16
|
+
var Y = /\s/;
|
|
17
|
+
function ko(t, e, r = "...") {
|
|
18
|
+
let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
|
|
19
|
+
if (t.length <= e)
|
|
20
|
+
return t;
|
|
21
|
+
let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
|
|
22
|
+
if (o && !Y.test(t[c.length] ?? " "))
|
|
23
|
+
c = c.replace(Nt, "") || c;
|
|
24
|
+
if (o)
|
|
25
|
+
c = c.trimEnd();
|
|
26
|
+
return s ? (c + n).slice(0, l) : c + n;
|
|
27
|
+
}
|
|
28
|
+
var 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));
|
|
29
|
+
var z = new Map;
|
|
30
|
+
|
|
13
31
|
// ../kit/src/mode.ts
|
|
14
32
|
import process2 from "process";
|
|
15
33
|
var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
@@ -27,15 +45,18 @@ function outputMode(stream = process2.stdout, env = process2.env) {
|
|
|
27
45
|
return "terminal";
|
|
28
46
|
return isSet(env.CI) ? "ci" : "pipe";
|
|
29
47
|
}
|
|
48
|
+
function isInteractive(streams = process2) {
|
|
49
|
+
return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
|
|
50
|
+
}
|
|
30
51
|
|
|
31
52
|
// ../kit/src/style.ts
|
|
32
53
|
import process3 from "process";
|
|
33
54
|
|
|
34
55
|
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
35
|
-
var
|
|
56
|
+
var G2 = /^[a-f0-9]+$/i;
|
|
36
57
|
function b(r) {
|
|
37
58
|
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
38
|
-
if (!
|
|
59
|
+
if (!G2.test(e))
|
|
39
60
|
return [0, 0, 0];
|
|
40
61
|
if (e.length === 3 || e.length === 4)
|
|
41
62
|
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
@@ -43,7 +64,7 @@ function b(r) {
|
|
|
43
64
|
throw Error(`Invalid hex color length: ${e.length}`);
|
|
44
65
|
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
45
66
|
}
|
|
46
|
-
var
|
|
67
|
+
var B2 = { 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") => {
|
|
47
68
|
let [l, n, c] = b(r);
|
|
48
69
|
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
49
70
|
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
@@ -61,7 +82,7 @@ function f(r, e = []) {
|
|
|
61
82
|
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
62
83
|
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
63
84
|
return new Proxy(c, { get(t, i) {
|
|
64
|
-
let a =
|
|
85
|
+
let a = B2[i];
|
|
65
86
|
if (Array.isArray(a)) {
|
|
66
87
|
let s = g.get(i);
|
|
67
88
|
if (s === undefined)
|
|
@@ -109,11 +130,34 @@ var STATUS_WORDS = {
|
|
|
109
130
|
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
110
131
|
|
|
111
132
|
// ../kit/src/format.ts
|
|
133
|
+
var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
134
|
+
function formatSeconds(total) {
|
|
135
|
+
let rest = Math.max(0, Math.round(total));
|
|
136
|
+
const amounts = UNITS.map(([unit, size]) => {
|
|
137
|
+
const amount = Math.floor(rest / size);
|
|
138
|
+
rest -= amount * size;
|
|
139
|
+
return `${amount}${unit}`;
|
|
140
|
+
});
|
|
141
|
+
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
142
|
+
if (first === -1)
|
|
143
|
+
return "0s";
|
|
144
|
+
const next = amounts[first + 1];
|
|
145
|
+
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
146
|
+
}
|
|
147
|
+
function formatDuration(ms) {
|
|
148
|
+
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
149
|
+
}
|
|
112
150
|
function upTo(text, separator) {
|
|
113
151
|
const end = text.indexOf(separator);
|
|
114
152
|
return end === -1 ? text : text.slice(0, end);
|
|
115
153
|
}
|
|
154
|
+
function truncate(text, width) {
|
|
155
|
+
return ko(text, width, { suffix: "\u2026", includeSuffix: true });
|
|
156
|
+
}
|
|
116
157
|
var ESCAPE = String.fromCharCode(27);
|
|
158
|
+
function textWidth(text) {
|
|
159
|
+
return Bun.stringWidth(text);
|
|
160
|
+
}
|
|
117
161
|
function jsonText(value, replacer, { stream = process4.stdout, env = process4.env } = {}) {
|
|
118
162
|
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
119
163
|
}
|
|
@@ -123,7 +167,7 @@ function printJson(value) {
|
|
|
123
167
|
|
|
124
168
|
// ../kit/src/help.ts
|
|
125
169
|
import process5 from "process";
|
|
126
|
-
var OPTIONAL =
|
|
170
|
+
var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
127
171
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
128
172
|
var FULL_STOP = /\.$/;
|
|
129
173
|
function usageLine(usage, colors = paint(process5.stdout)) {
|
|
@@ -162,29 +206,40 @@ function exampleRows(examples, colors = paint(process5.stdout)) {
|
|
|
162
206
|
return [];
|
|
163
207
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
164
208
|
}
|
|
209
|
+
var MAX_INLINE_CHOICES = 24;
|
|
165
210
|
function optionRows(options, colors = paint(process5.stdout)) {
|
|
166
211
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
167
212
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
168
|
-
const
|
|
213
|
+
const choices = option.choices?.join("|");
|
|
214
|
+
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
215
|
+
const named = inline ? `<${choices}>` : "<value>";
|
|
169
216
|
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
170
217
|
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
171
|
-
|
|
218
|
+
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
219
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
172
220
|
});
|
|
173
221
|
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
174
222
|
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
175
223
|
}
|
|
176
224
|
|
|
177
225
|
// ../kit/src/text.ts
|
|
178
|
-
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
179
226
|
function distance(a, b) {
|
|
180
|
-
|
|
181
|
-
|
|
227
|
+
const left = [...a];
|
|
228
|
+
const right = [...b];
|
|
229
|
+
let before = [];
|
|
230
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
231
|
+
for (const [i, x] of left.entries()) {
|
|
182
232
|
const current = [i + 1];
|
|
183
|
-
for (const [j,
|
|
184
|
-
|
|
233
|
+
for (const [j, y] of right.entries()) {
|
|
234
|
+
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
235
|
+
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
236
|
+
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
237
|
+
current.push(cost);
|
|
238
|
+
}
|
|
239
|
+
before = previous;
|
|
185
240
|
previous = current;
|
|
186
241
|
}
|
|
187
|
-
return previous[
|
|
242
|
+
return previous[right.length] ?? 0;
|
|
188
243
|
}
|
|
189
244
|
function closest(name, names) {
|
|
190
245
|
const started = names.find((known) => known.startsWith(name));
|
|
@@ -254,7 +309,7 @@ class Completing {
|
|
|
254
309
|
}
|
|
255
310
|
var completion = { active: false };
|
|
256
311
|
var OUTPUT_OPTIONS = {
|
|
257
|
-
color: { type: "string", description: "auto (on a terminal alone
|
|
312
|
+
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
258
313
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
259
314
|
};
|
|
260
315
|
function applyOutput(color, plain, env = process6.env) {
|
|
@@ -477,13 +532,91 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
|
477
532
|
// ../kit/src/cli.ts
|
|
478
533
|
import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
|
|
479
534
|
import { dirname as dirname2, join as join2 } from "path";
|
|
480
|
-
import
|
|
535
|
+
import process10 from "process";
|
|
536
|
+
|
|
537
|
+
// ../kit/src/completions.ts
|
|
538
|
+
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
539
|
+
var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
|
|
540
|
+
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
541
|
+
set -l current (commandline -ct)
|
|
542
|
+
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
543
|
+
if test "$line" = __files__
|
|
544
|
+
__fish_complete_path $current
|
|
545
|
+
else
|
|
546
|
+
echo $line
|
|
547
|
+
end
|
|
548
|
+
end
|
|
549
|
+
end`;
|
|
550
|
+
var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
551
|
+
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
552
|
+
local -a lines
|
|
553
|
+
COMPREPLY=()
|
|
554
|
+
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
555
|
+
for line in "\${lines[@]}"; do
|
|
556
|
+
if [[ $line == __files__ ]]; then
|
|
557
|
+
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
558
|
+
else
|
|
559
|
+
words+="\${line%%$'\\t'*}"$'\\n'
|
|
560
|
+
fi
|
|
561
|
+
done
|
|
562
|
+
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
563
|
+
}`;
|
|
564
|
+
var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
565
|
+
local line
|
|
566
|
+
local -a described plain
|
|
567
|
+
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
568
|
+
if [[ $line == __files__ ]]; then
|
|
569
|
+
_files
|
|
570
|
+
elif [[ $line == *$'\\t'* ]]; then
|
|
571
|
+
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
572
|
+
else
|
|
573
|
+
plain+=("$line")
|
|
574
|
+
fi
|
|
575
|
+
done
|
|
576
|
+
(( \${#described} )) && _describe -V value described
|
|
577
|
+
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
578
|
+
return 0
|
|
579
|
+
}`;
|
|
580
|
+
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
581
|
+
if (shell === "fish")
|
|
582
|
+
return `${header}
|
|
583
|
+
${FISH_FUNCTION}
|
|
584
|
+
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
585
|
+
`).join("")}`;
|
|
586
|
+
if (shell === "bash")
|
|
587
|
+
return `${header}
|
|
588
|
+
${BASH_FUNCTION}
|
|
589
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
590
|
+
`;
|
|
591
|
+
return `${header}
|
|
592
|
+
${ZSH_FUNCTION}
|
|
593
|
+
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
594
|
+
`;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// ../kit/src/notify.ts
|
|
598
|
+
import process8 from "process";
|
|
599
|
+
var NOTIFY_AFTER_MS = 1e4;
|
|
600
|
+
var CANCELLED = 130;
|
|
601
|
+
function base64(text) {
|
|
602
|
+
return Buffer.from(text).toString("base64");
|
|
603
|
+
}
|
|
604
|
+
function notification(title, body, env = process8.env) {
|
|
605
|
+
const id = `kit${process8.pid}`;
|
|
606
|
+
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\\`];
|
|
607
|
+
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
608
|
+
}
|
|
609
|
+
function notifyEnd(command, code, ms, { stream = process8.stderr, env = process8.env } = {}) {
|
|
610
|
+
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
611
|
+
return;
|
|
612
|
+
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
613
|
+
}
|
|
481
614
|
|
|
482
615
|
// ../kit/src/usage.ts
|
|
483
616
|
import { appendFileSync, mkdirSync } from "fs";
|
|
484
617
|
import { homedir } from "os";
|
|
485
618
|
import { dirname, isAbsolute, join } from "path";
|
|
486
|
-
import
|
|
619
|
+
import process9 from "process";
|
|
487
620
|
|
|
488
621
|
// ../kit/src/logs.ts
|
|
489
622
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -497,14 +630,14 @@ var usageError;
|
|
|
497
630
|
function noteUsageError(message) {
|
|
498
631
|
usageError = message;
|
|
499
632
|
}
|
|
500
|
-
function stateHome(env =
|
|
633
|
+
function stateHome(env = process9.env) {
|
|
501
634
|
const dir = env.XDG_STATE_HOME;
|
|
502
635
|
return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
|
|
503
636
|
}
|
|
504
|
-
function usagePath(env =
|
|
637
|
+
function usagePath(env = process9.env) {
|
|
505
638
|
return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
506
639
|
}
|
|
507
|
-
function usageRecorded(env =
|
|
640
|
+
function usageRecorded(env = process9.env) {
|
|
508
641
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
509
642
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
510
643
|
}
|
|
@@ -518,7 +651,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
518
651
|
usageError = undefined;
|
|
519
652
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
520
653
|
}
|
|
521
|
-
function recordUsage(entry, env =
|
|
654
|
+
function recordUsage(entry, env = process9.env) {
|
|
522
655
|
if (!usageRecorded(env))
|
|
523
656
|
return;
|
|
524
657
|
try {
|
|
@@ -534,7 +667,11 @@ var LEVEL_OPTIONS = {
|
|
|
534
667
|
...OUTPUT_OPTIONS,
|
|
535
668
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
536
669
|
};
|
|
537
|
-
var TOP_OPTIONS = {
|
|
670
|
+
var TOP_OPTIONS = {
|
|
671
|
+
...LEVEL_OPTIONS,
|
|
672
|
+
version: { type: "boolean", short: "v", description: "print the version" },
|
|
673
|
+
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
674
|
+
};
|
|
538
675
|
async function commandRows(all, colors) {
|
|
539
676
|
const commands = shown(all);
|
|
540
677
|
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
@@ -608,8 +745,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
608
745
|
`);
|
|
609
746
|
}
|
|
610
747
|
function printError(prefix, message, hint, cause) {
|
|
611
|
-
const colors = paint(
|
|
612
|
-
const styled = takesControlCodes(
|
|
748
|
+
const colors = paint(process10.stderr);
|
|
749
|
+
const styled = takesControlCodes(process10.stderr);
|
|
613
750
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
614
751
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
615
752
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -652,11 +789,11 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
652
789
|
}
|
|
653
790
|
}
|
|
654
791
|
if (name === undefined && level.path.length > 1) {
|
|
655
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
792
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stderr));
|
|
656
793
|
return 2;
|
|
657
794
|
}
|
|
658
795
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
659
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
796
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stdout));
|
|
660
797
|
return 0;
|
|
661
798
|
}
|
|
662
799
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
@@ -767,6 +904,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
|
|
|
767
904
|
}
|
|
768
905
|
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
769
906
|
}
|
|
907
|
+
var COMPLETIONS = "--completions";
|
|
908
|
+
function flagValue([flag = "", ...rest]) {
|
|
909
|
+
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
910
|
+
}
|
|
911
|
+
function printCompletionScript(name, args) {
|
|
912
|
+
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
913
|
+
if (shell === undefined || args.length !== 1) {
|
|
914
|
+
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
915
|
+
return 2;
|
|
916
|
+
}
|
|
917
|
+
console.log(completionScript(shell, [name]).trimEnd());
|
|
918
|
+
return 0;
|
|
919
|
+
}
|
|
770
920
|
async function printCandidates(found) {
|
|
771
921
|
for (const line of await found)
|
|
772
922
|
console.log(line);
|
|
@@ -791,10 +941,15 @@ async function runCli(cli, argv = scriptArgs()) {
|
|
|
791
941
|
const version = cli.version ?? packageVersion();
|
|
792
942
|
if (argv[0] === COMPLETE)
|
|
793
943
|
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
944
|
+
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
945
|
+
return printCompletionScript(cli.name, flagValue(argv));
|
|
946
|
+
const started = performance.now();
|
|
794
947
|
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 });
|
|
948
|
+
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
949
|
+
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
795
950
|
if (cli.usage !== false) {
|
|
796
951
|
try {
|
|
797
|
-
recordUsage(usageEntry(cli.name,
|
|
952
|
+
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
798
953
|
} catch {}
|
|
799
954
|
}
|
|
800
955
|
return code;
|
|
@@ -815,13 +970,423 @@ function commandPath(scope, argv) {
|
|
|
815
970
|
return path.length === 0 ? undefined : path.join(" ");
|
|
816
971
|
}
|
|
817
972
|
// ../kit/src/folders.ts
|
|
973
|
+
import { homedir as homedir2 } from "os";
|
|
974
|
+
import { join as join3 } from "path";
|
|
975
|
+
import process11 from "process";
|
|
818
976
|
var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
977
|
+
function cacheFolder({ home = homedir2(), env = process11.env } = {}) {
|
|
978
|
+
return env.XDG_CACHE_HOME ?? join3(home, ".cache");
|
|
979
|
+
}
|
|
819
980
|
// ../kit/src/secrets.ts
|
|
820
981
|
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
821
982
|
// ../kit/src/sessions.ts
|
|
822
983
|
var {Glob } = globalThis.Bun;
|
|
823
984
|
var SESSION_FILES = new Glob("*.json");
|
|
824
985
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
986
|
+
// ../kit/src/prompt.ts
|
|
987
|
+
import process14 from "process";
|
|
988
|
+
|
|
989
|
+
// ../kit/src/answers.ts
|
|
990
|
+
import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
|
|
991
|
+
import { dirname as dirname3, join as join4 } from "path";
|
|
992
|
+
var KEPT = 50;
|
|
993
|
+
function answersFile() {
|
|
994
|
+
return join4(cacheFolder(), "kaynooo-cli", "answers.json");
|
|
995
|
+
}
|
|
996
|
+
function stored() {
|
|
997
|
+
try {
|
|
998
|
+
const parsed = JSON.parse(readFileSync3(answersFile(), "utf-8"));
|
|
999
|
+
if (typeof parsed !== "object" || parsed === null)
|
|
1000
|
+
return {};
|
|
1001
|
+
return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
|
|
1002
|
+
} catch {
|
|
1003
|
+
return {};
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
function earlierAnswers(key) {
|
|
1007
|
+
return stored()[key] ?? [];
|
|
1008
|
+
}
|
|
1009
|
+
function rememberAnswer(key, answer) {
|
|
1010
|
+
const all = stored();
|
|
1011
|
+
const file = answersFile();
|
|
1012
|
+
all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
|
|
1013
|
+
try {
|
|
1014
|
+
mkdirSync2(dirname3(file), { recursive: true });
|
|
1015
|
+
writeFileSync(file, JSON.stringify(all));
|
|
1016
|
+
} catch {}
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
// ../kit/src/job.ts
|
|
1020
|
+
import process13 from "process";
|
|
1021
|
+
function stopJob() {
|
|
1022
|
+
process13.kill(0, "SIGTSTP");
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
// ../kit/src/picker/line.ts
|
|
1026
|
+
var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
|
|
1027
|
+
var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
|
|
1028
|
+
var FORWARD_KILLS = new Set(["killnext", "killend"]);
|
|
1029
|
+
function isEditKey(key) {
|
|
1030
|
+
return EDIT_KEYS.has(key);
|
|
1031
|
+
}
|
|
1032
|
+
function endsKills(key) {
|
|
1033
|
+
return typeof key !== "object" && !isEditKey(key);
|
|
1034
|
+
}
|
|
1035
|
+
var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
|
|
1036
|
+
var SPACE = /\s/;
|
|
1037
|
+
function isWord(char) {
|
|
1038
|
+
return char !== undefined && WORD_CHARACTER.test(char);
|
|
1039
|
+
}
|
|
1040
|
+
function wordStart(chars, from) {
|
|
1041
|
+
let at = from;
|
|
1042
|
+
while (at > 0 && !isWord(chars[at - 1]))
|
|
1043
|
+
at--;
|
|
1044
|
+
while (at > 0 && isWord(chars[at - 1]))
|
|
1045
|
+
at--;
|
|
1046
|
+
return at;
|
|
1047
|
+
}
|
|
1048
|
+
function wordEnd(chars, from) {
|
|
1049
|
+
let at = from;
|
|
1050
|
+
while (at < chars.length && !isWord(chars[at]))
|
|
1051
|
+
at++;
|
|
1052
|
+
while (at < chars.length && isWord(chars[at]))
|
|
1053
|
+
at++;
|
|
1054
|
+
return at;
|
|
1055
|
+
}
|
|
1056
|
+
function spacedStart(chars, from) {
|
|
1057
|
+
let at = from;
|
|
1058
|
+
while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
|
|
1059
|
+
at--;
|
|
1060
|
+
while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
|
|
1061
|
+
at--;
|
|
1062
|
+
return at;
|
|
1063
|
+
}
|
|
1064
|
+
function cut(chars, from, to) {
|
|
1065
|
+
return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
|
|
1066
|
+
}
|
|
1067
|
+
function insert(chars, at, text) {
|
|
1068
|
+
const typed = [...text];
|
|
1069
|
+
return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
|
|
1070
|
+
}
|
|
1071
|
+
function editLine(line, key) {
|
|
1072
|
+
const { killed = "", chained = false } = line;
|
|
1073
|
+
const chars = [...line.text];
|
|
1074
|
+
const at = Math.min(Math.max(line.caret, 0), chars.length);
|
|
1075
|
+
const edited = edit(chars, at, key, killed);
|
|
1076
|
+
if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
|
|
1077
|
+
return line.killed === undefined ? edited : { ...edited, killed };
|
|
1078
|
+
const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
|
|
1079
|
+
if (taken === "")
|
|
1080
|
+
return { ...edited, killed, chained };
|
|
1081
|
+
if (!chained)
|
|
1082
|
+
return { ...edited, killed: taken, chained: true };
|
|
1083
|
+
return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
|
|
1084
|
+
}
|
|
1085
|
+
function edit(chars, at, key, killed) {
|
|
1086
|
+
const text = chars.join("");
|
|
1087
|
+
if (typeof key === "object")
|
|
1088
|
+
return insert(chars, at, key.text);
|
|
1089
|
+
switch (key) {
|
|
1090
|
+
case "left":
|
|
1091
|
+
return { text, caret: Math.max(at - 1, 0) };
|
|
1092
|
+
case "right":
|
|
1093
|
+
return { text, caret: Math.min(at + 1, chars.length) };
|
|
1094
|
+
case "wordleft":
|
|
1095
|
+
return { text, caret: wordStart(chars, at) };
|
|
1096
|
+
case "wordright":
|
|
1097
|
+
return { text, caret: wordEnd(chars, at) };
|
|
1098
|
+
case "linestart":
|
|
1099
|
+
return { text, caret: 0 };
|
|
1100
|
+
case "lineend":
|
|
1101
|
+
return { text, caret: chars.length };
|
|
1102
|
+
case "erase":
|
|
1103
|
+
return cut(chars, Math.max(at - 1, 0), at);
|
|
1104
|
+
case "delete":
|
|
1105
|
+
return cut(chars, at, Math.min(at + 1, chars.length));
|
|
1106
|
+
case "word":
|
|
1107
|
+
return cut(chars, spacedStart(chars, at), at);
|
|
1108
|
+
case "killword":
|
|
1109
|
+
return cut(chars, wordStart(chars, at), at);
|
|
1110
|
+
case "killnext":
|
|
1111
|
+
return cut(chars, at, wordEnd(chars, at));
|
|
1112
|
+
case "clear":
|
|
1113
|
+
return cut(chars, 0, at);
|
|
1114
|
+
case "killend":
|
|
1115
|
+
return cut(chars, at, chars.length);
|
|
1116
|
+
case "yank":
|
|
1117
|
+
return insert(chars, at, killed);
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
function visible({ text, caret }, room) {
|
|
1121
|
+
const chars = [...text];
|
|
1122
|
+
const at = Math.min(Math.max(caret, 0), chars.length);
|
|
1123
|
+
const cells = at === chars.length ? [...chars, " "] : chars;
|
|
1124
|
+
const widths = cells.map((char) => Bun.stringWidth(char));
|
|
1125
|
+
const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
|
|
1126
|
+
const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
|
|
1127
|
+
let start = at;
|
|
1128
|
+
let end = at + 1;
|
|
1129
|
+
while (start > 0 && fits(start - 1, end))
|
|
1130
|
+
start--;
|
|
1131
|
+
while (end < cells.length && fits(start, end + 1))
|
|
1132
|
+
end++;
|
|
1133
|
+
const left = start > 0 ? "\u2026" : "";
|
|
1134
|
+
const right = end < cells.length ? "\u2026" : "";
|
|
1135
|
+
return { before: left + chars.slice(start, at).join(""), at: chars[at], after: chars.slice(at + 1, end).join("") + right, column: left.length + width(start, at) };
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
// ../kit/src/picker/score.ts
|
|
1139
|
+
var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
|
|
1140
|
+
var NONE = Number.NEGATIVE_INFINITY;
|
|
1141
|
+
|
|
1142
|
+
// ../kit/src/picker/state.ts
|
|
1143
|
+
var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
|
|
1144
|
+
var PASTE_START = "\x1B[200~";
|
|
1145
|
+
var PASTE_END = "\x1B[201~";
|
|
1146
|
+
var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
|
|
1147
|
+
var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
|
|
1148
|
+
var WHEEL_LINES = 3;
|
|
1149
|
+
var KEYS = {
|
|
1150
|
+
"\x1B[A": "up",
|
|
1151
|
+
"\x1BOA": "up",
|
|
1152
|
+
"\x10": "up",
|
|
1153
|
+
"\x1B[B": "down",
|
|
1154
|
+
"\x1BOB": "down",
|
|
1155
|
+
"\x0E": "down",
|
|
1156
|
+
"\x1B[5~": "pageup",
|
|
1157
|
+
"\x1B[6~": "pagedown",
|
|
1158
|
+
"\x1B[H": "home",
|
|
1159
|
+
"\x1B[1~": "home",
|
|
1160
|
+
"\x1BOH": "home",
|
|
1161
|
+
"\x1B[F": "end",
|
|
1162
|
+
"\x1B[4~": "end",
|
|
1163
|
+
"\x1BOF": "end",
|
|
1164
|
+
"\r": "enter",
|
|
1165
|
+
"\n": "enter",
|
|
1166
|
+
"\x03": "cancel",
|
|
1167
|
+
"\x1B": "cancel",
|
|
1168
|
+
"\x1B[D": "left",
|
|
1169
|
+
"\x1BOD": "left",
|
|
1170
|
+
"\x1B[C": "right",
|
|
1171
|
+
"\x1BOC": "right",
|
|
1172
|
+
"\x1B[1;5D": "wordleft",
|
|
1173
|
+
"\x1B[1;3D": "wordleft",
|
|
1174
|
+
"\x1Bb": "wordleft",
|
|
1175
|
+
"\x1B[1;5C": "wordright",
|
|
1176
|
+
"\x1B[1;3C": "wordright",
|
|
1177
|
+
"\x1Bf": "wordright",
|
|
1178
|
+
"\x01": "linestart",
|
|
1179
|
+
"\x05": "lineend",
|
|
1180
|
+
"\x7F": "erase",
|
|
1181
|
+
"\x1B[3~": "delete",
|
|
1182
|
+
"\b": "killword",
|
|
1183
|
+
"\x1B\x7F": "killword",
|
|
1184
|
+
"\x1B[3;5~": "killnext",
|
|
1185
|
+
"\x1Bd": "killnext",
|
|
1186
|
+
"\x15": "clear",
|
|
1187
|
+
"\v": "killend",
|
|
1188
|
+
"\x17": "word",
|
|
1189
|
+
"\x19": "yank",
|
|
1190
|
+
"\x1A": "suspend",
|
|
1191
|
+
"\t": "tab",
|
|
1192
|
+
"\x1F": "help",
|
|
1193
|
+
"\x1BOP": "help",
|
|
1194
|
+
"\x1B[11~": "help"
|
|
1195
|
+
};
|
|
1196
|
+
function repeat(value, count) {
|
|
1197
|
+
return Array.from({ length: count }).fill(value);
|
|
1198
|
+
}
|
|
1199
|
+
function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
1200
|
+
const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
|
|
1201
|
+
return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
|
|
1202
|
+
const wheel = MOUSE.exec(sequence)?.[1];
|
|
1203
|
+
if (wheel !== undefined)
|
|
1204
|
+
return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
|
|
1205
|
+
const named = codes.get(sequence);
|
|
1206
|
+
const key = named === undefined ? KEYS[sequence] : { ctrl: named };
|
|
1207
|
+
if (sequence === PASTE_START || sequence === PASTE_END) {
|
|
1208
|
+
paste.active = sequence === PASTE_START;
|
|
1209
|
+
return [];
|
|
1210
|
+
}
|
|
1211
|
+
if (paste.active && (sequence === "\r" || sequence === `
|
|
1212
|
+
`))
|
|
1213
|
+
return [];
|
|
1214
|
+
if (key !== undefined)
|
|
1215
|
+
return [key];
|
|
1216
|
+
return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
|
|
1217
|
+
});
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
// ../kit/src/redraw.ts
|
|
1221
|
+
var SYNC_START = "\x1B[?2026h";
|
|
1222
|
+
var SYNC_END = "\x1B[?2026l";
|
|
1223
|
+
function overwrite(lines, columns) {
|
|
1224
|
+
return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
|
|
1225
|
+
`);
|
|
1226
|
+
}
|
|
1227
|
+
function rowsTaken(lines, columns) {
|
|
1228
|
+
return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
// ../kit/src/prompt.ts
|
|
1232
|
+
var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
|
|
1233
|
+
var MAX_LISTED = 12;
|
|
1234
|
+
function readKeys(input, paste = { active: false }) {
|
|
1235
|
+
return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
|
|
1236
|
+
}
|
|
1237
|
+
function roomAfter(question, columns) {
|
|
1238
|
+
return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
|
|
1239
|
+
}
|
|
1240
|
+
function withCaret(colors, line, room, dim = false) {
|
|
1241
|
+
const { before, at, after } = visible(line, room);
|
|
1242
|
+
const tone = dim ? colors.dim : (text) => text;
|
|
1243
|
+
return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
|
|
1244
|
+
}
|
|
1245
|
+
function sharedStart(texts) {
|
|
1246
|
+
const [first = [], ...rest] = texts.map((text) => [...text]);
|
|
1247
|
+
let length = first.length;
|
|
1248
|
+
for (const chars of rest) {
|
|
1249
|
+
const differs = chars.findIndex((char, index) => char !== first[index]);
|
|
1250
|
+
length = Math.min(length, differs === -1 ? chars.length : differs);
|
|
1251
|
+
}
|
|
1252
|
+
return first.slice(0, length).join("");
|
|
1253
|
+
}
|
|
1254
|
+
function listed2(colors, found, columns) {
|
|
1255
|
+
const shared = sharedStart(found);
|
|
1256
|
+
const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
|
|
1257
|
+
const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
|
|
1258
|
+
const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
|
|
1259
|
+
return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
|
|
1260
|
+
}
|
|
1261
|
+
async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
|
|
1262
|
+
let line = { text: "", caret: 0 };
|
|
1263
|
+
let invalid;
|
|
1264
|
+
let completions = [];
|
|
1265
|
+
const remembered = history === undefined || mask ? undefined : history;
|
|
1266
|
+
const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
|
|
1267
|
+
let recalled = -1;
|
|
1268
|
+
let draft = line;
|
|
1269
|
+
const taken = () => line.text === "" ? fallback ?? "" : line.text;
|
|
1270
|
+
const shown = () => mask ? "*".repeat([...taken()].length) : taken();
|
|
1271
|
+
const accepted = await ask(question, settings, (colors, state, { columns }) => {
|
|
1272
|
+
if (state !== "asking")
|
|
1273
|
+
return [answer(colors, question, state, shown())];
|
|
1274
|
+
const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
|
|
1275
|
+
return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
|
|
1276
|
+
}, (key) => {
|
|
1277
|
+
if (key === "cancel")
|
|
1278
|
+
return "cancel";
|
|
1279
|
+
invalid = undefined;
|
|
1280
|
+
completions = [];
|
|
1281
|
+
if (line.chained === true && endsKills(key))
|
|
1282
|
+
line = { ...line, chained: false };
|
|
1283
|
+
if (key === "tab") {
|
|
1284
|
+
const chars = [...line.text];
|
|
1285
|
+
const before = chars.slice(0, line.caret).join("");
|
|
1286
|
+
const found = complete?.(before) ?? [];
|
|
1287
|
+
const filled = sharedStart(found);
|
|
1288
|
+
if ([...filled].length > [...before].length)
|
|
1289
|
+
line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
|
|
1290
|
+
else
|
|
1291
|
+
completions = found;
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
1294
|
+
if (key === "enter") {
|
|
1295
|
+
invalid = validate?.(taken());
|
|
1296
|
+
return invalid === undefined ? "enter" : undefined;
|
|
1297
|
+
}
|
|
1298
|
+
if (key === "up" || key === "down") {
|
|
1299
|
+
const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
|
|
1300
|
+
if (recalled === -1)
|
|
1301
|
+
draft = line;
|
|
1302
|
+
recalled = to;
|
|
1303
|
+
const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
|
|
1304
|
+
line = { ...shown, killed: line.killed ?? "" };
|
|
1305
|
+
return;
|
|
1306
|
+
}
|
|
1307
|
+
const edit = { home: "linestart", end: "lineend" }[key] ?? key;
|
|
1308
|
+
if (typeof edit === "object" || isEditKey(edit))
|
|
1309
|
+
line = editLine(line, edit);
|
|
1310
|
+
return;
|
|
1311
|
+
});
|
|
1312
|
+
if (!accepted)
|
|
1313
|
+
return;
|
|
1314
|
+
if (remembered !== undefined && taken() !== "")
|
|
1315
|
+
rememberAnswer(remembered, taken());
|
|
1316
|
+
return taken();
|
|
1317
|
+
}
|
|
1318
|
+
function answer(colors, question, state, picked) {
|
|
1319
|
+
return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
|
|
1320
|
+
}
|
|
1321
|
+
async function ask(question, { hint, terminal = process14 }, render, press) {
|
|
1322
|
+
const { stdin, stderr } = terminal;
|
|
1323
|
+
if (!isInteractive(terminal))
|
|
1324
|
+
fail(`cannot ask "${question}" off a terminal`, 2, hint);
|
|
1325
|
+
const colors = paint(stderr);
|
|
1326
|
+
let current = "asking";
|
|
1327
|
+
let outcome;
|
|
1328
|
+
const columns = () => stderr.columns || 80;
|
|
1329
|
+
const draw = (state, last = false) => {
|
|
1330
|
+
const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
|
|
1331
|
+
const rows = rowsTaken(frame, columns());
|
|
1332
|
+
stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
|
|
1333
|
+
current = state;
|
|
1334
|
+
};
|
|
1335
|
+
const redraw = () => draw(current);
|
|
1336
|
+
const paste = { active: false };
|
|
1337
|
+
const stop = terminal.stop ?? (terminal === process14 ? stopJob : undefined);
|
|
1338
|
+
const suspend = () => {
|
|
1339
|
+
if (stop === undefined)
|
|
1340
|
+
return;
|
|
1341
|
+
stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
|
|
1342
|
+
stdin.setRawMode(false);
|
|
1343
|
+
stop();
|
|
1344
|
+
stdin.setRawMode(true);
|
|
1345
|
+
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
1346
|
+
};
|
|
1347
|
+
try {
|
|
1348
|
+
stderr.on?.("resize", redraw);
|
|
1349
|
+
stdin.setRawMode(true);
|
|
1350
|
+
stdin.resume();
|
|
1351
|
+
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
1352
|
+
draw("asking");
|
|
1353
|
+
return await new Promise((resolve) => {
|
|
1354
|
+
function onData(data) {
|
|
1355
|
+
for (const key of readKeys(data.toString(), paste)) {
|
|
1356
|
+
if (key === "suspend") {
|
|
1357
|
+
suspend();
|
|
1358
|
+
continue;
|
|
1359
|
+
}
|
|
1360
|
+
const pressed = press(key);
|
|
1361
|
+
if (pressed !== undefined) {
|
|
1362
|
+
settle(pressed);
|
|
1363
|
+
return;
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
draw("asking");
|
|
1367
|
+
}
|
|
1368
|
+
function onEnd() {
|
|
1369
|
+
settle("cancel");
|
|
1370
|
+
}
|
|
1371
|
+
function settle(settled) {
|
|
1372
|
+
outcome = settled;
|
|
1373
|
+
stdin.off("data", onData);
|
|
1374
|
+
stdin.off("end", onEnd);
|
|
1375
|
+
resolve(settled === "enter");
|
|
1376
|
+
}
|
|
1377
|
+
stdin.on("data", onData);
|
|
1378
|
+
stdin.on("end", onEnd);
|
|
1379
|
+
});
|
|
1380
|
+
} finally {
|
|
1381
|
+
stderr.off?.("resize", redraw);
|
|
1382
|
+
draw(outcome ?? "cancel", true);
|
|
1383
|
+
stderr.write(`
|
|
1384
|
+
\x1B[?25h\x1B[?2004l`);
|
|
1385
|
+
stdin.setRawMode(false);
|
|
1386
|
+
stdin.pause();
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
|
|
825
1390
|
// src/encode.ts
|
|
826
1391
|
function b64Encode(bytes, url = false) {
|
|
827
1392
|
return Buffer.from(bytes).toString(url ? "base64url" : "base64");
|
|
@@ -841,6 +1406,15 @@ var ALGORITHMS = ["sha256", "sha1", "md5", "sha512"];
|
|
|
841
1406
|
function hashHex(algorithm, bytes) {
|
|
842
1407
|
return new Bun.CryptoHasher(algorithm).update(bytes).digest("hex");
|
|
843
1408
|
}
|
|
1409
|
+
async function hashStream(algorithm, stream) {
|
|
1410
|
+
const hasher = new Bun.CryptoHasher(algorithm);
|
|
1411
|
+
let bytes = 0;
|
|
1412
|
+
for await (const chunk of stream) {
|
|
1413
|
+
hasher.update(chunk);
|
|
1414
|
+
bytes += chunk.length;
|
|
1415
|
+
}
|
|
1416
|
+
return { digest: hasher.digest("hex"), bytes };
|
|
1417
|
+
}
|
|
844
1418
|
|
|
845
1419
|
// src/ids.ts
|
|
846
1420
|
var CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
@@ -881,7 +1455,7 @@ async function publicIp(family, service = IP_SERVICE) {
|
|
|
881
1455
|
}
|
|
882
1456
|
|
|
883
1457
|
// src/time.ts
|
|
884
|
-
var
|
|
1458
|
+
var UNITS2 = [["d", 86400000], ["h", 3600000], ["m", 60000], ["s", 1000]];
|
|
885
1459
|
var DURATION_UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
|
|
886
1460
|
function parts(ms, timeZone) {
|
|
887
1461
|
const formatter = new Intl.DateTimeFormat("en-US", { timeZone, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", timeZoneName: "longOffset" });
|
|
@@ -902,7 +1476,7 @@ function offsetAt(ms, timeZone) {
|
|
|
902
1476
|
function humanDuration(ms) {
|
|
903
1477
|
let rest = Math.floor(Math.abs(ms) / 1000) * 1000;
|
|
904
1478
|
const out = [];
|
|
905
|
-
for (const [name, size] of
|
|
1479
|
+
for (const [name, size] of UNITS2) {
|
|
906
1480
|
const count = Math.floor(rest / size);
|
|
907
1481
|
if (count > 0) {
|
|
908
1482
|
out.push(`${count}${name}`);
|
|
@@ -1044,6 +1618,8 @@ function urlParts(text) {
|
|
|
1044
1618
|
|
|
1045
1619
|
// src/cli.ts
|
|
1046
1620
|
var MAX_PASSWORD_BYTES = 65536;
|
|
1621
|
+
var TRAILING_NEWLINE = /\r?\n$/;
|
|
1622
|
+
var STDIN_OR_VALUE = /^(?!-.)/;
|
|
1047
1623
|
var ZONE_OPTION = { type: "string", description: "the IANA zone of the local dates, such as Europe/Paris (default: this host's)" };
|
|
1048
1624
|
function reading(read) {
|
|
1049
1625
|
try {
|
|
@@ -1067,6 +1643,11 @@ async function textInput(argument, what) {
|
|
|
1067
1643
|
return argument;
|
|
1068
1644
|
return !isStdinPiped() ? fail(`give ${what} as an argument or pipe it on stdin`, 2) : Bun.stdin.text();
|
|
1069
1645
|
}
|
|
1646
|
+
async function secretInput(what) {
|
|
1647
|
+
if (isInteractive())
|
|
1648
|
+
return await input2(what, { mask: true }) ?? fail("cancelled", 130);
|
|
1649
|
+
return (await textInput(undefined, what)).replace(TRAILING_NEWLINE, "");
|
|
1650
|
+
}
|
|
1070
1651
|
async function bytesInput(argument, what) {
|
|
1071
1652
|
if (argument !== undefined)
|
|
1072
1653
|
return new TextEncoder().encode(argument);
|
|
@@ -1075,17 +1656,17 @@ async function bytesInput(argument, what) {
|
|
|
1075
1656
|
return new Uint8Array(await Bun.stdin.arrayBuffer());
|
|
1076
1657
|
}
|
|
1077
1658
|
function printRows(rows) {
|
|
1078
|
-
const { cyan } = paint(
|
|
1659
|
+
const { cyan } = paint(process15.stdout);
|
|
1079
1660
|
const width = Math.max(...rows.map(([label]) => label.length));
|
|
1080
1661
|
for (const [label, value] of rows)
|
|
1081
1662
|
console.log(`${cyan(label.padEnd(width))} ${value}`);
|
|
1082
1663
|
}
|
|
1083
1664
|
var PASSWORD_USAGE = `dev password [length] [format] [-b|--bcrypt [password]]: a random password of <length> bytes (default ${DEFAULT_LENGTH}) as hex, base64 (default) or base64url
|
|
1084
1665
|
|
|
1085
|
-
Printed on stdout and copied to the clipboard when a tool for it (wl-copy, xclip, xsel, pbcopy) exists (the copy is said on stderr). With --bcrypt it is the bcrypt hash (cost 10) that prints: of the password given, or of a generated one, which then prints on stderr and is the one copied. Bun writes bcrypt as $2b$, the hash prints with the $2y$ prefix htpasswd -B writes, the one Apache, nginx and traefik basic auth all accept.`;
|
|
1086
|
-
var PASSWORD_EXITS = [[0, "it printed the password or hash"], [2, "a usage error"]];
|
|
1666
|
+
Printed on stdout and copied to the clipboard when a tool for it (wl-copy, xclip, xsel, pbcopy) exists (the copy is said on stderr). With --bcrypt it is the bcrypt hash (cost 10) that prints: of the password given (- asks for it masked on a terminal, or reads it from stdin, keeping it out of the shell history), or of a generated one, which then prints on stderr and is the one copied. Bun writes bcrypt as $2b$, the hash prints with the $2y$ prefix htpasswd -B writes, the one Apache, nginx and traefik basic auth all accept.`;
|
|
1667
|
+
var PASSWORD_EXITS = [[0, "it printed the password or hash"], [2, "a usage error"], [130, "the prompt was cancelled"]];
|
|
1087
1668
|
var PASSWORD_OPTIONS = {
|
|
1088
|
-
bcrypt: { type: "string", short: "b", optional: { bare: "" }, description: "print the bcrypt hash of the password given, or of a generated one" },
|
|
1669
|
+
bcrypt: { type: "string", short: "b", optional: { bare: "", accepts: STDIN_OR_VALUE }, description: "print the bcrypt hash of the password given, or of a generated one" },
|
|
1089
1670
|
"no-copy": { type: "boolean", description: "leave the clipboard alone" },
|
|
1090
1671
|
json: jsonOption("{password?, hash?, format, bytes, copied}")
|
|
1091
1672
|
};
|
|
@@ -1096,13 +1677,14 @@ async function password(args) {
|
|
|
1096
1677
|
positionals: ["[length]", "[format]"],
|
|
1097
1678
|
candidates: { "[length]": () => ["16", "24", "32", "48", "64"], "[format]": () => FORMATS.map((format) => [format, FORMAT_NOTES[format]]) },
|
|
1098
1679
|
replaces: 'openssl rand -base64 32 and htpasswd -bnBC 10 "" <password>',
|
|
1099
|
-
examples: ["dev password", ["dev password 16 hex", "16 random bytes as 32 hex characters"], ["dev password --bcrypt
|
|
1680
|
+
examples: ["dev password", ["dev password 16 hex", "16 random bytes as 32 hex characters"], ["dev password --bcrypt -", "asks for a password and prints the hash to paste into a basic auth file"]]
|
|
1100
1681
|
});
|
|
1101
1682
|
const bytes = wholeNumber(positionals[0], "<length>", DEFAULT_LENGTH);
|
|
1102
1683
|
const format = oneOf(positionals[1] ?? "base64", "<format>", FORMATS);
|
|
1103
1684
|
if (bytes > MAX_PASSWORD_BYTES)
|
|
1104
1685
|
badUsage(`<length> takes at most ${MAX_PASSWORD_BYTES}, not ${bytes}`);
|
|
1105
|
-
const
|
|
1686
|
+
const bcrypt = values.bcrypt === "" ? undefined : values.bcrypt;
|
|
1687
|
+
const given = bcrypt === "-" ? await secretInput("the password") : bcrypt;
|
|
1106
1688
|
const secret = given ?? generatePassword(bytes, format);
|
|
1107
1689
|
const hash = values.bcrypt === undefined ? undefined : await bcryptHash(secret);
|
|
1108
1690
|
const copied = values["no-copy"] === true ? false : await copyText(given === undefined ? secret : hash ?? secret);
|
|
@@ -1111,7 +1693,7 @@ async function password(args) {
|
|
|
1111
1693
|
return 0;
|
|
1112
1694
|
}
|
|
1113
1695
|
if (copied)
|
|
1114
|
-
console.error(paint(
|
|
1696
|
+
console.error(paint(process15.stderr).dim("copied to clipboard"));
|
|
1115
1697
|
if (hash !== undefined && given === undefined)
|
|
1116
1698
|
console.error(secret);
|
|
1117
1699
|
console.log(hash ?? secret);
|
|
@@ -1119,8 +1701,8 @@ async function password(args) {
|
|
|
1119
1701
|
}
|
|
1120
1702
|
var JWT_USAGE = `dev jwt [token]: the header and payload of a JWT, with iat, nbf and exp as local and UTC dates and how far from now
|
|
1121
1703
|
|
|
1122
|
-
The token is the argument
|
|
1123
|
-
var JWT_EXITS = [[0, "it decoded the token"], [1, "it is not a JWT"], [2, "a usage error"]];
|
|
1704
|
+
The token is the argument, what is piped on stdin, or asked for masked on a terminal; a leading "Bearer " is ignored. The signature is not verified.`;
|
|
1705
|
+
var JWT_EXITS = [[0, "it decoded the token"], [1, "it is not a JWT"], [2, "a usage error"], [130, "the prompt was cancelled"]];
|
|
1124
1706
|
var JWT_OPTIONS = {
|
|
1125
1707
|
zone: ZONE_OPTION,
|
|
1126
1708
|
json: jsonOption("{header, payload, claims: [{claim, epoch, local, utc, relative}], signatureBytes}")
|
|
@@ -1133,14 +1715,14 @@ async function jwt(args) {
|
|
|
1133
1715
|
examples: ["dev jwt eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDAwMDAwMDB9.c2ln", ["pbpaste | dev jwt --json", "for a script"]]
|
|
1134
1716
|
});
|
|
1135
1717
|
const zone = zoneOf(values.zone);
|
|
1136
|
-
const token =
|
|
1718
|
+
const token = positionals[0] ?? await secretInput("the token");
|
|
1137
1719
|
const decoded = reading(() => decodeJwt(token));
|
|
1138
1720
|
const claims = claimTimes(decoded.payload, Date.now(), zone);
|
|
1139
1721
|
if (values.json === true) {
|
|
1140
1722
|
printJson({ header: decoded.header, payload: decoded.payload, claims, signatureBytes: decoded.signatureBytes });
|
|
1141
1723
|
return 0;
|
|
1142
1724
|
}
|
|
1143
|
-
const { bold } = paint(
|
|
1725
|
+
const { bold } = paint(process15.stdout);
|
|
1144
1726
|
console.log(`${bold("header")}
|
|
1145
1727
|
${JSON.stringify(decoded.header, null, 2)}
|
|
1146
1728
|
|
|
@@ -1280,18 +1862,19 @@ async function hash(args) {
|
|
|
1280
1862
|
});
|
|
1281
1863
|
const algorithm = oneOf(positionals[0] ?? "", "<algorithm>", ALGORITHMS);
|
|
1282
1864
|
const file = positionals[1];
|
|
1283
|
-
let
|
|
1865
|
+
let result;
|
|
1284
1866
|
if (file === undefined) {
|
|
1285
|
-
|
|
1867
|
+
const input = await bytesInput(undefined, "a file");
|
|
1868
|
+
result = { digest: hashHex(algorithm, input), bytes: input.length };
|
|
1286
1869
|
} else {
|
|
1287
1870
|
const source = Bun.file(file);
|
|
1288
1871
|
if (!await source.exists())
|
|
1289
1872
|
return fail(`no file ${file}`, 1);
|
|
1290
|
-
|
|
1873
|
+
result = await hashStream(algorithm, source.stream());
|
|
1291
1874
|
}
|
|
1292
|
-
const digest =
|
|
1875
|
+
const digest = result.digest;
|
|
1293
1876
|
if (values.json === true)
|
|
1294
|
-
printJson({ algorithm, hash: digest, bytes: bytes
|
|
1877
|
+
printJson({ algorithm, hash: digest, bytes: result.bytes });
|
|
1295
1878
|
else
|
|
1296
1879
|
console.log(digest);
|
|
1297
1880
|
return 0;
|
|
@@ -1325,7 +1908,7 @@ async function ip(args) {
|
|
|
1325
1908
|
}
|
|
1326
1909
|
}
|
|
1327
1910
|
if (import.meta.main) {
|
|
1328
|
-
|
|
1911
|
+
process15.exitCode = await runCli({
|
|
1329
1912
|
name: "dev",
|
|
1330
1913
|
about: "small developer utilities: passwords and bcrypt hashes, JWTs, timestamps, UUIDs, base64, URLs and file hashes",
|
|
1331
1914
|
replaces: "openssl rand, htpasswd, jwt.io, date -d, uuidgen, base64, sha256sum and one-off scripts for each",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaynooo/cli-dev",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.6.1",
|
|
5
5
|
"description": "dev: small developer utilities in one bin: random passwords and bcrypt hashes, JWT decoding, timestamps, UUIDs and ULIDs, base64, URL parts and file hashes.",
|
|
6
6
|
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -36,6 +36,6 @@
|
|
|
36
36
|
"dev": "$npm_execpath src/cli.ts"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
|
-
"@kaynooo/cli-kit": "0.
|
|
39
|
+
"@kaynooo/cli-kit": "0.41.0"
|
|
40
40
|
}
|
|
41
41
|
}
|