@kaynooo/cli-dev 0.6.1 → 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 +1201 -912
  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", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
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,912 +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/completions.ts
538
- var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
539
- var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
540
- set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
541
- set -l current (commandline -ct)
542
- for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
543
- if test "$line" = __files__
544
- __fish_complete_path $current
545
- else
546
- echo $line
547
- end
548
- end
549
- end`;
550
- var BASH_FUNCTION = `__kaynooo_cli_complete() {
551
- local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
552
- local -a lines
553
- COMPREPLY=()
554
- lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
555
- for line in "\${lines[@]}"; do
556
- if [[ $line == __files__ ]]; then
557
- COMPREPLY+=($(compgen -f -- "$cur"))
558
- else
559
- words+="\${line%%$'\\t'*}"$'\\n'
560
- fi
561
- done
562
- COMPREPLY+=($(compgen -W "$words" -- "$cur"))
563
- }`;
564
- var ZSH_FUNCTION = `__kaynooo_cli_complete() {
565
- local line
566
- local -a described plain
567
- for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
568
- if [[ $line == __files__ ]]; then
569
- _files
570
- elif [[ $line == *$'\\t'* ]]; then
571
- described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
572
- else
573
- plain+=("$line")
574
- fi
575
- done
576
- (( \${#described} )) && _describe -V value described
577
- (( \${#plain} )) && compadd -- "\${plain[@]}"
578
- return 0
579
- }`;
580
- function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
581
- if (shell === "fish")
582
- return `${header}
583
- ${FISH_FUNCTION}
584
- ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
585
- `).join("")}`;
586
- if (shell === "bash")
587
- return `${header}
588
- ${BASH_FUNCTION}
589
- complete -F __kaynooo_cli_complete ${bins.join(" ")}
590
- `;
591
- return `${header}
592
- ${ZSH_FUNCTION}
593
- compdef __kaynooo_cli_complete ${bins.join(" ")}
594
- `;
629
+ // ../kit/src/job.ts
630
+ import process14 from "process";
631
+ function stopJob() {
632
+ process14.kill(0, "SIGTSTP");
595
633
  }
634
+ var init_job = () => {};
596
635
 
597
- // ../kit/src/notify.ts
598
- import process8 from "process";
599
- var NOTIFY_AFTER_MS = 1e4;
600
- var CANCELLED = 130;
601
- function base64(text) {
602
- return Buffer.from(text).toString("base64");
636
+ // ../kit/src/picker/line.ts
637
+ function isEditKey(key) {
638
+ return EDIT_KEYS.has(key);
603
639
  }
604
- function notification(title, body, env = process8.env) {
605
- const id = `kit${process8.pid}`;
606
- const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
607
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
640
+ function endsKills(key) {
641
+ return typeof key !== "object" && !isEditKey(key);
608
642
  }
609
- function notifyEnd(command, code, ms, { stream = process8.stderr, env = process8.env } = {}) {
610
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
611
- return;
612
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
643
+ function isWord(char) {
644
+ return char !== undefined && WORD_CHARACTER.test(char);
613
645
  }
614
-
615
- // ../kit/src/usage.ts
616
- import { appendFileSync, mkdirSync } from "fs";
617
- import { homedir } from "os";
618
- import { dirname, isAbsolute, join } from "path";
619
- import process9 from "process";
620
-
621
- // ../kit/src/logs.ts
622
- var DAY_MS = 24 * 60 * 60 * 1000;
623
- var CLI_FOLDER = "kaynooo-cli";
624
-
625
- // ../kit/src/usage.ts
626
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
627
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
628
- var LONGEST_NAME = 40;
629
- var usageError;
630
- function noteUsageError(message) {
631
- usageError = message;
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;
632
653
  }
633
- function stateHome(env = process9.env) {
634
- const dir = env.XDG_STATE_HOME;
635
- return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
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;
636
661
  }
637
- function usagePath(env = process9.env) {
638
- return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
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;
639
669
  }
640
- function usageRecorded(env = process9.env) {
641
- const off = env.KAYNOOO_CLI_NO_USAGE;
642
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
670
+ function cut(chars, from, to) {
671
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
643
672
  }
644
- function flagNames(argv) {
645
- const end = argv.indexOf("--");
646
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
647
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
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 };
648
676
  }
649
- function usageEntry(bin, command, argv, code, now = new Date) {
650
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
651
- usageError = undefined;
652
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
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 };
653
690
  }
654
- function recordUsage(entry, env = process9.env) {
655
- if (!usageRecorded(env))
656
- return;
657
- try {
658
- const path = usagePath(env);
659
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
660
- appendFileSync(path, `${JSON.stringify(entry)}
661
- `, { mode: 384 });
662
- } catch {}
663
- }
664
-
665
- // ../kit/src/cli.ts
666
- var LEVEL_OPTIONS = {
667
- ...OUTPUT_OPTIONS,
668
- help: { type: "boolean", short: "h", description: "show this help" }
669
- };
670
- var TOP_OPTIONS = {
671
- ...LEVEL_OPTIONS,
672
- version: { type: "boolean", short: "v", description: "print the version" },
673
- completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
674
- };
675
- async function commandRows(all, colors) {
676
- const commands = shown(all);
677
- const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
678
- const groups = new Map([["Commands:", []]]);
679
- const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
680
- for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
681
- const heading = group === undefined ? "Commands:" : `${group}:`;
682
- const rows = groups.get(heading) ?? [];
683
- rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
684
- groups.set(heading, rows);
685
- }
686
- return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
687
- }
688
- function shown(commands) {
689
- return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
690
- }
691
- function takeOutputFlags(argv) {
692
- let index = 0;
693
- for (;index < argv.length; index++) {
694
- const word = argv[index];
695
- if (word === "--plain")
696
- applyOutput(undefined, true);
697
- else if (word.startsWith("--color="))
698
- applyOutput(word.slice("--color=".length), undefined);
699
- else if (word === "--color" && argv[index + 1] !== undefined)
700
- applyOutput(argv[++index], undefined);
701
- else
702
- break;
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);
703
724
  }
704
- return argv.slice(index);
705
725
  }
706
- async function resolveSummary(summary) {
707
- return typeof summary === "string" ? summary : summary();
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) };
708
742
  }
709
- function scopeOf(commands, extra, aliases) {
710
- return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
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);
711
762
  }
712
- async function expand(scope, words) {
713
- if (scope.lazy.length === 0)
714
- return scope;
715
- const commands = { ...scope.commands };
716
- for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
717
- for (const [name, command] of Object.entries(added))
718
- commands[name] ??= command;
719
- }
720
- return { ...scope, commands, lazy: [] };
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
+ });
721
782
  }
