@kaynooo/cli-dev 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +579 -70
  2. 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 process11 from "process";
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 G = /^[a-f0-9]+$/i;
56
+ var G2 = /^[a-f0-9]+$/i;
36
57
  function b(r) {
37
58
  let e = r.startsWith("#") ? r.slice(1) : r;
38
- if (!G.test(e))
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 B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
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 = B[i];
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,24 +167,20 @@ function printJson(value) {
123
167
 
124
168
  // ../kit/src/help.ts
125
169
  import process5 from "process";
126
- var OPTIONAL = /\[[^\]]+\]/g;
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)) {
130
174
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
131
175
  }
132
- function helpText(usage, options, colors = paint(process5.stdout), { examples = [], replaces, exits = [] } = {}) {
133
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
176
+ function helpText(usage, options, colors = paint(process5.stdout), { examples = [], exits = [] } = {}) {
177
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
134
178
  `);
135
179
  }
136
180
  function exitRows(exits, colors = paint(process5.stdout)) {
137
181
  if (exits.length === 0)
138
182
  return [];
139
- const width = Math.max(...exits.map(([code]) => String(code).length));
140
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
141
- }
142
- function replacesRows(replaces, colors = paint(process5.stdout)) {
143
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
183
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
144
184
  }
145
185
  function wantsHelpJson(env = process5.env) {
146
186
  return env.KIT_HELP === "json";
@@ -166,29 +206,40 @@ function exampleRows(examples, colors = paint(process5.stdout)) {
166
206
  return [];
167
207
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
168
208
  }
209
+ var MAX_INLINE_CHOICES = 24;
169
210
  function optionRows(options, colors = paint(process5.stdout)) {
170
211
  const rows = Object.entries(options).map(([name, option]) => {
171
212
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
172
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
213
+ const choices = option.choices?.join("|");
214
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
215
+ const named = inline ? `<${choices}>` : "<value>";
173
216
  const placeholder = option.optional === undefined ? named : `[${named}]`;
174
217
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
175
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
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 };
176
220
  });
177
221
  const width = Math.max(0, ...rows.map((row) => row.width));
178
222
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
179
223
  }
180
224
 
181
225
  // ../kit/src/text.ts
182
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
183
226
  function distance(a, b) {
184
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
185
- for (const [i, left] of [...a].entries()) {
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()) {
186
232
  const current = [i + 1];
187
- for (const [j, right] of [...b].entries())
188
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
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;
189
240
  previous = current;
190
241
  }
191
- return previous[b.length] ?? 0;
242
+ return previous[right.length] ?? 0;
192
243
  }
193
244
  function closest(name, names) {
194
245
  const started = names.find((known) => known.startsWith(name));
@@ -481,13 +532,31 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
481
532
  // ../kit/src/cli.ts
482
533
  import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
483
534
  import { dirname as dirname2, join as join2 } from "path";
484
- import process9 from "process";
535
+ import process10 from "process";
536
+
537
+ // ../kit/src/notify.ts
538
+ import process8 from "process";
539
+ var NOTIFY_AFTER_MS = 1e4;
540
+ var CANCELLED = 130;
541
+ function base64(text) {
542
+ return Buffer.from(text).toString("base64");
543
+ }
544
+ function notification(title, body, env = process8.env) {
545
+ const id = `kit${process8.pid}`;
546
+ 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\\`];
547
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
548
+ }
549
+ function notifyEnd(command, code, ms, { stream = process8.stderr, env = process8.env } = {}) {
550
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
551
+ return;
552
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
553
+ }
485
554
 
486
555
  // ../kit/src/usage.ts
487
556
  import { appendFileSync, mkdirSync } from "fs";
488
557
  import { homedir } from "os";
489
558
  import { dirname, isAbsolute, join } from "path";
490
- import process8 from "process";
559
+ import process9 from "process";
491
560
 
492
561
  // ../kit/src/logs.ts
493
562
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -501,14 +570,14 @@ var usageError;
501
570
  function noteUsageError(message) {
502
571
  usageError = message;
503
572
  }
504
- function stateHome(env = process8.env) {
573
+ function stateHome(env = process9.env) {
505
574
  const dir = env.XDG_STATE_HOME;
506
575
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
507
576
  }
508
- function usagePath(env = process8.env) {
577
+ function usagePath(env = process9.env) {
509
578
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
510
579
  }
511
- function usageRecorded(env = process8.env) {
580
+ function usageRecorded(env = process9.env) {
512
581
  const off = env.KAYNOOO_CLI_NO_USAGE;
513
582
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
514
583
  }
@@ -522,7 +591,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
522
591
  usageError = undefined;
523
592
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
524
593
  }
525
- function recordUsage(entry, env = process8.env) {
594
+ function recordUsage(entry, env = process9.env) {
526
595
  if (!usageRecorded(env))
527
596
  return;
528
597
  try {
@@ -599,7 +668,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
599
668
  header(colors, summary),
600
669
  "",
601
670
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
602
- ...replacesRows(replaces, colors),
603
671
  "",
604
672
  ...await commandRows(commands, colors),
605
673
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -613,8 +681,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
613
681
  `);
614
682
  }
615
683
  function printError(prefix, message, hint, cause) {
616
- const colors = paint(process9.stderr);
617
- const styled = takesControlCodes(process9.stderr);
684
+ const colors = paint(process10.stderr);
685
+ const styled = takesControlCodes(process10.stderr);
618
686
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
619
687
  const under = (label, text, tint) => text === undefined ? "" : `
620
688
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -657,11 +725,11 @@ async function dispatch(level, typed, { version, redact }) {
657
725
  }
658
726
  }
659
727
  if (name === undefined && level.path.length > 1) {
660
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
728
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stderr));
661
729
  return 2;
662
730
  }
663
731
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
664
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
732
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stdout));
665
733
  return 0;
