@kaynooo/cli-dev 0.6.0 → 0.7.2

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 (3) hide show
  1. package/README.md +3 -3
  2. package/dist/cli.js +1206 -838
  3. package/package.json +5 -5
package/dist/cli.js CHANGED
@@ -1,20 +1,19 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
3
+ var __esm = (fn, res, err) => () => {
4
+ if (fn)
5
+ try {
6
+ res = fn(fn = 0);
7
+ } catch (e) {
8
+ err = [e];
9
+ }
10
+ if (err)
11
+ throw err[0];
12
+ return res;
13
+ };
3
14
 
4
- // src/cli.ts
5
- import process15 from "process";
6
- // ../kit/src/args.ts
7
- import process6 from "process";
8
- import { parseArgs } from "util";
9
-
10
- // ../kit/src/format.ts
11
- import process4 from "process";
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 = "...") {
15
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
16
+ function Ao(t, e, r = "...") {
18
17
  let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
19
18
  if (t.length <= e)
20
19
  return t;
@@ -25,13 +24,22 @@ function ko(t, e, r = "...") {
25
24
  c = c.trimEnd();
26
25
  return s ? (c + n).slice(0, l) : c + n;
27
26
  }
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;
27
+ var N, Nt, Y, be, W;
28
+ var init_chunk_rkhsft4a = __esm(() => {
29
+ N = new Map;
30
+ Nt = /\s+\S*$/;
31
+ Y = /\s/;
32
+ be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
33
+ W = new Map;
34
+ });
35
+
36
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
37
+ var init_text = __esm(() => {
38
+ init_chunk_rkhsft4a();
39
+ });
30
40
 
31
41
  // ../kit/src/mode.ts
32
42
  import process2 from "process";
33
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
34
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
35
43
  function isSet(value) {
36
44
  return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
37
45
  }
@@ -48,12 +56,13 @@ function outputMode(stream = process2.stdout, env = process2.env) {
48
56
  function isInteractive(streams = process2) {
49
57
  return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
50
58
  }
59
+ var MODES, AGENT_VARIABLES;
60
+ var init_mode = __esm(() => {
61
+ MODES = new Set(["terminal", "ci", "agent", "pipe"]);
62
+ AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
63
+ });
51
64
 
52
- // ../kit/src/style.ts
53
- import process3 from "process";
54
-
55
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
56
- var G2 = /^[a-f0-9]+$/i;
65
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
57
66
  function b(r) {
58
67
  let e = r.startsWith("#") ? r.slice(1) : r;
59
68
  if (!G2.test(e))
@@ -64,11 +73,6 @@ function b(r) {
64
73
  throw Error(`Invalid hex color length: ${e.length}`);
65
74
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
66
75
  }
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") => {
68
- let [l, n, c] = b(r);
69
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
70
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
71
- var h = new Set(["", "1", "2", "3", "true"]);
72
76
  function C(r, e = globalThis.process?.env ?? {}) {
73
77
  if (e.FORCE_COLOR !== undefined)
74
78
  return h.has(e.FORCE_COLOR);
@@ -82,7 +86,7 @@ function f(r, e = []) {
82
86
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
83
87
  let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
84
88
  return new Proxy(c, { get(t, i) {
85
- let a = B2[i];
89
+ let a = B[i];
86
90
  if (Array.isArray(a)) {
87
91
  let s = g.get(i);
88
92
  if (s === undefined)
@@ -105,32 +109,70 @@ function f(r, e = []) {
105
109
  function Fe(r = {}) {
106
110
  return f(r);
107
111
  }
108
- var o = Fe();
112
+ var G2, B, h, o;
113
+ var init_chunk_x450vn3m = __esm(() => {
114
+ G2 = /^[a-f0-9]+$/i;
115
+ B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
116
+ let [l, n, c] = b(r);
117
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
118
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
119
+ h = new Set(["", "1", "2", "3", "true"]);
120
+ o = Fe();
121
+ });
122
+
123
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
124
+ var init_colors = __esm(() => {
125
+ init_chunk_x450vn3m();
126
+ });
127
+
128
+ // ../kit/src/config.ts
129
+ var init_config = __esm(() => {
130
+ init_args();
131
+ });
132
+
133
+ // ../kit/src/user-config.ts
134
+ import { isAbsolute, join } from "path";
135
+ function xdgFolder(value, fallback) {
136
+ return value !== undefined && isAbsolute(value) ? value : fallback;
137
+ }
138
+ var init_user_config = () => {};
109
139
 
110
140
  // ../kit/src/theme.ts
111
- var ENDS = new Map;
112
- var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
113
- var MAX_FILE_BYTES = 64 * 1024;
114
- var warned = new Set;
141
+ var ENDS, STYLES, MAX_FILE_BYTES, warned;
142
+ var init_theme = __esm(() => {
143
+ init_config();
144
+ init_user_config();
145
+ ENDS = new Map;
146
+ STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
147
+ MAX_FILE_BYTES = 64 * 1024;
148
+ warned = new Set;
149
+ });
115
150
 
116
151
  // ../kit/src/style.ts
152
+ import process3 from "process";
117
153
  function takesControlCodes(stream, env = process3.env) {
118
154
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
119
155
  }
120
156
  function paint(stream, env = process3.env) {
121
157
  return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
122
158
  }
123
- var STATUS_WORDS = {
124
- passed: ["passed", "success", "succeeded", "ok"],
125
- failed: ["failed", "failure", "error", "errored"],
126
- running: ["running", "in_progress", "started", "holding"],
127
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
128
- skipped: ["skipped", "cancelled", "canceled", "manual"]
129
- };
130
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
159
+ var STATUS_WORDS, STATUS_OF;
160
+ var init_style = __esm(() => {
161
+ init_colors();
162
+ init_mode();
163
+ init_theme();
164
+ STATUS_WORDS = {
165
+ passed: ["passed", "success", "succeeded", "ok"],
166
+ failed: ["failed", "failure", "error", "errored"],
167
+ running: ["running", "in_progress", "started", "holding"],
168
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
169
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
170
+ };
171
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
172
+ });
131
173
 
132
174
  // ../kit/src/format.ts
133
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
175
+ import process4 from "process";
134
176
  function formatSeconds(total) {
135
177
  let rest = Math.max(0, Math.round(total));
136
178
  const amounts = UNITS.map(([unit, size]) => {
@@ -152,9 +194,8 @@ function upTo(text, separator) {
152
194
  return end === -1 ? text : text.slice(0, end);
153
195
  }
154
196
  function truncate(text, width) {
155
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
197
+ return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
156
198
  }
157
- var ESCAPE = String.fromCharCode(27);
158
199
  function textWidth(text) {
159
200
  return Bun.stringWidth(text);
160
201
  }
@@ -164,14 +205,39 @@ function jsonText(value, replacer, { stream = process4.stdout, env = process4.en
164
205
  function printJson(value) {
165
206
  console.log(jsonText(value));
166
207
  }
208
+ var UNITS, ESCAPE;
209
+ var init_format = __esm(() => {
210
+ init_text();
211
+ init_mode();
212
+ init_style();
213
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
214
+ ESCAPE = String.fromCharCode(27);
215
+ });
167
216
 
168
217
  // ../kit/src/help.ts
169
218
  import process5 from "process";
170
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
171
- var USAGE_PREFIX = /^usage:\s*/i;
172
- var FULL_STOP = /\.$/;
173
219
  function usageLine(usage, colors = paint(process5.stdout)) {
174
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
220
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
221
+ `);
222
+ const blank = lines.indexOf("");
223
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
224
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
225
+ const colon = synopses[0].indexOf(": ");
226
+ const inline = synopses[0].slice(colon + 2);
227
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
228
+ if (colon !== -1)
229
+ synopses[0] = synopses[0].slice(0, colon);
230
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
231
+ `)}`;
232
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
233
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
234
+ return [head, ...lead, ...rest].join(`
235
+ `);
236
+ }
237
+ function prose(line, colors) {
238
+ if (colors.cyan("x") === "x")
239
+ return line;
240
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
175
241
  }
176
242
  function helpText(usage, options, colors = paint(process5.stdout), { examples = [], exits = [] } = {}) {
177
243
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -206,7 +272,6 @@ function exampleRows(examples, colors = paint(process5.stdout)) {
206
272
  return [];
207
273
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
208
274
  }
209
- var MAX_INLINE_CHOICES = 24;
210
275
  function optionRows(options, colors = paint(process5.stdout)) {
211
276
  const rows = Object.entries(options).map(([name, option]) => {
212
277
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -221,6 +286,15 @@ function optionRows(options, colors = paint(process5.stdout)) {
221
286
  const width = Math.max(0, ...rows.map((row) => row.width));
222
287
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
223
288
  }
289
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
290
+ var init_help = __esm(() => {
291
+ init_mode();
292
+ init_style();
293
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
294
+ USAGE_PREFIX = /^usage:\s*/i;
295
+ FULL_STOP = /\.$/;
296
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
297
+ });
224
298
 
225
299
  // ../kit/src/text.ts
226
300
  function distance(a, b) {
@@ -248,9 +322,10 @@ function closest(name, names) {
248
322
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
249
323
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
250
324
  }
325
+ var init_text2 = () => {};
326
+
251
327
  // ../kit/src/input.ts
252
328
  import { fstatSync } from "fs";
253
- var WHOLE = /^\d+$/;
254
329
  function wholeNumber(value, name, fallback, min = 1) {
255
330
  if (value === undefined)
256
331
  return fallback;
@@ -263,40 +338,28 @@ function isStdinPiped() {
263
338
  const stat = fstatSync(0);
264
339
  return stat.isFIFO() || stat.isFile();
265
340
  }
341
+ var WHOLE;
342
+ var init_input = __esm(() => {
343
+ init_args();
344
+ WHOLE = /^\d+$/;
345
+ });
266
346
 
267
347
  // ../kit/src/args.ts
268
- var DASHES = /^-+/;
348
+ import process6 from "process";
349
+ import { parseArgs } from "util";
269
350
  function jsonOption(holds) {
270
351
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
271
352
  }
272
- class Exit extends Error {
273
- code;
274
- hint;
275
- constructor(message, code, hint) {
276
- super(message);
277
- this.code = code;
278
- this.hint = hint;
279
- }
353
+ function copyOption(what) {
354
+ return { type: "boolean", description: `also copy ${what} to the clipboard` };
280
355
  }
281
356
  function fail(message, code = 2, hint) {
282
357
  throw new Exit(message, code, hint);
283
358
  }
284
-
285
- class UsageError extends Exit {
286
- constructor(message, hint) {
287
- super(message, 2, hint);
288
- }
289
- }
290
359
  function badUsage(message) {
291
360
  throw new UsageError(message);
292
361
  }
293
362
 
294
- class HelpShown extends Exit {
295
- constructor() {
296
- super("help shown", 0);
297
- }
298
- }
299
-
300
363
  class Completing {
301
364
  options;
302
365
  positionals;
@@ -307,11 +370,6 @@ class Completing {
307
370
  this.candidates = candidates;
308
371
  }
309
372
  }
310
- var completion = { active: false };
311
- var OUTPUT_OPTIONS = {
312
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
313
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
314
- };
315
373
  function applyOutput(color, plain, env = process6.env) {
316
374
  const when = plain === true ? "never" : color ?? "auto";
317
375
  if (when === "auto")
@@ -465,7 +523,6 @@ function parseError(error) {
465
523
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
466
524
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
467
525
  }
468
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
469
526
  function nearestOption(message, options, allowNegative) {
470
527
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
471
528
  if (typed === undefined)
@@ -481,833 +538,1103 @@ function nearestOption(message, options, allowNegative) {
481
538
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
482
539
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
483
540
  }
484
- // ../kit/src/argv.ts
485
- import { readFileSync, realpathSync } from "fs";
486
- import { resolve } from "path";
487
- import process7 from "process";
488
- function commandLine() {
489
- try {
490
- return readFileSync("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
491
- } catch {
492
- return;
493
- }
541
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
542
+ var init_args = __esm(() => {
543
+ init_format();
544
+ init_help();
545
+ init_text2();
546
+ init_help();
547
+ init_input();
548
+ DASHES = /^-+/;
549
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
550
+ Exit = class Exit extends Error {
551
+ code;
552
+ hint;
553
+ [EXIT] = true;
554
+ constructor(message, code, hint) {
555
+ super(message);
556
+ this.code = code;
557
+ this.hint = hint;
558
+ }
559
+ static [Symbol.hasInstance](value) {
560
+ if (this !== Exit)
561
+ return Function.prototype[Symbol.hasInstance].call(this, value);
562
+ return typeof value === "object" && value !== null && value[EXIT] === true;
563
+ }
564
+ };
565
+ UsageError = class UsageError extends Exit {
566
+ constructor(message, hint) {
567
+ super(message, 2, hint);
568
+ }
569
+ };
570
+ HelpShown = class HelpShown extends Exit {
571
+ constructor() {
572
+ super("help shown", 0);
573
+ }
574
+ };
575
+ completion = { active: false };
576
+ OUTPUT_OPTIONS = {
577
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
578
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
579
+ };
580
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
581
+ });
582
+
583
+ // ../kit/src/folders.ts
584
+ import { homedir as homedir2 } from "os";
585
+ import { join as join4 } from "path";
586
+ import process12 from "process";
587
+ function cacheFolder({ home = homedir2(), env = process12.env } = {}) {
588
+ return xdgFolder(env.XDG_CACHE_HOME, join4(home, ".cache"));
589
+ }
590
+ var SKIPPED_FOLDERS;
591
+ var init_folders = __esm(() => {
592
+ init_user_config();
593
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
594
+ });
595
+
596
+ // ../kit/src/answers.ts
597
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
598
+ import { dirname as dirname3, join as join5 } from "path";
599
+ function answersFile() {
600
+ return join5(cacheFolder(), "kaynooo-cli", "answers.json");
494
601
  }
495
- function realPath(word) {
602
+ function stored() {
496
603
  try {
497
- return realpathSync(resolve(word));
604
+ const parsed = JSON.parse(readFileSync3(answersFile(), "utf-8"));
605
+ if (typeof parsed !== "object" || parsed === null)
606
+ return {};
607
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
498
608
  } catch {
499
- return;
609
+ return {};
500
610
  }
501
611
  }
502
- function scriptArgs(argv = process7.argv.slice(2), cmdline = commandLine(), script = process7.argv[1]) {
503
- const target = script === undefined ? undefined : realPath(script) ?? script;
504
- const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve(word) === script || realPath(word) === target));
505
- const after = at === -1 ? [] : cmdline.slice(at + 1);
506
- return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
507
- }
508
- // ../kit/src/process.ts
509
- var CLIPBOARDS = [["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"], ["pbcopy"], ["clip.exe"]];
510
- async function copyText(text, which = Bun.which) {
511
- for (const [command, ...args] of CLIPBOARDS) {
512
- const found = which(command);
513
- if (found !== null && await pipeInto([found, ...args], text))
514
- return true;
515
- }
516
- return false;
612
+ function earlierAnswers(key) {
613
+ return stored()[key] ?? [];
517
614
  }
518
- async function pipeInto(argv, text) {
615
+ function rememberAnswer(key, answer) {
616
+ const all = stored();
617
+ const file = answersFile();
618
+ all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
519
619
  try {
520
- const copy = Bun.spawn(argv, { stdin: new Blob([text]), stdout: "ignore", stderr: "ignore" });
521
- return await copy.exited === 0;
522
- } catch {
523
- return false;
524
- }
620
+ mkdirSync2(dirname3(file), { recursive: true });
621
+ writeFileSync(file, JSON.stringify(all));
622
+ } catch {}
525
623
  }
624
+ var KEPT = 50;
625
+ var init_answers = __esm(() => {
626
+ init_folders();
627
+ });
526
628
 
527
- // ../kit/src/progress.ts
528
- var ESC = String.fromCharCode(27);
529
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
530
- var RESET_STYLE = `${ESC}[0m`;
531
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
532
- // ../kit/src/cli.ts
533
- import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
534
- import { dirname as dirname2, join as join2 } from "path";
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));
629
+ // ../kit/src/job.ts
630
+ import process14 from "process";
631
+ function stopJob() {
632
+ process14.kill(0, "SIGTSTP");
553
633
  }
634
+ var init_job = () => {};
554
635
 
555
- // ../kit/src/usage.ts
556
- import { appendFileSync, mkdirSync } from "fs";
557
- import { homedir } from "os";
558
- import { dirname, isAbsolute, join } from "path";
559
- import process9 from "process";
560
-
561
- // ../kit/src/logs.ts
562
- var DAY_MS = 24 * 60 * 60 * 1000;
563
- var CLI_FOLDER = "kaynooo-cli";
564
-
565
- // ../kit/src/usage.ts
566
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
567
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
568
- var LONGEST_NAME = 40;
569
- var usageError;
570
- function noteUsageError(message) {
571
- usageError = message;
572
- }
573
- function stateHome(env = process9.env) {
574
- const dir = env.XDG_STATE_HOME;
575
- return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
576
- }
577
- function usagePath(env = process9.env) {
578
- return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
579
- }
580
- function usageRecorded(env = process9.env) {
581
- const off = env.KAYNOOO_CLI_NO_USAGE;
582
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
636
+ // ../kit/src/picker/line.ts
637
+ function isEditKey(key) {
638
+ return EDIT_KEYS.has(key);
583
639
  }
584
- function flagNames(argv) {
585
- const end = argv.indexOf("--");
586
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
587
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
640
+ function endsKills(key) {
641
+ return typeof key !== "object" && !isEditKey(key);
588
642
  }
589
- function usageEntry(bin, command, argv, code, now = new Date) {
590
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
591
- usageError = undefined;
592
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
643
+ function isWord(char) {
644
+ return char !== undefined && WORD_CHARACTER.test(char);
593
645
  }
594
- function recordUsage(entry, env = process9.env) {
595
- if (!usageRecorded(env))
596
- return;
597
- try {
598
- const path = usagePath(env);
599
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
600
- appendFileSync(path, `${JSON.stringify(entry)}
601
- `, { mode: 384 });
602
- } catch {}
646
+ function wordStart(chars, from) {
647
+ let at = from;
648
+ while (at > 0 && !isWord(chars[at - 1]))
649
+ at--;
650
+ while (at > 0 && isWord(chars[at - 1]))
651
+ at--;
652
+ return at;
603
653
  }
604
-
605
- // ../kit/src/cli.ts
606
- var LEVEL_OPTIONS = {
607
- ...OUTPUT_OPTIONS,
608
- help: { type: "boolean", short: "h", description: "show this help" }
609
- };
610
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
611
- async function commandRows(all, colors) {
612
- const commands = shown(all);
613
- const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
614
- const groups = new Map([["Commands:", []]]);
615
- const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
616
- for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
617
- const heading = group === undefined ? "Commands:" : `${group}:`;
618
- const rows = groups.get(heading) ?? [];
619
- rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
620
- groups.set(heading, rows);
621
- }
622
- return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
654
+ function wordEnd(chars, from) {
655
+ let at = from;
656
+ while (at < chars.length && !isWord(chars[at]))
657
+ at++;
658
+ while (at < chars.length && isWord(chars[at]))
659
+ at++;
660
+ return at;
623
661
  }
624
- function shown(commands) {
625
- return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
662
+ function spacedStart(chars, from) {
663
+ let at = from;
664
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
665
+ at--;
666
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
667
+ at--;
668
+ return at;
626
669
  }
627
- function takeOutputFlags(argv) {
628
- let index = 0;
629
- for (;index < argv.length; index++) {
630
- const word = argv[index];
631
- if (word === "--plain")
632
- applyOutput(undefined, true);
633
- else if (word.startsWith("--color="))
634
- applyOutput(word.slice("--color=".length), undefined);
635
- else if (word === "--color" && argv[index + 1] !== undefined)
636
- applyOutput(argv[++index], undefined);
637
- else
638
- break;
639
- }
640
- return argv.slice(index);
670
+ function cut(chars, from, to) {
671
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
641
672
  }
642
- async function resolveSummary(summary) {
643
- return typeof summary === "string" ? summary : summary();
673
+ function insert(chars, at, text) {
674
+ const typed = [...text];
675
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
644
676
  }
645
- function scopeOf(commands, extra, aliases) {
646
- return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
677
+ function editLine(line, key) {
678
+ const { killed = "", chained = false } = line;
679
+ const chars = [...line.text];
680
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
681
+ const edited = edit(chars, at, key, killed);
682
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
683
+ return line.killed === undefined ? edited : { ...edited, killed };
684
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
685
+ if (taken === "")
686
+ return { ...edited, killed, chained };
687
+ if (!chained)
688
+ return { ...edited, killed: taken, chained: true };
689
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
647
690
  }
648
- async function expand(scope, words) {
649
- if (scope.lazy.length === 0)
650
- return scope;
651
- const commands = { ...scope.commands };
652
- for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
653
- for (const [name, command] of Object.entries(added))
654
- commands[name] ??= command;
655
- }
656
- return { ...scope, commands, lazy: [] };
691
+ function edit(chars, at, key, killed) {
692
+ const text = chars.join("");
693
+ if (typeof key === "object")
694
+ return insert(chars, at, key.text);
695
+ switch (key) {
696
+ case "left":
697
+ return { text, caret: Math.max(at - 1, 0) };
698
+ case "right":
699
+ return { text, caret: Math.min(at + 1, chars.length) };
700
+ case "wordleft":
701
+ return { text, caret: wordStart(chars, at) };
702
+ case "wordright":
703
+ return { text, caret: wordEnd(chars, at) };
704
+ case "linestart":
705
+ return { text, caret: 0 };
706
+ case "lineend":
707
+ return { text, caret: chars.length };
708
+ case "erase":
709
+ return cut(chars, Math.max(at - 1, 0), at);
710
+ case "delete":
711
+ return cut(chars, at, Math.min(at + 1, chars.length));
712
+ case "word":
713
+ return cut(chars, spacedStart(chars, at), at);
714
+ case "killword":
715
+ return cut(chars, wordStart(chars, at), at);
716
+ case "killnext":
717
+ return cut(chars, at, wordEnd(chars, at));
718
+ case "clear":
719
+ return cut(chars, 0, at);
720
+ case "killend":
721
+ return cut(chars, at, chars.length);
722
+ case "yank":
723
+ return insert(chars, at, killed);
724
+ }
657
725
  }
658
- async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
659
- const colors = paint(stream);
660
- const prefix = path.join(" ");
661
- const summary = await resolveSummary(lazySummary);
662
- if (wantsHelpJson())
663
- return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
664
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
665
- const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
666
- const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
667
- return [
668
- header(colors, summary),
669
- "",
670
- usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
671
- "",
672
- ...await commandRows(commands, colors),
673
- ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
674
- "",
675
- colors.bold("Options:"),
676
- ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
677
- ...exampleRows(examples ?? [], colors),
678
- "",
679
- `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
680
- ].join(`
681
- `);
726
+ function visible({ text, caret }, room) {
727
+ const chars = [...text];
728
+ const at = Math.min(Math.max(caret, 0), chars.length);
729
+ const cells = at === chars.length ? [...chars, " "] : chars;
730
+ const widths = cells.map((char) => Bun.stringWidth(char));
731
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
732
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
733
+ let start = at;
734
+ let end = at + 1;
735
+ while (start > 0 && fits(start - 1, end))
736
+ start--;
737
+ while (end < cells.length && fits(start, end + 1))
738
+ end++;
739
+ const left = start > 0 ? "\u2026" : "";
740
+ const right = end < cells.length ? "\u2026" : "";
741
+ 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) };
682
742
  }
683
- function printError(prefix, message, hint, cause) {
684
- const colors = paint(process10.stderr);
685
- const styled = takesControlCodes(process10.stderr);
686
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
687
- const under = (label, text, tint) => text === undefined ? "" : `
688
- ${styled ? tint(label) : `${label}:`} ${text}`;
689
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
743
+ var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS, WORD_CHARACTER, SPACE;
744
+ var init_line = __esm(() => {
745
+ EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
746
+ BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
747
+ FORWARD_KILLS = new Set(["killnext", "killend"]);
748
+ WORD_CHARACTER = /[\p{L}\p{N}_]/u;
749
+ SPACE = /\s/;
750
+ });
751
+
752
+ // ../kit/src/picker/score.ts
753
+ var BOUNDARY_AFTER, NONE;
754
+ var init_score = __esm(() => {
755
+ BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
756
+ NONE = Number.NEGATIVE_INFINITY;
757
+ });
758
+
759
+ // ../kit/src/picker/state.ts
760
+ function repeat(value, count) {
761
+ return Array.from({ length: count }).fill(value);
690
762
  }
691
- function printJsonError(message, hint, cause) {
692
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
763
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
764
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
765
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
766
+ const wheel = MOUSE.exec(sequence)?.[1];
767
+ if (wheel !== undefined)
768
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
769
+ const named = codes.get(sequence);
770
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
771
+ if (sequence === PASTE_START || sequence === PASTE_END) {
772
+ paste.active = sequence === PASTE_START;
773
+ return [];
774
+ }
775
+ if (paste.active && (sequence === "\r" || sequence === `
776
+ `))
777
+ return [];
778
+ if (key !== undefined)
779
+ return [key];
780
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
781
+ });
693
782
  }
694
- function wantsJson(argv) {
695
- const end = argv.indexOf("--");
696
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
783
+ var IS_CONTROL, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS;
784
+ var init_state = __esm(() => {
785
+ init_text2();
786
+ init_line();
787
+ init_score();
788
+ IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
789
+ KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
790
+ MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
791
+ KEYS = {
792
+ "\x1B[A": "up",
793
+ "\x1BOA": "up",
794
+ "\x10": "up",
795
+ "\x1B[B": "down",
796
+ "\x1BOB": "down",
797
+ "\x0E": "down",
798
+ "\x1B[5~": "pageup",
799
+ "\x1B[6~": "pagedown",
800
+ "\x1B[H": "home",
801
+ "\x1B[1~": "home",
802
+ "\x1BOH": "home",
803
+ "\x1B[F": "end",
804
+ "\x1B[4~": "end",
805
+ "\x1BOF": "end",
806
+ "\r": "enter",
807
+ "\n": "enter",
808
+ "\x03": "cancel",
809
+ "\x1B": "cancel",
810
+ "\x1B[D": "left",
811
+ "\x1BOD": "left",
812
+ "\x1B[C": "right",
813
+ "\x1BOC": "right",
814
+ "\x1B[1;5D": "wordleft",
815
+ "\x1B[1;3D": "wordleft",
816
+ "\x1Bb": "wordleft",
817
+ "\x1B[1;5C": "wordright",
818
+ "\x1B[1;3C": "wordright",
819
+ "\x1Bf": "wordright",
820
+ "\x01": "linestart",
821
+ "\x05": "lineend",
822
+ "\x7F": "erase",
823
+ "\x1B[3~": "delete",
824
+ "\b": "killword",
825
+ "\x1B\x7F": "killword",
826
+ "\x1B[3;5~": "killnext",
827
+ "\x1Bd": "killnext",
828
+ "\x15": "clear",
829
+ "\v": "killend",
830
+ "\x17": "word",
831
+ "\x19": "yank",
832
+ "\x1A": "suspend",
833
+ "\t": "tab",
834
+ "\x1F": "help",
835
+ "\x1BOP": "help",
836
+ "\x1B[11~": "help"
837
+ };
838
+ });
839
+
840
+ // ../kit/src/redraw.ts
841
+ function overwrite(lines, columns) {
842
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
843
+ `);
697
844
  }
698
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
699
- if (error instanceof HelpShown)
700
- return 0;
701
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
702
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
703
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
704
- if (error instanceof Exit && error.code === 2)
705
- noteUsageError(error.message);
706
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
707
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
708
- return error instanceof Exit ? error.code : 1;
845
+ function rowsTaken(lines, columns) {
846
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
709
847
  }
710
- async function dispatch(level, typed, { version, redact }) {
711
- const prefix = level.path.join(" ");
712
- let argv;
713
- try {
714
- argv = takeOutputFlags(typed);
715
- } catch (error) {
716
- return reportThrown(prefix, error);
717
- }
718
- const [name, ...args] = argv;
719
- const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
720
- if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
721
- try {
722
- return await fallback.run([]);
723
- } catch (error) {
724
- return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
725
- }
726
- }
727
- if (name === undefined && level.path.length > 1) {
728
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stderr));
729
- return 2;
730
- }
731
- if (name === undefined || name === "help" || name === "--help" || name === "-h") {
732
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stdout));
733
- return 0;
734
- }
735
- if (level.path.length === 1 && (name === "--version" || name === "-v")) {
736
- console.log(version);
737
- return 0;
738
- }
739
- let command = level.commands[level.aliases?.[name] ?? name];
740
- let rest = args;
741
- let ran = name;
742
- if (command === undefined && level.lazy.length > 0) {
743
- level = await expand(level, [...level.path.slice(1), ...argv]);
744
- command = level.commands[level.aliases?.[name] ?? name];
745
- }
746
- if (command === undefined && level.defaultCommand !== undefined) {
747
- command = level.commands[level.defaultCommand];
748
- rest = argv;
749
- ran = level.defaultCommand;
750
- }
751
- if (command === undefined) {
752
- const meant = closest(name, Object.keys(shown(level.commands)));
753
- printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
754
- return 2;
755
- }
756
- if ("commands" in command) {
757
- const { summary } = command;
758
- return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
759
- }
760
- try {
761
- return await command.run(rest);
762
- } catch (error) {
763
- return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
764
- }
848
+ var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
849
+ var init_redraw = __esm(() => {
850
+ init_format();
851
+ });
852
+
853
+ // ../kit/src/prompt.ts
854
+ import process15 from "process";
855
+ function readKeys(input, paste = { active: false }) {
856
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
765
857
  }
766
- var COMPLETE = "__complete";
767
- var FILES = "__files__";
768
- async function completingOf(run) {
769
- completion.active = true;
770
- try {
771
- await run([]);
772
- } catch (error) {
773
- if (error instanceof Completing)
774
- return error;
775
- } finally {
776
- completion.active = false;
777
- }
778
- return new Completing({});
858
+ function roomAfter(question, columns) {
859
+ return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
779
860
  }
780
- async function optionsOf(run) {
781
- return (await completingOf(run)).options;
861
+ function withCaret(colors, line, room, dim = false) {
862
+ const { before, at, after } = visible(line, room);
863
+ const tone = dim ? colors.dim : (text) => text;
864
+ return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
782
865
  }
783
- function candidateLine(candidate) {
784
- return typeof candidate === "string" ? candidate : candidate.join("\t");
866
+ function sharedStart(texts) {
867
+ const [first = [], ...rest] = texts.map((text) => [...text]);
868
+ let length = first.length;
869
+ for (const chars of rest) {
870
+ const differs = chars.findIndex((char, index) => char !== first[index]);
871
+ length = Math.min(length, differs === -1 ? chars.length : differs);
872
+ }
873
+ return first.slice(0, length).join("");
785
874
  }
786
- function positionalBeingTyped(before, { options, positionals }) {
787
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
788
- const typed = [];
789
- let at = 0;
790
- while (at < before.length) {
791
- const word = before[at];
792
- if (word === "--") {
793
- typed.push(...before.slice(at + 1));
794
- break;
875
+ function listed2(colors, found, columns) {
876
+ const shared = sharedStart(found);
877
+ const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
878
+ const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
879
+ const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
880
+ return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
881
+ }
882
+ async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
883
+ let line = { text: "", caret: 0 };
884
+ let invalid;
885
+ let completions = [];
886
+ const remembered = history === undefined || mask ? undefined : history;
887
+ const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
888
+ let recalled = -1;
889
+ let draft = line;
890
+ const taken = () => line.text === "" ? fallback ?? "" : line.text;
891
+ const shown = () => mask ? "*".repeat([...taken()].length) : taken();
892
+ const accepted = await ask(question, settings, (colors, state, { columns }) => {
893
+ if (state !== "asking")
894
+ return [answer(colors, question, state, shown())];
895
+ const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
896
+ return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
897
+ }, (key) => {
898
+ if (key === "cancel")
899
+ return "cancel";
900
+ invalid = undefined;
901
+ completions = [];
902
+ if (line.chained === true && endsKills(key))
903
+ line = { ...line, chained: false };
904
+ if (key === "tab") {
905
+ const chars = [...line.text];
906
+ const before = chars.slice(0, line.caret).join("");
907
+ const found = complete?.(before) ?? [];
908
+ const filled = sharedStart(found);
909
+ if ([...filled].length > [...before].length)
910
+ line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
911
+ else
912
+ completions = found;
913
+ return;
795
914
  }
796
- if (!word.startsWith("-"))
797
- typed.push(word);
798
- else if (takesValue(word))
799
- at++;
800
- at++;
801
- }
802
- const last = positionals.at(-1);
803
- if (typed.length < positionals.length)
804
- return { name: positionals[typed.length], typed };
805
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
915
+ if (key === "enter") {
916
+ invalid = validate?.(taken());
917
+ return invalid === undefined ? "enter" : undefined;
918
+ }
919
+ if (key === "up" || key === "down") {
920
+ const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
921
+ if (recalled === -1)
922
+ draft = line;
923
+ recalled = to;
924
+ const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
925
+ line = { ...shown, killed: line.killed ?? "" };
926
+ return;
927
+ }
928
+ const edit = { home: "linestart", end: "lineend" }[key] ?? key;
929
+ if (typeof edit === "object" || isEditKey(edit))
930
+ line = editLine(line, edit);
931
+ return;
932
+ });
933
+ if (!accepted)
934
+ return;
935
+ if (remembered !== undefined && taken() !== "")
936
+ rememberAnswer(remembered, taken());
937
+ return taken();
806
938
  }
807
- async function leafCandidates(run, words) {
808
- const completing = await completingOf(run);
809
- if ((words.at(-1) ?? "").startsWith("-"))
810
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
811
- const flag = words.at(-2);
812
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
813
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
814
- if (option?.type === "string") {
815
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
816
- return values === undefined ? [FILES] : values.map(candidateLine);
939
+ function answer(colors, question, state, picked) {
940
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
941
+ }
942
+ async function ask(question, { hint, terminal = process15 }, render, press) {
943
+ const { stdin, stderr } = terminal;
944
+ if (!isInteractive(terminal))
945
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
946
+ const colors = paint(stderr);
947
+ let current = "asking";
948
+ let outcome;
949
+ const columns = () => stderr.columns || 80;
950
+ const draw = (state, last = false) => {
951
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
952
+ const rows = rowsTaken(frame, columns());
953
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
954
+ current = state;
955
+ };
956
+ const redraw = () => draw(current);
957
+ const paste = { active: false };
958
+ const stop = terminal.stop ?? (terminal === process15 ? stopJob : undefined);
959
+ const suspend = () => {
960
+ if (stop === undefined)
961
+ return;
962
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
963
+ stdin.setRawMode(false);
964
+ stop();
965
+ stdin.setRawMode(true);
966
+ stderr.write("\x1B[?25l\x1B[?2004h");
967
+ };
968
+ try {
969
+ stderr.on?.("resize", redraw);
970
+ stdin.setRawMode(true);
971
+ stdin.resume();
972
+ stderr.write("\x1B[?25l\x1B[?2004h");
973
+ draw("asking");
974
+ return await new Promise((resolve) => {
975
+ function onData(data) {
976
+ for (const key of readKeys(data.toString(), paste)) {
977
+ if (key === "suspend") {
978
+ suspend();
979
+ continue;
980
+ }
981
+ const pressed = press(key);
982
+ if (pressed !== undefined) {
983
+ settle(pressed);
984
+ return;
985
+ }
986
+ }
987
+ draw("asking");
988
+ }
989
+ function onEnd() {
990
+ settle("cancel");
991
+ }
992
+ function settle(settled) {
993
+ outcome = settled;
994
+ stdin.off("data", onData);
995
+ stdin.off("end", onEnd);
996
+ resolve(settled === "enter");
997
+ }
998
+ stdin.on("data", onData);
999
+ stdin.on("end", onEnd);
1000
+ });
1001
+ } finally {
1002
+ stderr.off?.("resize", redraw);
1003
+ draw(outcome ?? "cancel", true);
1004
+ stderr.write(`
1005
+ \x1B[?25h\x1B[?2004l`);
1006
+ stdin.setRawMode(false);
1007
+ stdin.pause();
817
1008
  }
818
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
819
- return values === undefined ? [FILES] : values.map(candidateLine);
820
1009
  }
821
- async function candidates(scope, defaultCommand, words, before = []) {
822
- const [word = "", ...rest] = words;
823
- const listing = rest.length === 0 && !word.startsWith("-");
824
- let { commands, aliases } = scope;
825
- let command = commands[aliases?.[word] ?? word];
826
- if (listing || command === undefined) {
827
- ({ commands, aliases } = await expand(scope, [...before, ...words]));
828
- command = commands[aliases?.[word] ?? word];
829
- }
830
- if (listing) {
831
- const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
832
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
833
- const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
834
- const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
835
- return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
836
- }
837
- if (command === undefined) {
838
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
839
- return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
1010
+ var PROMPT_KEYS, MAX_LISTED = 12;
1011
+ var init_prompt = __esm(() => {
1012
+ init_answers();
1013
+ init_args();
1014
+ init_format();
1015
+ init_job();
1016
+ init_mode();
1017
+ init_line();
1018
+ init_state();
1019
+ init_redraw();
1020
+ init_style();
1021
+ PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
1022
+ });
1023
+
1024
+ // src/cli.ts
1025
+ import process16 from "process";
1026
+
1027
+ // ../kit/src/index.ts
1028
+ init_args();
1029
+
1030
+ // ../kit/src/argv.ts
1031
+ import { readFileSync, realpathSync } from "fs";
1032
+ import { resolve } from "path";
1033
+ import process7 from "process";
1034
+ function commandLine() {
1035
+ try {
1036
+ return readFileSync("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
1037
+ } catch {
1038
+ return;
840
1039
  }
841
- return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
842
- }
843
- async function printCandidates(found) {
844
- for (const line of await found)
845
- console.log(line);
846
- return 0;
847
1040
  }
848
- function packageVersion(entry = Bun.main) {
849
- let resolved = entry;
1041
+ function realPath(word) {
850
1042
  try {
851
- resolved = realpathSync2(entry);
852
- } catch {}
853
- for (let dir = dirname2(resolved);; dir = dirname2(dir)) {
854
- try {
855
- const { version } = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
856
- if (typeof version === "string")
857
- return version;
858
- } catch {}
859
- if (dirname2(dir) === dir)
860
- return "0.0.0";
1043
+ return realpathSync(resolve(word));
1044
+ } catch {
1045
+ return;
861
1046
  }
862
1047
  }
863
- async function runCli(cli, argv = scriptArgs()) {
864
- const version = cli.version ?? packageVersion();
865
- if (argv[0] === COMPLETE)
866
- return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
867
- const started = performance.now();
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);
871
- if (cli.usage !== false) {
872
- try {
873
- recordUsage(usageEntry(cli.name, command, argv, code));
874
- } catch {}
1048
+ function scriptArgs(argv = process7.argv.slice(2), cmdline = commandLine(), script = process7.argv[1]) {
1049
+ const target = script === undefined ? undefined : realPath(script) ?? script;
1050
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve(word) === script || realPath(word) === target));
1051
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
1052
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
1053
+ }
1054
+ // ../kit/src/chart.ts
1055
+ init_format();
1056
+ init_mode();
1057
+ init_style();
1058
+ init_theme();
1059
+ // ../kit/src/ci.ts
1060
+ init_args();
1061
+ init_format();
1062
+
1063
+ // ../kit/src/progress.ts
1064
+ init_format();
1065
+
1066
+ // ../kit/src/process.ts
1067
+ var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
1068
+ var CLIPBOARDS = [["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"], ["pbcopy"], ["clip.exe"]];
1069
+ async function copyText(text, which = Bun.which) {
1070
+ for (const [command, ...args] of CLIPBOARDS) {
1071
+ const found = which(command);
1072
+ if (found !== null && await pipeInto([found, ...args], text))
1073
+ return true;
875
1074
  }
876
- return code;
1075
+ return false;
877
1076
  }
878
- function commandPath(scope, argv) {
879
- const path = [];
880
- let level = scope;
881
- for (const word of argv.filter((each) => !each.startsWith("-"))) {
882
- const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
883
- const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
884
- if (command === undefined)
885
- break;
886
- path.push(word);
887
- if (!("commands" in command))
888
- break;
889
- level = scopeOf(command.commands, command.extraCommands, command.aliases);
1077
+ async function pipeInto(argv, text) {
1078
+ try {
1079
+ const copy = Bun.spawn(argv, { stdin: new Blob([text]), stdout: "ignore", stderr: "ignore" });
1080
+ return await copy.exited === 0;
1081
+ } catch {
1082
+ return false;
890
1083
  }
891
- return path.length === 0 ? undefined : path.join(" ");
892
1084
  }
893
- // ../kit/src/folders.ts
894
- import { homedir as homedir2 } from "os";
895
- import { join as join3 } from "path";
1085
+
1086
+ // ../kit/src/progress.ts
1087
+ init_style();
1088
+ init_theme();
1089
+ var ESC = String.fromCharCode(27);
1090
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
1091
+ var RESET_STYLE = `${ESC}[0m`;
1092
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1093
+
1094
+ // ../kit/src/ci.ts
1095
+ init_style();
1096
+
1097
+ // ../kit/src/tool.ts
1098
+ init_format();
1099
+ // ../kit/src/cli.ts
1100
+ init_args();
1101
+ import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
1102
+ import { dirname as dirname2, join as join3 } from "path";
896
1103
  import process11 from "process";
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
- }
901
- // ../kit/src/secrets.ts
902
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
903
- // ../kit/src/sessions.ts
904
- var {Glob } = globalThis.Bun;
905
- var SESSION_FILES = new Glob("*.json");
906
- var ACCOUNT_DIRS = new Glob("*/sessions");
907
- // ../kit/src/prompt.ts
908
- import process14 from "process";
909
1104
 
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() {
1105
+ // ../kit/src/askpass.ts
1106
+ import process8 from "process";
1107
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1108
+ async function askpassClient(argv) {
1109
+ const socketPath = process8.env[SOCKET_VARIABLE];
1110
+ if (socketPath === undefined)
1111
+ return;
1112
+ const request = { prompt: argv[0] ?? "", ...process8.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1113
+ const { promise, resolve } = Promise.withResolvers();
1114
+ let received = "";
918
1115
  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")));
1116
+ await Bun.connect({
1117
+ unix: socketPath,
1118
+ socket: {
1119
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
1120
+ `),
1121
+ data: (_, chunk) => {
1122
+ received += chunk.toString();
1123
+ },
1124
+ close: () => resolve(received),
1125
+ error: () => resolve("")
1126
+ }
1127
+ });
923
1128
  } catch {
924
- return {};
1129
+ return 1;
925
1130
  }
1131
+ const reply = await promise;
1132
+ if (reply === "")
1133
+ return 1;
1134
+ const { answer } = JSON.parse(reply);
1135
+ if (request.notice === true)
1136
+ return 0;
1137
+ if (answer === undefined)
1138
+ return 1;
1139
+ process8.stdout.write(`${answer}
1140
+ `);
1141
+ return 0;
926
1142
  }
927
- function earlierAnswers(key) {
928
- return stored()[key] ?? [];
1143
+
1144
+ // ../kit/src/completions.ts
1145
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1146
+ 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'
1147
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1148
+ set -l current (commandline -ct)
1149
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1150
+ if test "$line" = __files__
1151
+ __fish_complete_path $current
1152
+ else
1153
+ echo $line
1154
+ end
1155
+ end
1156
+ end`;
1157
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1158
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1159
+ local -a lines
1160
+ COMPREPLY=()
1161
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1162
+ for line in "\${lines[@]}"; do
1163
+ if [[ $line == __files__ ]]; then
1164
+ COMPREPLY+=($(compgen -f -- "$cur"))
1165
+ else
1166
+ words+="\${line%%$'\\t'*}"$'\\n'
1167
+ fi
1168
+ done
1169
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1170
+ }`;
1171
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1172
+ local line
1173
+ local -a described plain
1174
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1175
+ if [[ $line == __files__ ]]; then
1176
+ _files
1177
+ elif [[ $line == *$'\\t'* ]]; then
1178
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1179
+ else
1180
+ plain+=("$line")
1181
+ fi
1182
+ done
1183
+ (( \${#described} )) && _describe -V value described
1184
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1185
+ return 0
1186
+ }`;
1187
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1188
+ if (shell === "fish")
1189
+ return `${header}
1190
+ ${FISH_FUNCTION}
1191
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1192
+ `).join("")}`;
1193
+ if (shell === "bash")
1194
+ return `${header}
1195
+ ${BASH_FUNCTION}
1196
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1197
+ `;
1198
+ return `${header}
1199
+ ${ZSH_FUNCTION}
1200
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1201
+ `;
929
1202
  }
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 {}
1203
+
1204
+ // ../kit/src/notify.ts
1205
+ init_format();
1206
+ init_mode();
1207
+ import process9 from "process";
1208
+ var NOTIFY_AFTER_MS = 1e4;
1209
+ var CANCELLED = 130;
1210
+ function base64(text) {
1211
+ return Buffer.from(text).toString("base64");
1212
+ }
1213
+ function notification(title, body, env = process9.env) {
1214
+ const id = `kit${process9.pid}`;
1215
+ 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\\`];
1216
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1217
+ }
1218
+ function notifyEnd(command, code, ms, { stream = process9.stderr, env = process9.env } = {}) {
1219
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1220
+ return;
1221
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
938
1222
  }
939
1223
 
940
- // ../kit/src/job.ts
941
- import process13 from "process";
942
- function stopJob() {
943
- process13.kill(0, "SIGTSTP");
1224
+ // ../kit/src/cli.ts
1225
+ init_style();
1226
+ init_text2();
1227
+
1228
+ // ../kit/src/usage.ts
1229
+ import { appendFileSync, mkdirSync } from "fs";
1230
+ import { homedir } from "os";
1231
+ import { dirname, join as join2 } from "path";
1232
+ import process10 from "process";
1233
+
1234
+ // ../kit/src/logs.ts
1235
+ init_user_config();
1236
+ var DAY_MS = 24 * 60 * 60 * 1000;
1237
+ var CLI_FOLDER = "kaynooo-cli";
1238
+
1239
+ // ../kit/src/usage.ts
1240
+ init_user_config();
1241
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1242
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1243
+ var LONGEST_NAME = 40;
1244
+ var usageError;
1245
+ function noteUsageError(message) {
1246
+ usageError = message;
1247
+ }
1248
+ function stateHome(env = process10.env) {
1249
+ return xdgFolder(env.XDG_STATE_HOME, join2(homedir(), ".local", "state"));
1250
+ }
1251
+ function usagePath(env = process10.env) {
1252
+ return join2(stateHome(env), CLI_FOLDER, "usage.jsonl");
1253
+ }
1254
+ function usageRecorded(env = process10.env) {
1255
+ const off = env.KAYNOOO_CLI_NO_USAGE;
1256
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1257
+ }
1258
+ function flagNames(argv) {
1259
+ const end = argv.indexOf("--");
1260
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1261
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1262
+ }
1263
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1264
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1265
+ usageError = undefined;
1266
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1267
+ }
1268
+ function recordUsage(entry, env = process10.env) {
1269
+ if (!usageRecorded(env))
1270
+ return;
1271
+ try {
1272
+ const path = usagePath(env);
1273
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
1274
+ appendFileSync(path, `${JSON.stringify(entry)}
1275
+ `, { mode: 384 });
1276
+ } catch {}
944
1277
  }
945
1278
 
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);
1279
+ // ../kit/src/cli.ts
1280
+ var LEVEL_OPTIONS = {
1281
+ ...OUTPUT_OPTIONS,
1282
+ help: { type: "boolean", short: "h", description: "show this help" }
1283
+ };
1284
+ var TOP_OPTIONS = {
1285
+ ...LEVEL_OPTIONS,
1286
+ version: { type: "boolean", short: "v", description: "print the version" },
1287
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1288
+ };
1289
+ async function commandRows(all, colors) {
1290
+ const commands = shown(all);
1291
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
1292
+ const groups = new Map([["Commands:", []]]);
1293
+ const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
1294
+ for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
1295
+ const heading = group === undefined ? "Commands:" : `${group}:`;
1296
+ const rows = groups.get(heading) ?? [];
1297
+ rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
1298
+ groups.set(heading, rows);
1299
+ }
1300
+ return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
952
1301
  }
953
- function endsKills(key) {
954
- return typeof key !== "object" && !isEditKey(key);
1302
+ function shown(commands) {
1303
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
955
1304
  }
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);
1305
+ function takeOutputFlags(argv) {
1306
+ let index = 0;
1307
+ for (;index < argv.length; index++) {
1308
+ const word = argv[index];
1309
+ if (word === "--plain")
1310
+ applyOutput(undefined, true);
1311
+ else if (word.startsWith("--color="))
1312
+ applyOutput(word.slice("--color=".length), undefined);
1313
+ else if (word === "--color" && argv[index + 1] !== undefined)
1314
+ applyOutput(argv[++index], undefined);
1315
+ else
1316
+ break;
1317
+ }
1318
+ return argv.slice(index);
960
1319
  }
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;
1320
+ async function resolveSummary(summary) {
1321
+ return typeof summary === "string" ? summary : summary();
968
1322
  }
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;
1323
+ function lookup({ commands, aliases }, word) {
1324
+ const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
1325
+ return Object.hasOwn(commands, name) ? commands[name] : undefined;
976
1326
  }
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;
1327
+ function scopeOf(commands, extra, aliases) {
1328
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
984
1329
  }
985
- function cut(chars, from, to) {
986
- return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
1330
+ async function expand(scope, words) {
1331
+ if (scope.lazy.length === 0)
1332
+ return scope;
1333
+ const commands = { ...scope.commands };
1334
+ for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
1335
+ for (const [name, command] of Object.entries(added))
1336
+ commands[name] ??= command;
1337
+ }
1338
+ return { ...scope, commands, lazy: [] };
987
1339
  }
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 };
1340
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
1341
+ const colors = paint(stream);
1342
+ const prefix = path.join(" ");
1343
+ const summary = await resolveSummary(lazySummary);
1344
+ if (wantsHelpJson())
1345
+ return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
1346
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1347
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
1348
+ const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
1349
+ return [
1350
+ header(colors, summary),
1351
+ "",
1352
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
1353
+ "",
1354
+ ...await commandRows(commands, colors),
1355
+ ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
1356
+ "",
1357
+ colors.bold("Options:"),
1358
+ ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
1359
+ ...exampleRows(examples ?? [], colors),
1360
+ "",
1361
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
1362
+ ].join(`
1363
+ `);
991
1364
  }
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 };
1365
+ function printError(prefix, message, hint, cause) {
1366
+ const colors = paint(process11.stderr);
1367
+ const styled = takesControlCodes(process11.stderr);
1368
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1369
+ const under = (label, text, tint) => text === undefined ? "" : `
1370
+ ${styled ? tint(label) : `${label}:`} ${text}`;
1371
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1005
1372
  }
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
- }
1373
+ function printJsonError(message, hint, cause) {
1374
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1040
1375
  }
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) };
1376
+ function wantsJson(argv) {
1377
+ const end = argv.indexOf("--");
1378
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1057
1379
  }
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);
1380
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
1381
+ if (error instanceof HelpShown)
1382
+ return 0;
1383
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1384
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1385
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1386
+ if (error instanceof Exit && error.code === 2)
1387
+ noteUsageError(error.message);
1388
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1389
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1390
+ return error instanceof Exit ? error.code : 1;
1119
1391
  }
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 [];
1392
+ async function dispatch(level, typed, { version, redact }) {
1393
+ const prefix = level.path.join(" ");
1394
+ let argv;
1395
+ try {
1396
+ argv = takeOutputFlags(typed);
1397
+ } catch (error) {
1398
+ return reportThrown(prefix, error);
1399
+ }
1400
+ const [name, ...args] = argv;
1401
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
1402
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
1403
+ try {
1404
+ return await fallback.run([]);
1405
+ } catch (error) {
1406
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
1131
1407
  }
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
- });
1408
+ }
1409
+ if (name === undefined && level.path.length > 1) {
1410
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process11.stderr));
1411
+ return 2;
1412
+ }
1413
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1414
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process11.stdout));
1415
+ return 0;
1416
+ }
1417
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
1418
+ console.log(version);
1419
+ return 0;
1420
+ }
1421
+ let command = lookup(level, name);
1422
+ let rest = args;
1423
+ let ran = name;
1424
+ if (command === undefined && level.lazy.length > 0) {
1425
+ level = await expand(level, [...level.path.slice(1), ...argv]);
1426
+ command = lookup(level, name);
1427
+ }
1428
+ if (command === undefined && level.defaultCommand !== undefined) {
1429
+ command = level.commands[level.defaultCommand];
1430
+ rest = argv;
1431
+ ran = level.defaultCommand;
1432
+ }
1433
+ if (command === undefined) {
1434
+ const meant = closest(name, Object.keys(shown(level.commands)));
1435
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
1436
+ return 2;
1437
+ }
1438
+ if ("commands" in command) {
1439
+ const { summary } = command;
1440
+ return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
1441
+ }
1442
+ try {
1443
+ return await command.run(rest);
1444
+ } catch (error) {
1445
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
1446
+ }
1139
1447
  }
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
- `);
1448
+ var COMPLETE = "__complete";
1449
+ var FILES = "__files__";
1450
+ async function completingOf(run) {
1451
+ completion.active = true;
1452
+ try {
1453
+ await run([]);
1454
+ } catch (error) {
1455
+ if (error instanceof Completing)
1456
+ return error;
1457
+ } finally {
1458
+ completion.active = false;
1459
+ }
1460
+ return new Completing({});
1147
1461
  }
1148
- function rowsTaken(lines, columns) {
1149
- return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1462
+ async function optionsOf(run) {
1463
+ return (await completingOf(run)).options;
1150
1464
  }
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));
1465
+ function candidateLine(candidate) {
1466
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
1157
1467
  }
1158
- function roomAfter(question, columns) {
1159
- return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
1468
+ function positionalBeingTyped(before, { options, positionals }) {
1469
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1470
+ const typed = [];
1471
+ let at = 0;
1472
+ while (at < before.length) {
1473
+ const word = before[at];
1474
+ if (word === "--") {
1475
+ typed.push(...before.slice(at + 1));
1476
+ break;
1477
+ }
1478
+ if (!word.startsWith("-"))
1479
+ typed.push(word);
1480
+ else if (takesValue(word))
1481
+ at++;
1482
+ at++;
1483
+ }
1484
+ const last = positionals.at(-1);
1485
+ if (typed.length < positionals.length)
1486
+ return { name: positionals[typed.length], typed };
1487
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1160
1488
  }
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)}`;
1489
+ async function leafCandidates(run, words) {
1490
+ const completing = await completingOf(run);
1491
+ if ((words.at(-1) ?? "").startsWith("-"))
1492
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1493
+ const flag = words.at(-2);
1494
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1495
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1496
+ if (option?.type === "string") {
1497
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1498
+ return values === undefined ? [FILES] : values.map(candidateLine);
1499
+ }
1500
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1501
+ return values === undefined ? [FILES] : values.map(candidateLine);
1165
1502
  }
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);
1503
+ async function candidates(scope, defaultCommand, words, before = []) {
1504
+ const [word = "", ...rest] = words;
1505
+ const listing = rest.length === 0 && !word.startsWith("-");
1506
+ let { commands } = scope;
1507
+ let command = lookup(scope, word);
1508
+ if (listing || command === undefined) {
1509
+ const expanded = await expand(scope, [...before, ...words]);
1510
+ commands = expanded.commands;
1511
+ command = lookup(expanded, word);
1172
1512
  }
1173
- return first.slice(0, length).join("");
1513
+ if (listing) {
1514
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1515
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1516
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1517
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1518
+ return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
1519
+ }
1520
+ if (command === undefined) {
1521
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1522
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
1523
+ }
1524
+ return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1174
1525
  }
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)))}`;
1526
+ var COMPLETIONS = "--completions";
1527
+ function flagValue([flag = "", ...rest]) {
1528
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1181
1529
  }
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();
1530
+ function printCompletionScript(name, args) {
1531
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1532
+ if (shell === undefined || args.length !== 1) {
1533
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1534
+ return 2;
1535
+ }
1536
+ console.log(completionScript(shell, [name]).trimEnd());
1537
+ return 0;
1238
1538
  }
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")}`;
1539
+ async function printCandidates(found) {
1540
+ for (const line of await found)
1541
+ console.log(line);
1542
+ return 0;
1241
1543
  }
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
- };
1544
+ function packageVersion(entry = Bun.main) {
1545
+ let resolved = entry;
1268
1546
  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();
1547
+ resolved = realpathSync2(entry);
1548
+ } catch {}
1549
+ for (let dir = dirname2(resolved);; dir = dirname2(dir)) {
1550
+ try {
1551
+ const { version } = JSON.parse(readFileSync2(join3(dir, "package.json"), "utf8"));
1552
+ if (typeof version === "string")
1553
+ return version;
1554
+ } catch {}
1555
+ if (dirname2(dir) === dir)
1556
+ return "0.0.0";
1557
+ }
1558
+ }
1559
+ async function runCli(cli, argv = scriptArgs()) {
1560
+ const version = cli.version ?? packageVersion();
1561
+ const answered = await askpassClient(argv);
1562
+ if (answered !== undefined)
1563
+ return answered;
1564
+ if (argv[0] === COMPLETE)
1565
+ return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1566
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1567
+ return printCompletionScript(cli.name, flagValue(argv));
1568
+ const started = performance.now();
1569
+ 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 });
1570
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1571
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1572
+ if (cli.usage !== false) {
1573
+ try {
1574
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
1575
+ } catch {}
1576
+ }
1577
+ return code;
1578
+ }
1579
+ function commandPath(scope, argv) {
1580
+ const path = [];
1581
+ let level = scope;
1582
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
1583
+ const command = lookup(level, word);
1584
+ if (command === undefined)
1585
+ break;
1586
+ path.push(word);
1587
+ if (!("commands" in command))
1588
+ break;
1589
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
1308
1590
  }
1591
+ return path.length === 0 ? undefined : path.join(" ");
1309
1592
  }
1310
1593
 
1594
+ // ../kit/src/index.ts
1595
+ init_config();
1596
+
1597
+ // ../kit/src/excerpt.ts
1598
+ init_text2();
1599
+
1600
+ // ../kit/src/index.ts
1601
+ init_folders();
1602
+ init_format();
1603
+
1604
+ // ../kit/src/git.ts
1605
+ init_args();
1606
+ // ../kit/src/limit.ts
1607
+ init_args();
1608
+
1609
+ // ../kit/src/index.ts
1610
+ init_mode();
1611
+
1612
+ // ../kit/src/report.ts
1613
+ init_style();
1614
+ init_text2();
1615
+ // ../kit/src/secrets.ts
1616
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1617
+ var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
1618
+ // ../kit/src/sessions.ts
1619
+ var {Glob } = globalThis.Bun;
1620
+ var SESSION_FILES = new Glob("*.json");
1621
+ var ACCOUNT_DIRS = new Glob("*/sessions");
1622
+
1623
+ // ../kit/src/index.ts
1624
+ init_style();
1625
+ init_text2();
1626
+ init_theme();
1627
+ init_user_config();
1628
+
1629
+ // ../kit/src/watch.ts
1630
+ init_args();
1631
+ init_input();
1632
+ init_style();
1633
+ // ../kit/src/workspace-root.ts
1634
+ init_user_config();
1635
+ // src/cli.ts
1636
+ init_prompt();
1637
+
1311
1638
  // src/encode.ts
1312
1639
  function b64Encode(bytes, url = false) {
1313
1640
  return Buffer.from(bytes).toString(url ? "base64url" : "base64");
@@ -1364,6 +1691,38 @@ function ulid(now = Date.now(), random = randomBytes(16)) {
1364
1691
  function uuidV4() {
1365
1692
  return crypto.randomUUID();
1366
1693
  }
1694
+ function nextUlid(id) {
1695
+ const digits = [...id];
1696
+ for (let i = digits.length - 1;i >= 0; i--) {
1697
+ const value = CROCKFORD.indexOf(digits[i]) + 1;
1698
+ digits[i] = CROCKFORD[value % 32];
1699
+ if (value < 32)
1700
+ break;
1701
+ }
1702
+ return digits.join("");
1703
+ }
1704
+ function nextUuidV7(id) {
1705
+ const bits = BigInt(`0x${id.replaceAll("-", "")}`);
1706
+ const time = bits >> 80n;
1707
+ const random = (bits >> 64n & 0xFFFn) << 62n | bits & (1n << 62n) - 1n;
1708
+ const next = (time << 74n | random) + 1n;
1709
+ const nextTime = next >> 74n;
1710
+ const nextA = next >> 62n & 0xFFFn;
1711
+ const nextB = next & (1n << 62n) - 1n;
1712
+ const hex = (nextTime << 80n | 0x7n << 76n | nextA << 64n | 0x2n << 62n | nextB).toString(16).padStart(32, "0");
1713
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1714
+ }
1715
+ function monotonic(count, draw, successor, clock = Date.now) {
1716
+ const ids = [];
1717
+ let last = Number.NEGATIVE_INFINITY;
1718
+ for (let i = 0;i < count; i++) {
1719
+ const now = clock();
1720
+ const previous = ids.at(-1);
1721
+ ids.push(previous !== undefined && now <= last ? successor(previous) : draw(now));
1722
+ last = Math.max(last, now);
1723
+ }
1724
+ return ids;
1725
+ }
1367
1726
 
1368
1727
  // src/ip.ts
1369
1728
  var IP_SERVICE = "https://ipecho.net/plain";
@@ -1426,10 +1785,11 @@ var ZONELESS = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\
1426
1785
  var DATE_SPACE = /^(\d{4}-\d{2}-\d{2}) /;
1427
1786
  var WHITESPACE2 = /\s+/g;
1428
1787
  var ZONED = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?\s*(?:Z|[+-]\d{2}(?::?\d{2})?)$/i;
1788
+ var HOUR_OFFSET = /([+-]\d{2})$/;
1429
1789
  function parseDate(text, timeZone) {
1430
1790
  const match = ZONELESS.exec(text);
1431
1791
  if (match === null) {
1432
- const ms = ZONED.test(text) ? Date.parse(text.replace(DATE_SPACE, "$1T").replace(WHITESPACE2, "")) : Number.NaN;
1792
+ const ms = ZONED.test(text) ? Date.parse(text.replace(DATE_SPACE, "$1T").replace(WHITESPACE2, "").replace(HOUR_OFFSET, "$1:00")) : Number.NaN;
1433
1793
  return Number.isNaN(ms) ? undefined : ms;
1434
1794
  }
1435
1795
  const [, year, month, day, hour = "0", minute = "0", second = "0", fraction = "0"] = match;
@@ -1465,7 +1825,11 @@ function decodeJwt(token) {
1465
1825
  function claimTimes(payload, now = Date.now(), timeZone) {
1466
1826
  return TIME_CLAIMS.flatMap((claim) => {
1467
1827
  const epoch = payload[claim];
1468
- return typeof epoch === "number" && Number.isFinite(epoch) ? [{ claim, epoch, ...zoned(epoch * 1000, timeZone), relative: relative(epoch * 1000, now) }] : [];
1828
+ if (typeof epoch !== "number" || !Number.isFinite(epoch))
1829
+ return [];
1830
+ if (Number.isNaN(new Date(epoch * 1000).getTime()))
1831
+ return [{ claim, epoch, local: "out of range", utc: "", relative: "" }];
1832
+ return [{ claim, epoch, ...zoned(epoch * 1000, timeZone), relative: relative(epoch * 1000, now) }];
1469
1833
  });
1470
1834
  }
1471
1835
 
@@ -1476,6 +1840,7 @@ function generatePassword(length, format, random = (bytes) => crypto.getRandomVa
1476
1840
  const buffer = Buffer.from(random(new Uint8Array(length)));
1477
1841
  return buffer.toString(format);
1478
1842
  }
1843
+ var BCRYPT_MAX_BYTES = 72;
1479
1844
  async function bcryptHash(password) {
1480
1845
  const hash = await Bun.password.hash(password, { algorithm: "bcrypt", cost: 10 });
1481
1846
  return `$2y$${hash.slice("$2b$".length)}`;
@@ -1486,7 +1851,7 @@ var NUMBER = /^-?\d+(?:\.\d+)?$/;
1486
1851
  var MILLISECONDS_FROM = 100000000000;
1487
1852
  function instant(kind, ms, now, timeZone) {
1488
1853
  if (Number.isNaN(new Date(ms).getTime()))
1489
- throw new Error("the date is out of range");
1854
+ throw new RangeError("the date is out of range");
1490
1855
  return { kind, ...zoned(ms, timeZone), ms, seconds: Math.floor(ms / 1000), relative: relative(ms, now) };
1491
1856
  }
1492
1857
  function convert(value, { now = Date.now(), timeZone } = {}) {
@@ -1577,18 +1942,18 @@ async function bytesInput(argument, what) {
1577
1942
  return new Uint8Array(await Bun.stdin.arrayBuffer());
1578
1943
  }
1579
1944
  function printRows(rows) {
1580
- const { cyan } = paint(process15.stdout);
1945
+ const { cyan } = paint(process16.stdout);
1581
1946
  const width = Math.max(...rows.map(([label]) => label.length));
1582
1947
  for (const [label, value] of rows)
1583
1948
  console.log(`${cyan(label.padEnd(width))} ${value}`);
1584
1949
  }
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
1950
+ var PASSWORD_USAGE = `dev password [length] [format] [-b|--bcrypt [password]] [--copy]: a random password of <length> bytes (default ${DEFAULT_LENGTH}) as hex, base64 (default) or base64url
1586
1951
 
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.`;
1952
+ Printed on stdout, and copied with --copy. With --bcrypt the bcrypt hash (cost 10) prints, of the password given (- asks for it masked on a terminal, or reads stdin, keeping it out of the shell history) or of a generated one, which prints on stderr and is the one --copy copies. The hash has the $2y$ prefix htpasswd -B writes; a password over 72 bytes, all bcrypt reads, is refused.`;
1588
1953
  var PASSWORD_EXITS = [[0, "it printed the password or hash"], [2, "a usage error"], [130, "the prompt was cancelled"]];
1589
1954
  var PASSWORD_OPTIONS = {
1590
1955
  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" },
1591
- "no-copy": { type: "boolean", description: "leave the clipboard alone" },
1956
+ copy: copyOption("the password, or the hash of a password given"),
1592
1957
  json: jsonOption("{password?, hash?, format, bytes, copied}")
1593
1958
  };
1594
1959
  var FORMAT_NOTES = { hex: "hexadecimal", base64: "base64", base64url: "url-safe base64" };
@@ -1607,14 +1972,16 @@ async function password(args) {
1607
1972
  const bcrypt = values.bcrypt === "" ? undefined : values.bcrypt;
1608
1973
  const given = bcrypt === "-" ? await secretInput("the password") : bcrypt;
1609
1974
  const secret = given ?? generatePassword(bytes, format);
1975
+ if (values.bcrypt !== undefined && Buffer.byteLength(secret) > BCRYPT_MAX_BYTES)
1976
+ badUsage(`bcrypt takes a password of at most ${BCRYPT_MAX_BYTES} bytes, this one has ${Buffer.byteLength(secret)}${given === undefined ? `: ${bytes} bytes as ${format} is too long, pick a smaller <length>` : ""}`);
1610
1977
  const hash = values.bcrypt === undefined ? undefined : await bcryptHash(secret);
1611
- const copied = values["no-copy"] === true ? false : await copyText(given === undefined ? secret : hash ?? secret);
1978
+ const copied = values.copy === true && await copyText(given === undefined ? secret : hash ?? secret);
1612
1979
  if (values.json === true) {
1613
1980
  printJson({ ...hash === undefined ? {} : { hash }, ...given === undefined ? { password: secret } : {}, format, bytes, copied });
1614
1981
  return 0;
1615
1982
  }
1616
1983
  if (copied)
1617
- console.error(paint(process15.stderr).dim("copied to clipboard"));
1984
+ console.error(paint(process16.stderr).dim("copied to clipboard"));
1618
1985
  if (hash !== undefined && given === undefined)
1619
1986
  console.error(secret);
1620
1987
  console.log(hash ?? secret);
@@ -1643,7 +2010,7 @@ async function jwt(args) {
1643
2010
  printJson({ header: decoded.header, payload: decoded.payload, claims, signatureBytes: decoded.signatureBytes });
1644
2011
  return 0;
1645
2012
  }
1646
- const { bold } = paint(process15.stdout);
2013
+ const { bold } = paint(process16.stdout);
1647
2014
  console.log(`${bold("header")}
1648
2015
  ${JSON.stringify(decoded.header, null, 2)}
1649
2016
 
@@ -1651,7 +2018,7 @@ ${bold("payload")}
1651
2018
  ${JSON.stringify(decoded.payload, null, 2)}`);
1652
2019
  if (claims.length > 0) {
1653
2020
  console.log("");
1654
- printRows(claims.map(({ claim, local, utc, relative }) => [claim, `${local} ${utc} ${relative}`]));
2021
+ printRows(claims.map(({ claim, local, utc, relative }) => [claim, [local, utc, relative].filter(Boolean).join(" ")]));
1655
2022
  }
1656
2023
  return 0;
1657
2024
  }
@@ -1694,7 +2061,8 @@ function uuid(args) {
1694
2061
  replaces: 'uuidgen and python -c "import uuid"',
1695
2062
  examples: ["dev uuid", ["dev uuid -n 5 --v7", "five time-ordered UUIDs"]]
1696
2063
  });
1697
- const ids = Array.from({ length: wholeNumber(values.n, "n", 1) }, () => values.v7 === true ? uuidV7() : uuidV4());
2064
+ const count = wholeNumber(values.n, "n", 1);
2065
+ const ids = values.v7 === true ? monotonic(count, (now) => uuidV7(now), nextUuidV7) : Array.from({ length: count }, uuidV4);
1698
2066
  printIds(ids, values.json === true);
1699
2067
  return 0;
1700
2068
  }
@@ -1707,7 +2075,7 @@ function ulidCommand(args) {
1707
2075
  replaces: "installing a ulid package to mint one",
1708
2076
  examples: ["dev ulid", ["dev ulid -n 3", "three ULIDs"]]
1709
2077
  });
1710
- printIds(Array.from({ length: wholeNumber(values.n, "n", 1) }, () => ulid()), values.json === true);
2078
+ printIds(monotonic(wholeNumber(values.n, "n", 1), (now) => ulid(now), nextUlid), values.json === true);
1711
2079
  return 0;
1712
2080
  }
1713
2081
  function printIds(ids, json) {
@@ -1829,13 +2197,13 @@ async function ip(args) {
1829
2197
  }
1830
2198
  }
1831
2199
  if (import.meta.main) {
1832
- process15.exitCode = await runCli({
2200
+ process16.exitCode = await runCli({
1833
2201
  name: "dev",
1834
2202
  about: "small developer utilities: passwords and bcrypt hashes, JWTs, timestamps, UUIDs, base64, URLs and file hashes",
1835
2203
  replaces: "openssl rand, htpasswd, jwt.io, date -d, uuidgen, base64, sha256sum and one-off scripts for each",
1836
2204
  examples: ["dev password", ["dev jwt <token>", "header, payload and expiry"], ["dev ts 1700000000", "an epoch as dates"]],
1837
2205
  commands: {
1838
- password: { summary: "a random password, copied to the clipboard, or its bcrypt hash", run: password },
2206
+ password: { summary: "a random password, or its bcrypt hash", run: password },
1839
2207
  jwt: { summary: "decode a JWT without verifying it, expiry shown as dates", run: jwt },
1840
2208
  ts: { summary: "convert epochs, ISO dates and durations, local and UTC", run: ts },
1841
2209
  uuid: { summary: "random UUIDs, v4 or v7", run: async (args) => Promise.resolve(uuid(args)) },