722
- async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
723
- const colors = paint(stream);
724
- const prefix = path.join(" ");
725
- const summary = await resolveSummary(lazySummary);
726
- if (wantsHelpJson())
727
- return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
728
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
729
- const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
730
- const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
731
- return [
732
- header(colors, summary),
733
- "",
734
- usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
735
- "",
736
- ...await commandRows(commands, colors),
737
- ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
738
- "",
739
- colors.bold("Options:"),
740
- ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
741
- ...exampleRows(examples ?? [], colors),
742
- "",
743
- `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
744
- ].join(`
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(`
745
843
  `);
746
844
  }
747
- function printError(prefix, message, hint, cause) {
748
- const colors = paint(process10.stderr);
749
- const styled = takesControlCodes(process10.stderr);
750
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
751
- const under = (label, text, tint) => text === undefined ? "" : `
752
- ${styled ? tint(label) : `${label}:`} ${text}`;
753
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
845
+ function rowsTaken(lines, columns) {
846
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
754
847
  }
755
- function printJsonError(message, hint, cause) {
756
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
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));
757
857
  }
758
- function wantsJson(argv) {
759
- const end = argv.indexOf("--");
760
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
858
+ function roomAfter(question, columns) {
859
+ return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
761
860
  }
762
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
763
- if (error instanceof HelpShown)
764
- return 0;
765
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
766
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
767
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
768
- if (error instanceof Exit && error.code === 2)
769
- noteUsageError(error.message);
770
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
771
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
772
- return error instanceof Exit ? error.code : 1;
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)}`;
773
865
  }
774
- async function dispatch(level, typed, { version, redact }) {
775
- const prefix = level.path.join(" ");
776
- let argv;
777
- try {
778
- argv = takeOutputFlags(typed);
779
- } catch (error) {
780
- return reportThrown(prefix, error);
781
- }
782
- const [name, ...args] = argv;
783
- const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
784
- if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
785
- try {
786
- return await fallback.run([]);
787
- } catch (error) {
788
- return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
789
- }
790
- }
791
- if (name === undefined && level.path.length > 1) {
792
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stderr));
793
- return 2;
794
- }
795
- if (name === undefined || name === "help" || name === "--help" || name === "-h") {
796
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process10.stdout));
797
- return 0;
798
- }
799
- if (level.path.length === 1 && (name === "--version" || name === "-v")) {
800
- console.log(version);
801
- return 0;
802
- }
803
- let command = level.commands[level.aliases?.[name] ?? name];
804
- let rest = args;
805
- let ran = name;
806
- if (command === undefined && level.lazy.length > 0) {
807
- level = await expand(level, [...level.path.slice(1), ...argv]);
808
- command = level.commands[level.aliases?.[name] ?? name];
809
- }
810
- if (command === undefined && level.defaultCommand !== undefined) {
811
- command = level.commands[level.defaultCommand];
812
- rest = argv;
813
- ran = level.defaultCommand;
814
- }
815
- if (command === undefined) {
816
- const meant = closest(name, Object.keys(shown(level.commands)));
817
- printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
818
- return 2;
819
- }
820
- if ("commands" in command) {
821
- const { summary } = command;
822
- 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 });
823
- }
824
- try {
825
- return await command.run(rest);
826
- } catch (error) {
827
- return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
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);
828
872
  }
873
+ return first.slice(0, length).join("");
829
874
  }
830
- var COMPLETE = "__complete";
831
- var FILES = "__files__";
832
- async function completingOf(run) {
833
- completion.active = true;
834
- try {
835
- await run([]);
836
- } catch (error) {
837
- if (error instanceof Completing)
838
- return error;
839
- } finally {
840
- completion.active = false;
841
- }
842
- return new Completing({});
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)))}`;
843
881
  }