666
734
  }
667
735
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -778,7 +846,11 @@ async function printCandidates(found) {
778
846
  return 0;
779
847
  }
780
848
  function packageVersion(entry = Bun.main) {
781
- for (let dir = dirname2(realpathSync2(entry));; dir = dirname2(dir)) {
849
+ let resolved = entry;
850
+ try {
851
+ resolved = realpathSync2(entry);
852
+ } catch {}
853
+ for (let dir = dirname2(resolved);; dir = dirname2(dir)) {
782
854
  try {
783
855
  const { version } = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
784
856
  if (typeof version === "string")
@@ -792,10 +864,13 @@ async function runCli(cli, argv = scriptArgs()) {
792
864
  const version = cli.version ?? packageVersion();
793
865
  if (argv[0] === COMPLETE)
794
866
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
867
+ const started = performance.now();
795
868
  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 });
869
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
870
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
796
871
  if (cli.usage !== false) {
797
872
  try {
798
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
873
+ recordUsage(usageEntry(cli.name, command, argv, code));
799
874
  } catch {}
800
875
  }
801
876
  return code;
@@ -816,13 +891,423 @@ function commandPath(scope, argv) {
816
891
  return path.length === 0 ? undefined : path.join(" ");
817
892
  }
818
893
  // ../kit/src/folders.ts
894
+ import { homedir as homedir2 } from "os";
895
+ import { join as join3 } from "path";
896
+ import process11 from "process";
819
897
  var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
898
+ function cacheFolder({ home = homedir2(), env = process11.env } = {}) {
899
+ return env.XDG_CACHE_HOME ?? join3(home, ".cache");
900
+ }
820
901
  // ../kit/src/secrets.ts
821
902
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
822
903
  // ../kit/src/sessions.ts
823
904
  var {Glob } = globalThis.Bun;
824
905
  var SESSION_FILES = new Glob("*.json");
825
906
  var ACCOUNT_DIRS = new Glob("*/sessions");
907
+ // ../kit/src/prompt.ts
908
+ import process14 from "process";
909
+
910
+ // ../kit/src/answers.ts
911
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
912
+ import { dirname as dirname3, join as join4 } from "path";
913
+ var KEPT = 50;
914
+ function answersFile() {
915
+ return join4(cacheFolder(), "kaynooo-cli", "answers.json");
916
+ }
917
+ function stored() {
918
+ try {
919
+ const parsed = JSON.parse(readFileSync3(answersFile(), "utf-8"));
920
+ if (typeof parsed !== "object" || parsed === null)
921
+ return {};
922
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
923
+ } catch {
924
+ return {};
925
+ }
926
+ }
927
+ function earlierAnswers(key) {
928
+ return stored()[key] ?? [];
929
+ }
930
+ function rememberAnswer(key, answer) {
931
+ const all = stored();
932
+ const file = answersFile();
933
+ all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
934
+ try {
935
+ mkdirSync2(dirname3(file), { recursive: true });
936
+ writeFileSync(file, JSON.stringify(all));
937
+ } catch {}
938
+ }
939
+
940
+ // ../kit/src/job.ts
941
+ import process13 from "process";
942
+ function stopJob() {
943
+ process13.kill(0, "SIGTSTP");
944
+ }
945
+
946
+ // ../kit/src/picker/line.ts
947
+ var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
948
+ var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
949
+ var FORWARD_KILLS = new Set(["killnext", "killend"]);
950
+ function isEditKey(key) {
951
+ return EDIT_KEYS.has(key);
952
+ }
953
+ function endsKills(key) {
954
+ return typeof key !== "object" && !isEditKey(key);
955
+ }
956
+ var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
957
+ var SPACE = /\s/;
958
+ function isWord(char) {
959
+ return char !== undefined && WORD_CHARACTER.test(char);
960
+ }
961
+ function wordStart(chars, from) {
962
+ let at = from;
963
+ while (at > 0 && !isWord(chars[at - 1]))
964
+ at--;
965
+ while (at > 0 && isWord(chars[at - 1]))
966
+ at--;
967
+ return at;
968
+ }
969
+ function wordEnd(chars, from) {
970
+ let at = from;
971
+ while (at < chars.length && !isWord(chars[at]))
972
+ at++;
973
+ while (at < chars.length && isWord(chars[at]))
974
+ at++;
975
+ return at;
976
+ }
977
+ function spacedStart(chars, from) {
978
+ let at = from;
979
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
980
+ at--;
981
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
982
+ at--;
983
+ return at;
984
+ }
985
+ function cut(chars, from, to) {
986
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
987
+ }
988
+ function insert(chars, at, text) {
989
+ const typed = [...text];
990
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
991
+ }
992
+ function editLine(line, key) {
993
+ const { killed = "", chained = false } = line;
994
+ const chars = [...line.text];
995
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
996
+ const edited = edit(chars, at, key, killed);
997
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
998
+ return line.killed === undefined ? edited : { ...edited, killed };
999
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
1000
+ if (taken === "")
1001
+ return { ...edited, killed, chained };
1002
+ if (!chained)
1003
+ return { ...edited, killed: taken, chained: true };
1004
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
1005
+ }
1006
+ function edit(chars, at, key, killed) {
1007
+ const text = chars.join("");
1008
+ if (typeof key === "object")
1009
+ return insert(chars, at, key.text);
1010
+ switch (key) {
1011
+ case "left":
1012
+ return { text, caret: Math.max(at - 1, 0) };
1013
+ case "right":
1014
+ return { text, caret: Math.min(at + 1, chars.length) };
1015
+ case "wordleft":
1016
+ return { text, caret: wordStart(chars, at) };
1017
+ case "wordright":
1018
+ return { text, caret: wordEnd(chars, at) };
1019
+ case "linestart":
1020
+ return { text, caret: 0 };
1021
+ case "lineend":
1022
+ return { text, caret: chars.length };
1023
+ case "erase":
1024
+ return cut(chars, Math.max(at - 1, 0), at);
1025
+ case "delete":
1026
+ return cut(chars, at, Math.min(at + 1, chars.length));
1027
+ case "word":
1028
+ return cut(chars, spacedStart(chars, at), at);
1029
+ case "killword":
1030
+ return cut(chars, wordStart(chars, at), at);
1031
+ case "killnext":
1032
+ return cut(chars, at, wordEnd(chars, at));
1033
+ case "clear":
1034
+ return cut(chars, 0, at);
1035
+ case "killend":
1036
+ return cut(chars, at, chars.length);
1037
+ case "yank":
1038
+ return insert(chars, at, killed);
1039
+ }
1040
+ }
1041
+ function visible({ text, caret }, room) {
1042
+ const chars = [...text];
1043
+ const at = Math.min(Math.max(caret, 0), chars.length);
1044
+ const cells = at === chars.length ? [...chars, " "] : chars;
1045
+ const widths = cells.map((char) => Bun.stringWidth(char));
1046
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
1047
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
1048
+ let start = at;
1049
+ let end = at + 1;
1050
+ while (start > 0 && fits(start - 1, end))
1051
+ start--;
1052
+ while (end < cells.length && fits(start, end + 1))
1053
+ end++;
1054
+ const left = start > 0 ? "\u2026" : "";
1055
+ const right = end < cells.length ? "\u2026" : "";
1056
+ 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) };
1057
+ }
1058
+
1059
+ // ../kit/src/picker/score.ts
1060
+ var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1061
+ var NONE = Number.NEGATIVE_INFINITY;
1062
+
1063
+ // ../kit/src/picker/state.ts
1064
+ var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1065
+ var PASTE_START = "\x1B[200~";
1066
+ var PASTE_END = "\x1B[201~";
1067
+ var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1068
+ var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1069
+ var WHEEL_LINES = 3;
1070
+ var KEYS = {
1071
+ "\x1B[A": "up",
1072
+ "\x1BOA": "up",
1073
+ "\x10": "up",
1074
+ "\x1B[B": "down",
1075
+ "\x1BOB": "down",
1076
+ "\x0E": "down",
1077
+ "\x1B[5~": "pageup",
1078
+ "\x1B[6~": "pagedown",
1079
+ "\x1B[H": "home",
1080
+ "\x1B[1~": "home",
1081
+ "\x1BOH": "home",
1082
+ "\x1B[F": "end",
1083
+ "\x1B[4~": "end",
1084
+ "\x1BOF": "end",
1085
+ "\r": "enter",
1086
+ "\n": "enter",
1087
+ "\x03": "cancel",
1088
+ "\x1B": "cancel",
1089
+ "\x1B[D": "left",
1090
+ "\x1BOD": "left",
1091
+ "\x1B[C": "right",
1092
+ "\x1BOC": "right",
1093
+ "\x1B[1;5D": "wordleft",
1094
+ "\x1B[1;3D": "wordleft",
1095
+ "\x1Bb": "wordleft",
1096
+ "\x1B[1;5C": "wordright",
1097
+ "\x1B[1;3C": "wordright",
1098
+ "\x1Bf": "wordright",
1099
+ "\x01": "linestart",
1100
+ "\x05": "lineend",
1101
+ "\x7F": "erase",
1102
+ "\x1B[3~": "delete",
1103
+ "\b": "killword",
1104
+ "\x1B\x7F": "killword",
1105
+ "\x1B[3;5~": "killnext",
1106
+ "\x1Bd": "killnext",
1107
+ "\x15": "clear",
1108
+ "\v": "killend",
1109
+ "\x17": "word",
1110
+ "\x19": "yank",
1111
+ "\x1A": "suspend",
1112
+ "\t": "tab",
1113
+ "\x1F": "help",
1114
+ "\x1BOP": "help",
1115
+ "\x1B[11~": "help"
1116
+ };
1117
+ function repeat(value, count) {
1118
+ return Array.from({ length: count }).fill(value);
1119
+ }
1120
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
1121
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1122
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1123
+ const wheel = MOUSE.exec(sequence)?.[1];
1124
+ if (wheel !== undefined)
1125
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1126
+ const named = codes.get(sequence);
1127
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1128
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1129
+ paste.active = sequence === PASTE_START;
1130
+ return [];
1131
+ }
1132
+ if (paste.active && (sequence === "\r" || sequence === `
1133
+ `))
1134
+ return [];
1135
+ if (key !== undefined)
1136
+ return [key];
1137
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1138
+ });
1139
+ }
1140
+
1141
+ // ../kit/src/redraw.ts
1142
+ var SYNC_START = "\x1B[?2026h";
1143
+ var SYNC_END = "\x1B[?2026l";
1144
+ function overwrite(lines, columns) {
1145
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1146
+ `);
1147
+ }
1148
+ function rowsTaken(lines, columns) {
1149
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1150
+ }
1151
+
1152
+ // ../kit/src/prompt.ts
1153
+ var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
1154
+ var MAX_LISTED = 12;
1155
+ function readKeys(input, paste = { active: false }) {
1156
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
1157
+ }
1158
+ function roomAfter(question, columns) {
1159
+ return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
1160
+ }
1161
+ function withCaret(colors, line, room, dim = false) {
1162
+ const { before, at, after } = visible(line, room);
1163
+ const tone = dim ? colors.dim : (text) => text;
1164
+ return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
1165
+ }
1166
+ function sharedStart(texts) {
1167
+ const [first = [], ...rest] = texts.map((text) => [...text]);
1168
+ let length = first.length;
1169
+ for (const chars of rest) {
1170
+ const differs = chars.findIndex((char, index) => char !== first[index]);
1171
+ length = Math.min(length, differs === -1 ? chars.length : differs);
1172
+ }
1173
+ return first.slice(0, length).join("");
1174
+ }
1175
+ function listed2(colors, found, columns) {
1176
+ const shared = sharedStart(found);
1177
+ const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
1178
+ const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
1179
+ const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
1180
+ return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
1181
+ }
1182
+ async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
1183
+ let line = { text: "", caret: 0 };
1184
+ let invalid;
1185
+ let completions = [];
1186
+ const remembered = history === undefined || mask ? undefined : history;
1187
+ const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
1188
+ let recalled = -1;
1189
+ let draft = line;
1190
+ const taken = () => line.text === "" ? fallback ?? "" : line.text;
1191
+ const shown = () => mask ? "*".repeat([...taken()].length) : taken();
1192
+ const accepted = await ask(question, settings, (colors, state, { columns }) => {
1193
+ if (state !== "asking")
1194
+ return [answer(colors, question, state, shown())];
1195
+ const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
1196
+ return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
1197
+ }, (key) => {
1198
+ if (key === "cancel")
1199
+ return "cancel";
1200
+ invalid = undefined;
1201
+ completions = [];
1202
+ if (line.chained === true && endsKills(key))
1203
+ line = { ...line, chained: false };
1204
+ if (key === "tab") {
1205
+ const chars = [...line.text];
1206
+ const before = chars.slice(0, line.caret).join("");
1207
+ const found = complete?.(before) ?? [];
1208
+ const filled = sharedStart(found);
1209
+ if ([...filled].length > [...before].length)
1210
+ line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
1211
+ else
1212
+ completions = found;
1213
+ return;
1214
+ }
1215
+ if (key === "enter") {
1216
+ invalid = validate?.(taken());
1217
+ return invalid === undefined ? "enter" : undefined;
1218
+ }
1219
+ if (key === "up" || key === "down") {
1220
+ const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
1221
+ if (recalled === -1)
1222
+ draft = line;
1223
+ recalled = to;
1224
+ const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
1225
+ line = { ...shown, killed: line.killed ?? "" };
1226
+ return;
1227
+ }
1228
+ const edit = { home: "linestart", end: "lineend" }[key] ?? key;
1229
+ if (typeof edit === "object" || isEditKey(edit))
1230
+ line = editLine(line, edit);
1231
+ return;
1232
+ });
1233
+ if (!accepted)
1234
+ return;
1235
+ if (remembered !== undefined && taken() !== "")
1236
+ rememberAnswer(remembered, taken());
1237
+ return taken();
1238
+ }
1239
+ function answer(colors, question, state, picked) {
1240
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1241
+ }
1242
+ async function ask(question, { hint, terminal = process14 }, render, press) {
1243
+ const { stdin, stderr } = terminal;
1244
+ if (!isInteractive(terminal))
1245
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
1246
+ const colors = paint(stderr);
1247
+ let current = "asking";
1248
+ let outcome;
1249
+ const columns = () => stderr.columns || 80;
1250
+ const draw = (state, last = false) => {
1251
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1252
+ const rows = rowsTaken(frame, columns());
1253
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
1254
+ current = state;
1255
+ };
1256
+ const redraw = () => draw(current);
1257
+ const paste = { active: false };
1258
+ const stop = terminal.stop ?? (terminal === process14 ? stopJob : undefined);
1259
+ const suspend = () => {
1260
+ if (stop === undefined)
1261
+ return;
1262
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
1263
+ stdin.setRawMode(false);
1264
+ stop();
1265
+ stdin.setRawMode(true);
1266
+ stderr.write("\x1B[?25l\x1B[?2004h");
1267
+ };
1268
+ try {
1269
+ stderr.on?.("resize", redraw);
1270
+ stdin.setRawMode(true);
1271
+ stdin.resume();
1272
+ stderr.write("\x1B[?25l\x1B[?2004h");
1273
+ draw("asking");
1274
+ return await new Promise((resolve) => {
1275
+ function onData(data) {
1276
+ for (const key of readKeys(data.toString(), paste)) {
1277
+ if (key === "suspend") {
1278
+ suspend();
1279
+ continue;
1280
+ }
1281
+ const pressed = press(key);
1282
+ if (pressed !== undefined) {
1283
+ settle(pressed);
1284
+ return;
1285
+ }
1286
+ }
1287
+ draw("asking");
1288
+ }
1289
+ function onEnd() {
1290
+ settle("cancel");
1291
+ }
1292
+ function settle(settled) {
1293
+ outcome = settled;
1294
+ stdin.off("data", onData);
1295
+ stdin.off("end", onEnd);
1296
+ resolve(settled === "enter");
1297
+ }
1298
+ stdin.on("data", onData);
1299
+ stdin.on("end", onEnd);
1300
+ });
1301
+ } finally {
1302
+ stderr.off?.("resize", redraw);
1303
+ draw(outcome ?? "cancel", true);
1304
+ stderr.write(`
1305
+ \x1B[?25h\x1B[?2004l`);
1306
+ stdin.setRawMode(false);
1307
+ stdin.pause();
1308
+ }
1309
+ }
1310
+
826
1311
  // src/encode.ts
827
1312
  function b64Encode(bytes, url = false) {
828
1313
  return Buffer.from(bytes).toString(url ? "base64url" : "base64");
@@ -842,6 +1327,15 @@ var ALGORITHMS = ["sha256", "sha1", "md5", "sha512"];
842
1327
  function hashHex(algorithm, bytes) {
843
1328
  return new Bun.CryptoHasher(algorithm).update(bytes).digest("hex");
844
1329
  }
1330
+ async function hashStream(algorithm, stream) {
1331
+ const hasher = new Bun.CryptoHasher(algorithm);
1332
+ let bytes = 0;
1333
+ for await (const chunk of stream) {
1334
+ hasher.update(chunk);
1335
+ bytes += chunk.length;
1336
+ }
1337
+ return { digest: hasher.digest("hex"), bytes };
1338
+ }
845
1339
 
846
1340
  // src/ids.ts
847
1341
  var CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
@@ -882,7 +1376,7 @@ async function publicIp(family, service = IP_SERVICE) {
882
1376
  }
883
1377
 
884
1378
  // src/time.ts
885
- var UNITS = [["d", 86400000], ["h", 3600000], ["m", 60000], ["s", 1000]];
1379
+ var UNITS2 = [["d", 86400000], ["h", 3600000], ["m", 60000], ["s", 1000]];
886
1380
  var DURATION_UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
887
1381
  function parts(ms, timeZone) {
888
1382
  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" });
@@ -903,7 +1397,7 @@ function offsetAt(ms, timeZone) {
903
1397
  function humanDuration(ms) {
904
1398
  let rest = Math.floor(Math.abs(ms) / 1000) * 1000;
905
1399
  const out = [];
906
- for (const [name, size] of UNITS) {
1400
+ for (const [name, size] of UNITS2) {
907
1401
  const count = Math.floor(rest / size);
908
1402
  if (count > 0) {
909
1403
  out.push(`${count}${name}`);
@@ -1045,6 +1539,8 @@ function urlParts(text) {
1045
1539
 
1046
1540
  // src/cli.ts
1047
1541
  var MAX_PASSWORD_BYTES = 65536;
1542
+ var TRAILING_NEWLINE = /\r?\n$/;
1543
+ var STDIN_OR_VALUE = /^(?!-.)/;
1048
1544
  var ZONE_OPTION = { type: "string", description: "the IANA zone of the local dates, such as Europe/Paris (default: this host's)" };
1049
1545
  function reading(read) {
1050
1546
  try {
@@ -1068,6 +1564,11 @@ async function textInput(argument, what) {
1068
1564
  return argument;
1069
1565
  return !isStdinPiped() ? fail(`give ${what} as an argument or pipe it on stdin`, 2) : Bun.stdin.text();
1070
1566
  }
1567
+ async function secretInput(what) {
1568
+ if (isInteractive())
1569
+ return await input2(what, { mask: true }) ?? fail("cancelled", 130);
1570
+ return (await textInput(undefined, what)).replace(TRAILING_NEWLINE, "");
1571
+ }
1071
1572
  async function bytesInput(argument, what) {
1072
1573
  if (argument !== undefined)
1073
1574
  return new TextEncoder().encode(argument);
@@ -1076,33 +1577,35 @@ async function bytesInput(argument, what) {
1076
1577
  return new Uint8Array(await Bun.stdin.arrayBuffer());
1077
1578
  }
1078
1579
  function printRows(rows) {
1079
- const { cyan } = paint(process11.stdout);
1580
+ const { cyan } = paint(process15.stdout);
1080
1581
  const width = Math.max(...rows.map(([label]) => label.length));
1081
1582
  for (const [label, value] of rows)
1082
1583
  console.log(`${cyan(label.padEnd(width))} ${value}`);
1083
1584
  }
1084
1585
  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
1085
1586
 
1086
- 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.
1087
- Exits 0 when it printed the password or hash, 2 on a usage error.`;
1587
+ 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.`;
1588
+ var PASSWORD_EXITS = [[0, "it printed the password or hash"], [2, "a usage error"], [130, "the prompt was cancelled"]];
1088
1589
  var PASSWORD_OPTIONS = {
1089
- bcrypt: { type: "string", short: "b", optional: { bare: "" }, description: "print the bcrypt hash of the password given, or of a generated one" },
1590
+ 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" },
1090
1591
  "no-copy": { type: "boolean", description: "leave the clipboard alone" },
1091
1592
  json: jsonOption("{password?, hash?, format, bytes, copied}")
1092
1593
  };
1093
1594
  var FORMAT_NOTES = { hex: "hexadecimal", base64: "base64", base64url: "url-safe base64" };
1094
1595
  async function password(args) {
1095
1596
  const { values, positionals } = parse(args, PASSWORD_USAGE, PASSWORD_OPTIONS, {
1597
+ exits: PASSWORD_EXITS,
1096
1598
  positionals: ["[length]", "[format]"],
1097
1599
  candidates: { "[length]": () => ["16", "24", "32", "48", "64"], "[format]": () => FORMATS.map((format) => [format, FORMAT_NOTES[format]]) },
1098
1600
  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 hunter2", "the hash to paste into a basic auth file"]]
1601
+ 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
1602
  });
1101
1603
  const bytes = wholeNumber(positionals[0], "<length>", DEFAULT_LENGTH);
1102
1604
  const format = oneOf(positionals[1] ?? "base64", "<format>", FORMATS);
1103
1605
  if (bytes > MAX_PASSWORD_BYTES)
1104
1606
  badUsage(`<length> takes at most ${MAX_PASSWORD_BYTES}, not ${bytes}`);
1105
- const given = values.bcrypt === undefined || values.bcrypt === "" ? undefined : values.bcrypt;
1607
+ const bcrypt = values.bcrypt === "" ? undefined : values.bcrypt;
1608
+ const given = bcrypt === "-" ? await secretInput("the password") : bcrypt;
1106
1609
  const secret = given ?? generatePassword(bytes, format);
1107
1610
  const hash = values.bcrypt === undefined ? undefined : await bcryptHash(secret);
1108
1611
  const copied = values["no-copy"] === true ? false : await copyText(given === undefined ? secret : hash ?? secret);
@@ -1111,7 +1614,7 @@ async function password(args) {
1111
1614
  return 0;
1112
1615
  }
1113
1616
  if (copied)
1114
- console.error(paint(process11.stderr).dim("copied to clipboard"));
1617
+ console.error(paint(process15.stderr).dim("copied to clipboard"));
1115
1618
  if (hash !== undefined && given === undefined)
1116
1619
  console.error(secret);
1117
1620
  console.log(hash ?? secret);
@@ -1119,27 +1622,28 @@ async function password(args) {
1119
1622
  }
1120
1623
  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
1624
 
1122
- The token is the argument or what is piped on stdin, a leading "Bearer " is ignored. The signature is not verified.
1123
- Exits 0 when it decoded the token, 1 when it is not a JWT, 2 on a usage error.`;
1625
+ 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.`;
1626
+ var JWT_EXITS = [[0, "it decoded the token"], [1, "it is not a JWT"], [2, "a usage error"], [130, "the prompt was cancelled"]];
1124
1627
  var JWT_OPTIONS = {
1125
1628
  zone: ZONE_OPTION,
1126
1629
  json: jsonOption("{header, payload, claims: [{claim, epoch, local, utc, relative}], signatureBytes}")
1127
1630
  };
1128
1631
  async function jwt(args) {
1129
1632
  const { values, positionals } = parse(args, JWT_USAGE, JWT_OPTIONS, {
1633
+ exits: JWT_EXITS,
1130
1634
  positionals: ["[token]"],
1131
1635
  replaces: "pasting a token into jwt.io or decoding its segments with base64 and jq",
1132
1636
  examples: ["dev jwt eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDAwMDAwMDB9.c2ln", ["pbpaste | dev jwt --json", "for a script"]]
1133
1637
  });
1134
1638
  const zone = zoneOf(values.zone);
1135
- const token = await textInput(positionals[0], "the token");
1639
+ const token = positionals[0] ?? await secretInput("the token");
1136
1640
  const decoded = reading(() => decodeJwt(token));
1137
1641
  const claims = claimTimes(decoded.payload, Date.now(), zone);
1138
1642
  if (values.json === true) {
1139
1643
  printJson({ header: decoded.header, payload: decoded.payload, claims, signatureBytes: decoded.signatureBytes });
1140
1644
  return 0;
1141
1645
  }
1142
- const { bold } = paint(process11.stdout);
1646
+ const { bold } = paint(process15.stdout);
1143
1647
  console.log(`${bold("header")}
1144
1648
  ${JSON.stringify(decoded.header, null, 2)}
1145
1649
 
@@ -1153,14 +1657,15 @@ ${JSON.stringify(decoded.payload, null, 2)}`);
1153
1657
  }
1154
1658
  var TS_USAGE = `dev ts [value]: a time as local and UTC dates, whatever it is written as
1155
1659
 
1156
- The value is epoch seconds or milliseconds (told apart by size: from 1e11 up it is milliseconds), an ISO date or date-time (read in the local zone when it gives none), or a duration such as 90m or 2h30m, shown with the date that far from now. Without a value it is now; "-" reads the value on stdin.
1157
- Exits 0 when it converted the value, 1 when it is none of those, 2 on a usage error.`;
1660
+ The value is epoch seconds or milliseconds (told apart by size: from 1e11 up it is milliseconds), an ISO date or date-time (read in the local zone when it gives none), or a duration such as 90m or 2h30m, shown with the date that far from now. Without a value it is now; "-" reads the value on stdin.`;
1661
+ var TS_EXITS = [[0, "it converted the value"], [1, "it is none of those"], [2, "a usage error"]];
1158
1662
  var TS_OPTIONS = {
1159
1663
  zone: ZONE_OPTION,
1160
1664
  json: jsonOption("{kind, ms, seconds, local, utc, relative} or, for a duration, {kind, ms, seconds, human, fromNow}")
1161
1665
  };
1162
1666
  async function ts(args) {
1163
1667
  const { values, positionals } = parse(args, TS_USAGE, TS_OPTIONS, {
1668
+ exits: TS_EXITS,
1164
1669
  positionals: ["[value]"],
1165
1670
  replaces: "date -d @<seconds> and date -u, and doing the milliseconds division by hand",
1166
1671
  examples: ["dev ts 1700000000", ["dev ts 2h30m", "the date 2h30m from now"], ["dev ts 2024-05-06T08:09:10Z --zone Europe/Paris", "that instant in Paris"]]
@@ -1179,12 +1684,12 @@ async function ts(args) {
1179
1684
  printRows([["local", converted.local], ["utc", converted.utc], ["seconds", String(converted.seconds)], ["ms", String(converted.ms)], ["relative", converted.relative]]);
1180
1685
  return 0;
1181
1686
  }
1182
- var UUID_USAGE = `dev uuid [-n <count>] [--v7]: random UUIDs, version 4 or, with --v7, version 7 (time-ordered)
1183
-
1184
- Exits 0 when it printed them, 2 on a usage error.`;
1687
+ var UUID_USAGE = `dev uuid [-n <count>] [--v7]: random UUIDs, version 4 or, with --v7, version 7 (time-ordered)`;
1688
+ var UUID_EXITS = [[0, "it printed them"], [2, "a usage error"]];
1185
1689
  var COUNT_OPTION = { type: "string", short: "n", description: "how many to print (default 1)" };
1186
1690
  function uuid(args) {
1187
1691
  const { values } = parse(args, UUID_USAGE, { n: COUNT_OPTION, v7: { type: "boolean", description: "a version 7 UUID, which sorts by creation time" }, json: jsonOption('["uuid"]') }, {
1692
+ exits: UUID_EXITS,
1188
1693
  positionals: [],
1189
1694
  replaces: 'uuidgen and python -c "import uuid"',
1190
1695
  examples: ["dev uuid", ["dev uuid -n 5 --v7", "five time-ordered UUIDs"]]
@@ -1193,11 +1698,11 @@ function uuid(args) {
1193
1698
  printIds(ids, values.json === true);
1194
1699
  return 0;
1195
1700
  }
1196
- var ULID_USAGE = `dev ulid [-n <count>]: random ULIDs, 26 sortable characters of time and randomness
1197
-
1198
- Exits 0 when it printed them, 2 on a usage error.`;
1701
+ var ULID_USAGE = `dev ulid [-n <count>]: random ULIDs, 26 sortable characters of time and randomness`;
1702
+ var ULID_EXITS = [[0, "it printed them"], [2, "a usage error"]];
1199
1703
  function ulidCommand(args) {
1200
1704
  const { values } = parse(args, ULID_USAGE, { n: COUNT_OPTION, json: jsonOption('["ulid"]') }, {
1705
+ exits: ULID_EXITS,
1201
1706
  positionals: [],
1202
1707
  replaces: "installing a ulid package to mint one",
1203
1708
  examples: ["dev ulid", ["dev ulid -n 3", "three ULIDs"]]
@@ -1214,8 +1719,8 @@ function printIds(ids, json) {
1214
1719
  }
1215
1720
  var B64_USAGE = `dev b64 [-d] [--url] [text]: base64 of the text, or with -d the text behind a base64 one
1216
1721
 
1217
- The text is the argument or what is piped on stdin, taken as is (a piped trailing newline is encoded, as base64 does). With --url the output is URL-safe and unpadded. Decoding takes either alphabet, padded or not, and writes the raw bytes.
1218
- Exits 0 when it printed the result, 1 when -d is given text that is not base64, 2 on a usage error.`;
1722
+ The text is the argument or what is piped on stdin, taken as is (a piped trailing newline is encoded, as base64 does). With --url the output is URL-safe and unpadded. Decoding takes either alphabet, padded or not, and writes the raw bytes.`;
1723
+ var B64_EXITS = [[0, "it printed the result"], [1, "-d is given text that is not base64"], [2, "a usage error"]];
1219
1724
  var B64_OPTIONS = {
1220
1725
  decode: { type: "boolean", short: "d", description: "decode instead of encode" },
1221
1726
  url: { type: "boolean", description: "URL-safe alphabet without padding, when encoding" },
@@ -1223,6 +1728,7 @@ var B64_OPTIONS = {
1223
1728
  };
1224
1729
  async function b64(args) {
1225
1730
  const { values, positionals } = parse(args, B64_USAGE, B64_OPTIONS, {
1731
+ exits: B64_EXITS,
1226
1732
  positionals: ["[text]"],
1227
1733
  replaces: "base64 and base64 -d, which leave the URL-safe alphabet to tr",
1228
1734
  examples: ["dev b64 hello", ["echo aGVsbG8 | dev b64 -d", "decoded, padding optional"]]
@@ -1245,10 +1751,11 @@ async function b64(args) {
1245
1751
  }
1246
1752
  var URL_USAGE = `dev url [url]: the parts of a URL and its query decoded, one per line
1247
1753
 
1248
- The URL is the argument or what is piped on stdin, and has to include its scheme.
1249
- Exits 0 when it printed the parts, 1 when the text is not a URL, 2 on a usage error.`;
1754
+ The URL is the argument or what is piped on stdin, and has to include its scheme.`;
1755
+ var URL_EXITS = [[0, "it printed the parts"], [1, "the text is not a URL"], [2, "a usage error"]];
1250
1756
  async function url(args) {
1251
1757
  const { values, positionals } = parse(args, URL_USAGE, { json: jsonOption("{href, protocol, username, password, host, hostname, port, pathname, query: [{key, value}], hash}") }, {
1758
+ exits: URL_EXITS,
1252
1759
  positionals: ["[url]"],
1253
1760
  replaces: "reading a long query string by eye or decoding it with python urllib",
1254
1761
  examples: ['dev url "https://example.com:8443/a%20b?q=x%26y&page=2#top"', ['dev url "https://example.com/?a=1" --json', "for a script"]]
@@ -1264,11 +1771,11 @@ async function url(args) {
1264
1771
  printRows([...shown, ...query.map(({ key, value }) => [`?${key}`, value])]);
1265
1772
  return 0;
1266
1773
  }
1267
- var HASH_USAGE = `dev hash <sha256|sha1|md5|sha512> [file]: the hex digest of a file, or of what is piped on stdin
1268
-
1269
- Exits 0 when it printed the digest, 1 when the file does not exist, 2 on a usage error.`;
1774
+ var HASH_USAGE = `dev hash <sha256|sha1|md5|sha512> [file]: the hex digest of a file, or of what is piped on stdin`;
1775
+ var HASH_EXITS = [[0, "it printed the digest"], [1, "the file does not exist"], [2, "a usage error"]];
1270
1776
  async function hash(args) {
1271
1777
  const { values, positionals } = parse(args, HASH_USAGE, { json: jsonOption("{algorithm, hash, bytes}") }, {
1778
+ exits: HASH_EXITS,
1272
1779
  positionals: ["<algorithm>", "[file]"],
1273
1780
  candidates: { "<algorithm>": () => [...ALGORITHMS] },
1274
1781
  replaces: "sha256sum, sha1sum and md5sum, which print the file name beside the digest",
@@ -1276,28 +1783,30 @@ async function hash(args) {
1276
1783
  });
1277
1784
  const algorithm = oneOf(positionals[0] ?? "", "<algorithm>", ALGORITHMS);
1278
1785
  const file = positionals[1];
1279
- let bytes;
1786
+ let result;
1280
1787
  if (file === undefined) {
1281
- bytes = await bytesInput(undefined, "a file");
1788
+ const input = await bytesInput(undefined, "a file");
1789
+ result = { digest: hashHex(algorithm, input), bytes: input.length };
1282
1790
  } else {
1283
1791
  const source = Bun.file(file);
1284
1792
  if (!await source.exists())
1285
1793
  return fail(`no file ${file}`, 1);
1286
- bytes = new Uint8Array(await source.arrayBuffer());
1794
+ result = await hashStream(algorithm, source.stream());
1287
1795
  }
1288
- const digest = hashHex(algorithm, bytes);
1796
+ const digest = result.digest;
1289
1797
  if (values.json === true)
1290
- printJson({ algorithm, hash: digest, bytes: bytes.length });
1798
+ printJson({ algorithm, hash: digest, bytes: result.bytes });
1291
1799
  else
1292
1800
  console.log(digest);
1293
1801
  return 0;
1294
1802
  }
1295
1803
  var IP_USAGE = `dev ip [-4|-6]: the public IP address of this host, as a web service sees it
1296
1804
 
1297
- -4 or -6 asks over that IP family only, which fails when the host has no route over it.
1298
- Exits 0 when it printed the address, 1 when the service could not be reached, 2 on a usage error.`;
1805
+ -4 or -6 asks over that IP family only, which fails when the host has no route over it.`;
1806
+ var IP_EXITS = [[0, "it printed the address"], [1, "the service could not be reached"], [2, "a usage error"]];
1299
1807
  async function ip(args) {
1300
1808
  const { values } = parse(args, IP_USAGE, { 4: { type: "boolean", short: "4", description: "over IPv4 only" }, 6: { type: "boolean", short: "6", description: "over IPv6 only" }, json: jsonOption("{ip, family?}") }, {
1809
+ exits: IP_EXITS,
1301
1810
  replaces: "curl https://ipecho.net/plain typed from memory",
1302
1811
  examples: ["dev ip", ["dev ip -6", "the IPv6 address"]]
1303
1812
  });
@@ -1320,7 +1829,7 @@ async function ip(args) {
1320
1829
  }
1321
1830
  }
1322
1831
  if (import.meta.main) {
1323
- process11.exitCode = await runCli({
1832
+ process15.exitCode = await runCli({
1324
1833
  name: "dev",
1325
1834
  about: "small developer utilities: passwords and bcrypt hashes, JWTs, timestamps, UUIDs, base64, URLs and file hashes",
1326
1835
  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.5.0",
4
+ "version": "0.6.0",
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.38.1"
39
+ "@kaynooo/cli-kit": "0.40.0"
40
40
  }
41
41
  }