844
- async function optionsOf(run) {
845
- return (await completingOf(run)).options;
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;
914
+ }
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();
846
938
  }
847
- function candidateLine(candidate) {
848
- return typeof candidate === "string" ? candidate : candidate.join("\t");
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")}`;
849
941
  }
850
- function positionalBeingTyped(before, { options, positionals }) {
851
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
852
- const typed = [];
853
- let at = 0;
854
- while (at < before.length) {
855
- const word = before[at];
856
- if (word === "--") {
857
- typed.push(...before.slice(at + 1));
858
- break;
859
- }
860
- if (!word.startsWith("-"))
861
- typed.push(word);
862
- else if (takesValue(word))
863
- at++;
864
- at++;
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();
865
1008
  }
866
- const last = positionals.at(-1);
867
- if (typed.length < positionals.length)
868
- return { name: positionals[typed.length], typed };
869
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
870
1009
  }
871
- async function leafCandidates(run, words) {
872
- const completing = await completingOf(run);
873
- if ((words.at(-1) ?? "").startsWith("-"))
874
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
875
- const flag = words.at(-2);
876
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
877
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
878
- if (option?.type === "string") {
879
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
880
- return values === undefined ? [FILES] : values.map(candidateLine);
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;
881
1039
  }
882
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
883
- return values === undefined ? [FILES] : values.map(candidateLine);
884
1040
  }
885
- async function candidates(scope, defaultCommand, words, before = []) {
886
- const [word = "", ...rest] = words;
887
- const listing = rest.length === 0 && !word.startsWith("-");
888
- let { commands, aliases } = scope;
889
- let command = commands[aliases?.[word] ?? word];
890
- if (listing || command === undefined) {
891
- ({ commands, aliases } = await expand(scope, [...before, ...words]));
892
- command = commands[aliases?.[word] ?? word];
893
- }
894
- if (listing) {
895
- const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
896
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
897
- const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
898
- const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
899
- return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
900
- }
901
- if (command === undefined) {
902
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
903
- return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
1041
+ function realPath(word) {
1042
+ try {
1043
+ return realpathSync(resolve(word));
1044
+ } catch {
1045
+ return;
904
1046
  }
905
- return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
906
1047
  }
907
- var COMPLETIONS = "--completions";
908
- function flagValue([flag = "", ...rest]) {
909
- return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
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;
910
1053
  }
911
- function printCompletionScript(name, args) {
912
- const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
913
- if (shell === undefined || args.length !== 1) {
914
- printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
915
- return 2;
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;
916
1074
  }
917
- console.log(completionScript(shell, [name]).trimEnd());
918
- return 0;
919
- }
920
- async function printCandidates(found) {
921
- for (const line of await found)
922
- console.log(line);
923
- return 0;
1075
+ return false;
924
1076
  }
925
- function packageVersion(entry = Bun.main) {
926
- let resolved = entry;
1077
+ async function pipeInto(argv, text) {
927
1078
  try {
928
- resolved = realpathSync2(entry);
929
- } catch {}
930
- for (let dir = dirname2(resolved);; dir = dirname2(dir)) {
931
- try {
932
- const { version } = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
933
- if (typeof version === "string")
934
- return version;
935
- } catch {}
936
- if (dirname2(dir) === dir)
937
- return "0.0.0";
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;
938
1083
  }
939
1084
  }
940
- async function runCli(cli, argv = scriptArgs()) {
941
- const version = cli.version ?? packageVersion();
942
- if (argv[0] === COMPLETE)
943
- return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
944
- if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
945
- return printCompletionScript(cli.name, flagValue(argv));
946
- const started = performance.now();
947
- const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
948
- const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
949
- notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
950
- if (cli.usage !== false) {
951
- try {
952
- recordUsage(usageEntry(cli.name, command, argv, code));
953
- } catch {}
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";
1103
+ import process11 from "process";
1104
+
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 = "";
1115
+ try {
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
+ });
1128
+ } catch {
1129
+ return 1;
954
1130
  }
955
- return code;
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;
956
1142
  }
957
- function commandPath(scope, argv) {
958
- const path = [];
959
- let level = scope;
960
- for (const word of argv.filter((each) => !each.startsWith("-"))) {
961
- const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
962
- const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
963
- if (command === undefined)
964
- break;
965
- path.push(word);
966
- if (!("commands" in command))
967
- break;
968
- level = scopeOf(command.commands, command.extraCommands, command.aliases);
969
- }
970
- return path.length === 0 ? undefined : path.join(" ");
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
+ `;
971
1202
  }
972
- // ../kit/src/folders.ts
973
- import { homedir as homedir2 } from "os";
974
- import { join as join3 } from "path";
975
- import process11 from "process";
976
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
977
- function cacheFolder({ home = homedir2(), env = process11.env } = {}) {
978
- return env.XDG_CACHE_HOME ?? join3(home, ".cache");
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));
979
1222
  }
980
- // ../kit/src/secrets.ts
981
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
982
- // ../kit/src/sessions.ts
983
- var {Glob } = globalThis.Bun;
984
- var SESSION_FILES = new Glob("*.json");
985
- var ACCOUNT_DIRS = new Glob("*/sessions");
986
- // ../kit/src/prompt.ts
987
- import process14 from "process";
988
1223
 
989
- // ../kit/src/answers.ts
990
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
991
- import { dirname as dirname3, join as join4 } from "path";
992
- var KEPT = 50;
993
- function answersFile() {
994
- return join4(cacheFolder(), "kaynooo-cli", "answers.json");
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;
995
1247
  }
996
- function stored() {
997
- try {
998
- const parsed = JSON.parse(readFileSync3(answersFile(), "utf-8"));
999
- if (typeof parsed !== "object" || parsed === null)
1000
- return {};
1001
- return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
1002
- } catch {
1003
- return {};
1004
- }
1248
+ function stateHome(env = process10.env) {
1249
+ return xdgFolder(env.XDG_STATE_HOME, join2(homedir(), ".local", "state"));
1005
1250
  }
1006
- function earlierAnswers(key) {
1007
- return stored()[key] ?? [];
1251
+ function usagePath(env = process10.env) {
1252
+ return join2(stateHome(env), CLI_FOLDER, "usage.jsonl");
1008
1253
  }
1009
- function rememberAnswer(key, answer) {
1010
- const all = stored();
1011
- const file = answersFile();
1012
- all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
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;
1013
1271
  try {
1014
- mkdirSync2(dirname3(file), { recursive: true });
1015
- writeFileSync(file, JSON.stringify(all));
1272
+ const path = usagePath(env);
1273
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
1274
+ appendFileSync(path, `${JSON.stringify(entry)}
1275
+ `, { mode: 384 });
1016
1276
  } catch {}
1017
1277
  }
1018
1278
 
1019
- // ../kit/src/job.ts
1020
- import process13 from "process";
1021
- function stopJob() {
1022
- process13.kill(0, "SIGTSTP");
1023
- }
1024
-
1025
- // ../kit/src/picker/line.ts
1026
- var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
1027
- var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
1028
- var FORWARD_KILLS = new Set(["killnext", "killend"]);
1029
- function isEditKey(key) {
1030
- return EDIT_KEYS.has(key);
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]);
1031
1301
  }
1032
- function endsKills(key) {
1033
- return typeof key !== "object" && !isEditKey(key);
1302
+ function shown(commands) {
1303
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
1034
1304
  }
1035
- var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
1036
- var SPACE = /\s/;
1037
- function isWord(char) {
1038
- return char !== undefined && WORD_CHARACTER.test(char);
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);
1039
1319
  }
1040
- function wordStart(chars, from) {
1041
- let at = from;
1042
- while (at > 0 && !isWord(chars[at - 1]))
1043
- at--;
1044
- while (at > 0 && isWord(chars[at - 1]))
1045
- at--;
1046
- return at;
1320
+ async function resolveSummary(summary) {
1321
+ return typeof summary === "string" ? summary : summary();
1047
1322
  }
1048
- function wordEnd(chars, from) {
1049
- let at = from;
1050
- while (at < chars.length && !isWord(chars[at]))
1051
- at++;
1052
- while (at < chars.length && isWord(chars[at]))
1053
- at++;
1054
- return at;
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;
1055
1326
  }
1056
- function spacedStart(chars, from) {
1057
- let at = from;
1058
- while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
1059
- at--;
1060
- while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
1061
- at--;
1062
- return at;
1327
+ function scopeOf(commands, extra, aliases) {
1328
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
1063
1329
  }
1064
- function cut(chars, from, to) {
1065
- 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: [] };
1066
1339
  }
1067
- function insert(chars, at, text) {
1068
- const typed = [...text];
1069
- return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
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
+ `);
1070
1364
  }
1071
- function editLine(line, key) {
1072
- const { killed = "", chained = false } = line;
1073
- const chars = [...line.text];
1074
- const at = Math.min(Math.max(line.caret, 0), chars.length);
1075
- const edited = edit(chars, at, key, killed);
1076
- if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
1077
- return line.killed === undefined ? edited : { ...edited, killed };
1078
- const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
1079
- if (taken === "")
1080
- return { ...edited, killed, chained };
1081
- if (!chained)
1082
- return { ...edited, killed: taken, chained: true };
1083
- return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
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)}`);
1084
1372
  }
1085
- function edit(chars, at, key, killed) {
1086
- const text = chars.join("");
1087
- if (typeof key === "object")
1088
- return insert(chars, at, key.text);
1089
- switch (key) {
1090
- case "left":
1091
- return { text, caret: Math.max(at - 1, 0) };
1092
- case "right":
1093
- return { text, caret: Math.min(at + 1, chars.length) };
1094
- case "wordleft":
1095
- return { text, caret: wordStart(chars, at) };
1096
- case "wordright":
1097
- return { text, caret: wordEnd(chars, at) };
1098
- case "linestart":
1099
- return { text, caret: 0 };
1100
- case "lineend":
1101
- return { text, caret: chars.length };
1102
- case "erase":
1103
- return cut(chars, Math.max(at - 1, 0), at);
1104
- case "delete":
1105
- return cut(chars, at, Math.min(at + 1, chars.length));
1106
- case "word":
1107
- return cut(chars, spacedStart(chars, at), at);
1108
- case "killword":
1109
- return cut(chars, wordStart(chars, at), at);
1110
- case "killnext":
1111
- return cut(chars, at, wordEnd(chars, at));
1112
- case "clear":
1113
- return cut(chars, 0, at);
1114
- case "killend":
1115
- return cut(chars, at, chars.length);
1116
- case "yank":
1117
- return insert(chars, at, killed);
1118
- }
1373
+ function printJsonError(message, hint, cause) {
1374
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1119
1375
  }
1120
- function visible({ text, caret }, room) {
1121
- const chars = [...text];
1122
- const at = Math.min(Math.max(caret, 0), chars.length);
1123
- const cells = at === chars.length ? [...chars, " "] : chars;
1124
- const widths = cells.map((char) => Bun.stringWidth(char));
1125
- const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
1126
- const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
1127
- let start = at;
1128
- let end = at + 1;
1129
- while (start > 0 && fits(start - 1, end))
1130
- start--;
1131
- while (end < cells.length && fits(start, end + 1))
1132
- end++;
1133
- const left = start > 0 ? "\u2026" : "";
1134
- const right = end < cells.length ? "\u2026" : "";
1135
- return { before: left + chars.slice(start, at).join(""), at: chars[at], after: chars.slice(at + 1, end).join("") + right, column: left.length + width(start, at) };
1376
+ function wantsJson(argv) {
1377
+ const end = argv.indexOf("--");
1378
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1136
1379
  }
1137
-
1138
- // ../kit/src/picker/score.ts
1139
- var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1140
- var NONE = Number.NEGATIVE_INFINITY;
1141
-
1142
- // ../kit/src/picker/state.ts
1143
- var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1144
- var PASTE_START = "\x1B[200~";
1145
- var PASTE_END = "\x1B[201~";
1146
- var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1147
- var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1148
- var WHEEL_LINES = 3;
1149
- var KEYS = {
1150
- "\x1B[A": "up",
1151
- "\x1BOA": "up",
1152
- "\x10": "up",
1153
- "\x1B[B": "down",
1154
- "\x1BOB": "down",
1155
- "\x0E": "down",
1156
- "\x1B[5~": "pageup",
1157
- "\x1B[6~": "pagedown",
1158
- "\x1B[H": "home",
1159
- "\x1B[1~": "home",
1160
- "\x1BOH": "home",
1161
- "\x1B[F": "end",
1162
- "\x1B[4~": "end",
1163
- "\x1BOF": "end",
1164
- "\r": "enter",
1165
- "\n": "enter",
1166
- "\x03": "cancel",
1167
- "\x1B": "cancel",
1168
- "\x1B[D": "left",
1169
- "\x1BOD": "left",
1170
- "\x1B[C": "right",
1171
- "\x1BOC": "right",
1172
- "\x1B[1;5D": "wordleft",
1173
- "\x1B[1;3D": "wordleft",
1174
- "\x1Bb": "wordleft",
1175
- "\x1B[1;5C": "wordright",
1176
- "\x1B[1;3C": "wordright",
1177
- "\x1Bf": "wordright",
1178
- "\x01": "linestart",
1179
- "\x05": "lineend",
1180
- "\x7F": "erase",
1181
- "\x1B[3~": "delete",
1182
- "\b": "killword",
1183
- "\x1B\x7F": "killword",
1184
- "\x1B[3;5~": "killnext",
1185
- "\x1Bd": "killnext",
1186
- "\x15": "clear",
1187
- "\v": "killend",
1188
- "\x17": "word",
1189
- "\x19": "yank",
1190
- "\x1A": "suspend",
1191
- "\t": "tab",
1192
- "\x1F": "help",
1193
- "\x1BOP": "help",
1194
- "\x1B[11~": "help"
1195
- };
1196
- function repeat(value, count) {
1197
- return Array.from({ length: count }).fill(value);
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;
1198
1391
  }
1199
- function parseKeys(input, paste = { active: false }, ctrls = []) {
1200
- const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1201
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1202
- const wheel = MOUSE.exec(sequence)?.[1];
1203
- if (wheel !== undefined)
1204
- return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1205
- const named = codes.get(sequence);
1206
- const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1207
- if (sequence === PASTE_START || sequence === PASTE_END) {
1208
- paste.active = sequence === PASTE_START;
1209
- return [];
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);
1210
1407
  }
1211
- if (paste.active && (sequence === "\r" || sequence === `
1212
- `))
1213
- return [];
1214
- if (key !== undefined)
1215
- return [key];
1216
- return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1217
- });
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
+ }
1218
1447
  }
1219
-
1220
- // ../kit/src/redraw.ts
1221
- var SYNC_START = "\x1B[?2026h";
1222
- var SYNC_END = "\x1B[?2026l";
1223
- function overwrite(lines, columns) {
1224
- return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1225
- `);
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({});
1226
1461
  }
1227
- function rowsTaken(lines, columns) {
1228
- 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;
1464
+ }
1465
+ function candidateLine(candidate) {
1466
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
1467
+ }
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 };
1229
1488
  }
1230
-
1231
- // ../kit/src/prompt.ts
1232
- var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
1233
- var MAX_LISTED = 12;
1234
- function readKeys(input, paste = { active: false }) {
1235
- return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
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);
1236
1502
  }
1237
- function roomAfter(question, columns) {
1238
- return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
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);
1512
+ }
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);
1239
1525
  }
1240
- function withCaret(colors, line, room, dim = false) {
1241
- const { before, at, after } = visible(line, room);
1242
- const tone = dim ? colors.dim : (text) => text;
1243
- return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
1526
+ var COMPLETIONS = "--completions";
1527
+ function flagValue([flag = "", ...rest]) {
1528
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1244
1529
  }
1245
- function sharedStart(texts) {
1246
- const [first = [], ...rest] = texts.map((text) => [...text]);
1247
- let length = first.length;
1248
- for (const chars of rest) {
1249
- const differs = chars.findIndex((char, index) => char !== first[index]);
1250
- length = Math.min(length, differs === -1 ? chars.length : differs);
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;
1251
1535
  }
1252
- return first.slice(0, length).join("");
1536
+ console.log(completionScript(shell, [name]).trimEnd());
1537
+ return 0;
1253
1538
  }
1254
- function listed2(colors, found, columns) {
1255
- const shared = sharedStart(found);
1256
- const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
1257
- const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
1258
- const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
1259
- return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
1539
+ async function printCandidates(found) {
1540
+ for (const line of await found)
1541
+ console.log(line);
1542
+ return 0;
1260
1543
  }
1261
- async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
1262
- let line = { text: "", caret: 0 };
1263
- let invalid;
1264
- let completions = [];
1265
- const remembered = history === undefined || mask ? undefined : history;
1266
- const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
1267
- let recalled = -1;
1268
- let draft = line;
1269
- const taken = () => line.text === "" ? fallback ?? "" : line.text;
1270
- const shown = () => mask ? "*".repeat([...taken()].length) : taken();
1271
- const accepted = await ask(question, settings, (colors, state, { columns }) => {
1272
- if (state !== "asking")
1273
- return [answer(colors, question, state, shown())];
1274
- const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
1275
- return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
1276
- }, (key) => {
1277
- if (key === "cancel")
1278
- return "cancel";
1279
- invalid = undefined;
1280
- completions = [];
1281
- if (line.chained === true && endsKills(key))
1282
- line = { ...line, chained: false };
1283
- if (key === "tab") {
1284
- const chars = [...line.text];
1285
- const before = chars.slice(0, line.caret).join("");
1286
- const found = complete?.(before) ?? [];
1287
- const filled = sharedStart(found);
1288
- if ([...filled].length > [...before].length)
1289
- line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
1290
- else
1291
- completions = found;
1292
- return;
1293
- }
1294
- if (key === "enter") {
1295
- invalid = validate?.(taken());
1296
- return invalid === undefined ? "enter" : undefined;
1297
- }
1298
- if (key === "up" || key === "down") {
1299
- const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
1300
- if (recalled === -1)
1301
- draft = line;
1302
- recalled = to;
1303
- const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
1304
- line = { ...shown, killed: line.killed ?? "" };
1305
- return;
1306
- }
1307
- const edit = { home: "linestart", end: "lineend" }[key] ?? key;
1308
- if (typeof edit === "object" || isEditKey(edit))
1309
- line = editLine(line, edit);
1310
- return;
1311
- });
1312
- if (!accepted)
1313
- return;
1314
- if (remembered !== undefined && taken() !== "")
1315
- rememberAnswer(remembered, taken());
1316
- return taken();
1544
+ function packageVersion(entry = Bun.main) {
1545
+ let resolved = entry;
1546
+ try {
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
+ }
1317
1558
  }
1318
- function answer(colors, question, state, picked) {
1319
- return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
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;
1320
1578
  }
1321
- async function ask(question, { hint, terminal = process14 }, render, press) {
1322
- const { stdin, stderr } = terminal;
1323
- if (!isInteractive(terminal))
1324
- fail(`cannot ask "${question}" off a terminal`, 2, hint);
1325
- const colors = paint(stderr);
1326
- let current = "asking";
1327
- let outcome;
1328
- const columns = () => stderr.columns || 80;
1329
- const draw = (state, last = false) => {
1330
- const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1331
- const rows = rowsTaken(frame, columns());
1332
- stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
1333
- current = state;
1334
- };
1335
- const redraw = () => draw(current);
1336
- const paste = { active: false };
1337
- const stop = terminal.stop ?? (terminal === process14 ? stopJob : undefined);
1338
- const suspend = () => {
1339
- if (stop === undefined)
1340
- return;
1341
- stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
1342
- stdin.setRawMode(false);
1343
- stop();
1344
- stdin.setRawMode(true);
1345
- stderr.write("\x1B[?25l\x1B[?2004h");
1346
- };
1347
- try {
1348
- stderr.on?.("resize", redraw);
1349
- stdin.setRawMode(true);
1350
- stdin.resume();
1351
- stderr.write("\x1B[?25l\x1B[?2004h");
1352
- draw("asking");
1353
- return await new Promise((resolve) => {
1354
- function onData(data) {
1355
- for (const key of readKeys(data.toString(), paste)) {
1356
- if (key === "suspend") {
1357
- suspend();
1358
- continue;
1359
- }
1360
- const pressed = press(key);
1361
- if (pressed !== undefined) {
1362
- settle(pressed);
1363
- return;
1364
- }
1365
- }
1366
- draw("asking");
1367
- }
1368
- function onEnd() {
1369
- settle("cancel");
1370
- }
1371
- function settle(settled) {
1372
- outcome = settled;
1373
- stdin.off("data", onData);
1374
- stdin.off("end", onEnd);
1375
- resolve(settled === "enter");
1376
- }
1377
- stdin.on("data", onData);
1378
- stdin.on("end", onEnd);
1379
- });
1380
- } finally {
1381
- stderr.off?.("resize", redraw);
1382
- draw(outcome ?? "cancel", true);
1383
- stderr.write(`
1384
- \x1B[?25h\x1B[?2004l`);
1385
- stdin.setRawMode(false);
1386
- stdin.pause();
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);
1387
1590
  }
1591
+ return path.length === 0 ? undefined : path.join(" ");
1388
1592
  }
1389
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
+
1390
1638
  // src/encode.ts
1391
1639
  function b64Encode(bytes, url = false) {
1392
1640
  return Buffer.from(bytes).toString(url ? "base64url" : "base64");
@@ -1443,6 +1691,38 @@ function ulid(now = Date.now(), random = randomBytes(16)) {
1443
1691
  function uuidV4() {
1444
1692
  return crypto.randomUUID();
1445
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
+ }
1446
1726
 
1447
1727
  // src/ip.ts
1448
1728
  var IP_SERVICE = "https://ipecho.net/plain";
@@ -1505,10 +1785,11 @@ var ZONELESS = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\
1505
1785
  var DATE_SPACE = /^(\d{4}-\d{2}-\d{2}) /;
1506
1786
  var WHITESPACE2 = /\s+/g;
1507
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})$/;
1508
1789
  function parseDate(text, timeZone) {
1509
1790
  const match = ZONELESS.exec(text);
1510
1791
  if (match === null) {
1511
- 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;
1512
1793
  return Number.isNaN(ms) ? undefined : ms;
1513
1794
  }
1514
1795
  const [, year, month, day, hour = "0", minute = "0", second = "0", fraction = "0"] = match;
@@ -1544,7 +1825,11 @@ function decodeJwt(token) {
1544
1825
  function claimTimes(payload, now = Date.now(), timeZone) {
1545
1826
  return TIME_CLAIMS.flatMap((claim) => {
1546
1827
  const epoch = payload[claim];
1547
- 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) }];
1548
1833
  });
1549
1834
  }
1550
1835
 
@@ -1555,6 +1840,7 @@ function generatePassword(length, format, random = (bytes) => crypto.getRandomVa
1555
1840
  const buffer = Buffer.from(random(new Uint8Array(length)));
1556
1841
  return buffer.toString(format);
1557
1842
  }
1843
+ var BCRYPT_MAX_BYTES = 72;
1558
1844
  async function bcryptHash(password) {
1559
1845
  const hash = await Bun.password.hash(password, { algorithm: "bcrypt", cost: 10 });
1560
1846
  return `$2y$${hash.slice("$2b$".length)}`;
@@ -1565,7 +1851,7 @@ var NUMBER = /^-?\d+(?:\.\d+)?$/;
1565
1851
  var MILLISECONDS_FROM = 100000000000;
1566
1852
  function instant(kind, ms, now, timeZone) {
1567
1853
  if (Number.isNaN(new Date(ms).getTime()))
1568
- throw new Error("the date is out of range");
1854
+ throw new RangeError("the date is out of range");
1569
1855
  return { kind, ...zoned(ms, timeZone), ms, seconds: Math.floor(ms / 1000), relative: relative(ms, now) };
1570
1856
  }
1571
1857
  function convert(value, { now = Date.now(), timeZone } = {}) {
@@ -1656,18 +1942,18 @@ async function bytesInput(argument, what) {
1656
1942
  return new Uint8Array(await Bun.stdin.arrayBuffer());
1657
1943
  }
1658
1944
  function printRows(rows) {
1659
- const { cyan } = paint(process15.stdout);
1945
+ const { cyan } = paint(process16.stdout);
1660
1946
  const width = Math.max(...rows.map(([label]) => label.length));
1661
1947
  for (const [label, value] of rows)
1662
1948
  console.log(`${cyan(label.padEnd(width))} ${value}`);
1663
1949
  }
1664
- var PASSWORD_USAGE = `dev password [length] [format] [-b|--bcrypt [password]]: a random password of <length> bytes (default ${DEFAULT_LENGTH}) as hex, base64 (default) or base64url
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
1665
1951
 
1666
- Printed on stdout and copied to the clipboard when a tool for it (wl-copy, xclip, xsel, pbcopy) exists (the copy is said on stderr). With --bcrypt it is the bcrypt hash (cost 10) that prints: of the password given (- asks for it masked on a terminal, or reads it from stdin, keeping it out of the shell history), or of a generated one, which then prints on stderr and is the one copied. Bun writes bcrypt as $2b$, the hash prints with the $2y$ prefix htpasswd -B writes, the one Apache, nginx and traefik basic auth all accept.`;
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.`;
1667
1953
  var PASSWORD_EXITS = [[0, "it printed the password or hash"], [2, "a usage error"], [130, "the prompt was cancelled"]];
1668
1954
  var PASSWORD_OPTIONS = {
1669
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" },
1670
- "no-copy": { type: "boolean", description: "leave the clipboard alone" },
1956
+ copy: copyOption("the password, or the hash of a password given"),
1671
1957
  json: jsonOption("{password?, hash?, format, bytes, copied}")
1672
1958
  };
1673
1959
  var FORMAT_NOTES = { hex: "hexadecimal", base64: "base64", base64url: "url-safe base64" };
@@ -1686,14 +1972,16 @@ async function password(args) {
1686
1972
  const bcrypt = values.bcrypt === "" ? undefined : values.bcrypt;
1687
1973
  const given = bcrypt === "-" ? await secretInput("the password") : bcrypt;
1688
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>` : ""}`);
1689
1977
  const hash = values.bcrypt === undefined ? undefined : await bcryptHash(secret);
1690
- 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);
1691
1979
  if (values.json === true) {
1692
1980
  printJson({ ...hash === undefined ? {} : { hash }, ...given === undefined ? { password: secret } : {}, format, bytes, copied });
1693
1981
  return 0;
1694
1982
  }
1695
1983
  if (copied)
1696
- console.error(paint(process15.stderr).dim("copied to clipboard"));
1984
+ console.error(paint(process16.stderr).dim("copied to clipboard"));
1697
1985
  if (hash !== undefined && given === undefined)
1698
1986
  console.error(secret);
1699
1987
  console.log(hash ?? secret);
@@ -1722,7 +2010,7 @@ async function jwt(args) {
1722
2010
  printJson({ header: decoded.header, payload: decoded.payload, claims, signatureBytes: decoded.signatureBytes });
1723
2011
  return 0;
1724
2012
  }
1725
- const { bold } = paint(process15.stdout);
2013
+ const { bold } = paint(process16.stdout);
1726
2014
  console.log(`${bold("header")}
1727
2015
  ${JSON.stringify(decoded.header, null, 2)}
1728
2016
 
@@ -1730,7 +2018,7 @@ ${bold("payload")}
1730
2018
  ${JSON.stringify(decoded.payload, null, 2)}`);
1731
2019
  if (claims.length > 0) {
1732
2020
  console.log("");
1733
- 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(" ")]));
1734
2022
  }
1735
2023
  return 0;
1736
2024
  }
@@ -1773,7 +2061,8 @@ function uuid(args) {
1773
2061
  replaces: 'uuidgen and python -c "import uuid"',
1774
2062
  examples: ["dev uuid", ["dev uuid -n 5 --v7", "five time-ordered UUIDs"]]
1775
2063
  });
1776
- 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);
1777
2066
  printIds(ids, values.json === true);
1778
2067
  return 0;
1779
2068
  }
@@ -1786,7 +2075,7 @@ function ulidCommand(args) {
1786
2075
  replaces: "installing a ulid package to mint one",
1787
2076
  examples: ["dev ulid", ["dev ulid -n 3", "three ULIDs"]]
1788
2077
  });
1789
- 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);
1790
2079
  return 0;
1791
2080
  }
1792
2081
  function printIds(ids, json) {
@@ -1908,13 +2197,13 @@ async function ip(args) {
1908
2197
  }
1909
2198
  }
1910
2199
  if (import.meta.main) {
1911
- process15.exitCode = await runCli({
2200
+ process16.exitCode = await runCli({
1912
2201
  name: "dev",
1913
2202
  about: "small developer utilities: passwords and bcrypt hashes, JWTs, timestamps, UUIDs, base64, URLs and file hashes",
1914
2203
  replaces: "openssl rand, htpasswd, jwt.io, date -d, uuidgen, base64, sha256sum and one-off scripts for each",
1915
2204
  examples: ["dev password", ["dev jwt <token>", "header, payload and expiry"], ["dev ts 1700000000", "an epoch as dates"]],
1916
2205
  commands: {
1917
- 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 },
1918
2207
  jwt: { summary: "decode a JWT without verifying it, expiry shown as dates", run: jwt },
1919
2208
  ts: { summary: "convert epochs, ISO dates and durations, local and UTC", run: ts },
1920
2209
  uuid: { summary: "random UUIDs, v4 or v7", run: async (args) => Promise.resolve(uuid(args)) },