@kaynooo/cli-pick 0.11.0 → 0.11.3

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 +2 -0
  2. package/dist/pick.js +956 -668
  3. package/package.json +5 -5
package/dist/pick.js CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
3
-
4
- // src/pick.ts
5
- import process18 from "process";
6
- // ../kit/src/args.ts
7
- import process9 from "process";
8
- import { parseArgs } from "util";
9
-
10
- // ../kit/src/format.ts
11
- import process7 from "process";
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
+ };
12
14
 
13
15
  // ../kit/src/mode.ts
14
16
  import process2 from "process";
15
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
16
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
17
17
  function isSet(value) {
18
18
  return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
19
19
  }
@@ -27,12 +27,13 @@ function outputMode(stream = process2.stdout, env = process2.env) {
27
27
  return "terminal";
28
28
  return isSet(env.CI) ? "ci" : "pipe";
29
29
  }
30
+ var MODES, AGENT_VARIABLES;
31
+ var init_mode = __esm(() => {
32
+ MODES = new Set(["terminal", "ci", "agent", "pipe"]);
33
+ AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
34
+ });
30
35
 
31
- // ../kit/src/style.ts
32
- import process6 from "process";
33
-
34
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
35
- var G = /^[a-f0-9]+$/i;
36
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
36
37
  function b(r) {
37
38
  let e = r.startsWith("#") ? r.slice(1) : r;
38
39
  if (!G.test(e))
@@ -43,11 +44,6 @@ function b(r) {
43
44
  throw Error(`Invalid hex color length: ${e.length}`);
44
45
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
45
46
  }
46
- var B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
47
- let [l, n, c] = b(r);
48
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
49
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
50
- var h = new Set(["", "1", "2", "3", "true"]);
51
47
  function C(r, e = globalThis.process?.env ?? {}) {
52
48
  if (e.FORCE_COLOR !== undefined)
53
49
  return h.has(e.FORCE_COLOR);
@@ -84,13 +80,21 @@ function f(r, e = []) {
84
80
  function Fe(r = {}) {
85
81
  return f(r);
86
82
  }
87
- var o = Fe();
83
+ var G, B, h, o;
84
+ var init_chunk_x450vn3m = __esm(() => {
85
+ G = /^[a-f0-9]+$/i;
86
+ 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") => {
87
+ let [l, n, c] = b(r);
88
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
89
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
90
+ h = new Set(["", "1", "2", "3", "true"]);
91
+ o = Fe();
92
+ });
88
93
 
89
- // ../kit/src/theme.ts
90
- import { existsSync as existsSync2, readFileSync, statSync } from "fs";
91
- import { homedir as homedir2 } from "os";
92
- import { join as join3, resolve as resolve2 } from "path";
93
- import process5 from "process";
94
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
95
+ var init_colors = __esm(() => {
96
+ init_chunk_x450vn3m();
97
+ });
94
98
 
95
99
  // ../kit/src/config.ts
96
100
  import { existsSync } from "fs";
@@ -106,6 +110,9 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
106
110
  return;
107
111
  }
108
112
  }
113
+ var init_config = __esm(() => {
114
+ init_args();
115
+ });
109
116
 
110
117
  // ../kit/src/user-config.ts
111
118
  import { homedir } from "os";
@@ -118,36 +125,18 @@ function configBase(where = {}) {
118
125
  function userConfigPath(bin, where = {}) {
119
126
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
120
127
  }
128
+ var init_user_config = () => {};
121
129
 
122
130
  // ../kit/src/theme.ts
123
- var ENDS = new Map;
124
- var DEFAULT = {
125
- colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
126
- glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
127
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
128
- bins: {},
129
- gradient: ["#c084fc", "#67e8f9"]
130
- };
131
- var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
132
- var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
133
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
134
- var PRESETS = {
135
- default: {},
136
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
137
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
138
- ascii: { glyphs: ASCII }
139
- };
140
- 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"]);
141
- var HEX = /^#[0-9a-f]{6}$/i;
142
- var CONTROL = /\p{Cc}/u;
143
- var MAX_FILE_BYTES = 64 * 1024;
144
- var SPACES = /\s+/;
131
+ import { existsSync as existsSync2, readFileSync, statSync } from "fs";
132
+ import { homedir as homedir2 } from "os";
133
+ import { join as join3, resolve as resolve2 } from "path";
134
+ import process5 from "process";
145
135
  function isColorSpec(spec) {
146
136
  if (typeof spec === "number")
147
137
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
148
138
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
149
139
  }
150
- var CUBE = [0, 95, 135, 175, 215, 255];
151
140
  function cubeLevel(channel) {
152
141
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
153
142
  }
@@ -252,7 +241,6 @@ function applyFile(theme, file, where, warn) {
252
241
  function endsWalk(home) {
253
242
  return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
254
243
  }
255
- var warned = new Set;
256
244
  function warnOnce(message) {
257
245
  if (warned.has(message))
258
246
  return;
@@ -289,8 +277,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
289
277
  }
290
278
  return { theme, sources, preset };
291
279
  }
292
- var current;
293
- var currentKey = "";
294
280
  function activeTheme() {
295
281
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
296
282
  if (current === undefined || key !== currentKey) {
@@ -299,8 +285,38 @@ function activeTheme() {
299
285
  }
300
286
  return current;
301
287
  }
288
+ var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
289
+ var init_theme = __esm(() => {
290
+ init_config();
291
+ init_user_config();
292
+ ENDS = new Map;
293
+ DEFAULT = {
294
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
295
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
296
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
297
+ bins: {},
298
+ gradient: ["#c084fc", "#67e8f9"]
299
+ };
300
+ BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
301
+ MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
302
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
303
+ PRESETS = {
304
+ default: {},
305
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
306
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
307
+ ascii: { glyphs: ASCII }
308
+ };
309
+ 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"]);
310
+ HEX = /^#[0-9a-f]{6}$/i;
311
+ CONTROL = /\p{Cc}/u;
312
+ MAX_FILE_BYTES = 64 * 1024;
313
+ SPACES = /\s+/;
314
+ CUBE = [0, 95, 135, 175, 215, 255];
315
+ warned = new Set;
316
+ });
302
317
 
303
318
  // ../kit/src/style.ts
319
+ import process6 from "process";
304
320
  function takesControlCodes(stream, env = process6.env) {
305
321
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
306
322
  }
@@ -311,17 +327,23 @@ function role(name, stream, env = process6.env) {
311
327
  const colors = paint(stream, env);
312
328
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
313
329
  }
314
- var STATUS_WORDS = {
315
- passed: ["passed", "success", "succeeded", "ok"],
316
- failed: ["failed", "failure", "error", "errored"],
317
- running: ["running", "in_progress", "started", "holding"],
318
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
319
- skipped: ["skipped", "cancelled", "canceled", "manual"]
320
- };
321
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
330
+ var STATUS_WORDS, STATUS_OF;
331
+ var init_style = __esm(() => {
332
+ init_colors();
333
+ init_mode();
334
+ init_theme();
335
+ STATUS_WORDS = {
336
+ passed: ["passed", "success", "succeeded", "ok"],
337
+ failed: ["failed", "failure", "error", "errored"],
338
+ running: ["running", "in_progress", "started", "holding"],
339
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
340
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
341
+ };
342
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
343
+ });
322
344
 
323
345
  // ../kit/src/format.ts
324
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
346
+ import process7 from "process";
325
347
  function formatSeconds(total) {
326
348
  let rest = Math.max(0, Math.round(total));
327
349
  const amounts = UNITS.map(([unit, size]) => {
@@ -342,7 +364,6 @@ function upTo(text, separator) {
342
364
  const end = text.indexOf(separator);
343
365
  return end === -1 ? text : text.slice(0, end);
344
366
  }
345
- var ESCAPE = String.fromCharCode(27);
346
367
  function textWidth(text) {
347
368
  return Bun.stringWidth(text);
348
369
  }
@@ -352,14 +373,38 @@ function jsonText(value, replacer, { stream = process7.stdout, env = process7.en
352
373
  function printJson(value) {
353
374
  console.log(jsonText(value));
354
375
  }
376
+ var UNITS, ESCAPE;
377
+ var init_format = __esm(() => {
378
+ init_mode();
379
+ init_style();
380
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
381
+ ESCAPE = String.fromCharCode(27);
382
+ });
355
383
 
356
384
  // ../kit/src/help.ts
357
385
  import process8 from "process";
358
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
359
- var USAGE_PREFIX = /^usage:\s*/i;
360
- var FULL_STOP = /\.$/;
361
386
  function usageLine(usage, colors = paint(process8.stdout)) {
362
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
387
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
388
+ `);
389
+ const blank = lines.indexOf("");
390
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
391
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
392
+ const colon = synopses[0].indexOf(": ");
393
+ const inline = synopses[0].slice(colon + 2);
394
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
395
+ if (colon !== -1)
396
+ synopses[0] = synopses[0].slice(0, colon);
397
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
398
+ `)}`;
399
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
400
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
401
+ return [head, ...lead, ...rest].join(`
402
+ `);
403
+ }
404
+ function prose(line, colors) {
405
+ if (colors.cyan("x") === "x")
406
+ return line;
407
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
363
408
  }
364
409
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
365
410
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -394,7 +439,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
394
439
  return [];
395
440
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
396
441
  }
397
- var MAX_INLINE_CHOICES = 24;
398
442
  function optionRows(options, colors = paint(process8.stdout)) {
399
443
  const rows = Object.entries(options).map(([name, option]) => {
400
444
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -409,9 +453,17 @@ function optionRows(options, colors = paint(process8.stdout)) {
409
453
  const width = Math.max(0, ...rows.map((row) => row.width));
410
454
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
411
455
  }
456
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
457
+ var init_help = __esm(() => {
458
+ init_mode();
459
+ init_style();
460
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
461
+ USAGE_PREFIX = /^usage:\s*/i;
462
+ FULL_STOP = /\.$/;
463
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
464
+ });
412
465
 
413
466
  // ../kit/src/text.ts
414
- var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
415
467
  function distance(a, b) {
416
468
  const left = [...a];
417
469
  const right = [...b];
@@ -437,40 +489,29 @@ function closest(name, names) {
437
489
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
438
490
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
439
491
  }
492
+ var ANSI;
493
+ var init_text = __esm(() => {
494
+ ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
495
+ });
496
+
497
+ // ../kit/src/input.ts
498
+ var init_input = __esm(() => {
499
+ init_args();
500
+ });
440
501
 
441
502
  // ../kit/src/args.ts
442
- var DASHES = /^-+/;
503
+ import process9 from "process";
504
+ import { parseArgs } from "util";
443
505
  function jsonOption(holds) {
444
506
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
445
507
  }
446
- class Exit extends Error {
447
- code;
448
- hint;
449
- constructor(message, code, hint) {
450
- super(message);
451
- this.code = code;
452
- this.hint = hint;
453
- }
454
- }
455
508
  function fail(message, code = 2, hint) {
456
509
  throw new Exit(message, code, hint);
457
510
  }
458
-
459
- class UsageError extends Exit {
460
- constructor(message, hint) {
461
- super(message, 2, hint);
462
- }
463
- }
464
511
  function badUsage(message) {
465
512
  throw new UsageError(message);
466
513
  }
467
514
 
468
- class HelpShown extends Exit {
469
- constructor() {
470
- super("help shown", 0);
471
- }
472
- }
473
-
474
515
  class Completing {
475
516
  options;
476
517
  positionals;
@@ -481,11 +522,6 @@ class Completing {
481
522
  this.candidates = candidates;
482
523
  }
483
524
  }
484
- var completion = { active: false };
485
- var OUTPUT_OPTIONS = {
486
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
487
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
488
- };
489
525
  function applyOutput(color, plain, env = process9.env) {
490
526
  const when = plain === true ? "never" : color ?? "auto";
491
527
  if (when === "auto")
@@ -639,7 +675,6 @@ function parseError(error) {
639
675
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
640
676
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
641
677
  }
642
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
643
678
  function nearestOption(message, options, allowNegative) {
644
679
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
645
680
  if (typed === undefined)
@@ -655,371 +690,177 @@ function nearestOption(message, options, allowNegative) {
655
690
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
656
691
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
657
692
  }
658
- // ../kit/src/argv.ts
659
- import { readFileSync as readFileSync2, realpathSync } from "fs";
660
- import { resolve as resolve3 } from "path";
661
- import process10 from "process";
662
- function commandLine() {
663
- try {
664
- return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
665
- } catch {
666
- return;
667
- }
668
- }
669
- function realPath(word) {
670
- try {
671
- return realpathSync(resolve3(word));
672
- } catch {
673
- return;
674
- }
675
- }
676
- function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
677
- const target = script === undefined ? undefined : realPath(script) ?? script;
678
- const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
679
- const after = at === -1 ? [] : cmdline.slice(at + 1);
680
- return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
681
- }
682
- // ../kit/src/progress.ts
683
- var ESC = String.fromCharCode(27);
684
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
685
- var RESET_STYLE = `${ESC}[0m`;
686
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
687
- // ../kit/src/cli.ts
688
- import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
689
- import { dirname as dirname3, join as join5 } from "path";
690
- import process13 from "process";
693
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
694
+ var init_args = __esm(() => {
695
+ init_format();
696
+ init_help();
697
+ init_text();
698
+ init_help();
699
+ init_input();
700
+ DASHES = /^-+/;
701
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
702
+ Exit = class Exit extends Error {
703
+ code;
704
+ hint;
705
+ [EXIT] = true;
706
+ constructor(message, code, hint) {
707
+ super(message);
708
+ this.code = code;
709
+ this.hint = hint;
710
+ }
711
+ static [Symbol.hasInstance](value) {
712
+ if (this !== Exit)
713
+ return Function.prototype[Symbol.hasInstance].call(this, value);
714
+ return typeof value === "object" && value !== null && value[EXIT] === true;
715
+ }
716
+ };
717
+ UsageError = class UsageError extends Exit {
718
+ constructor(message, hint) {
719
+ super(message, 2, hint);
720
+ }
721
+ };
722
+ HelpShown = class HelpShown extends Exit {
723
+ constructor() {
724
+ super("help shown", 0);
725
+ }
726
+ };
727
+ completion = { active: false };
728
+ OUTPUT_OPTIONS = {
729
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
730
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
731
+ };
732
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
733
+ });
691
734
 
692
- // ../kit/src/notify.ts
693
- import process11 from "process";
694
- var NOTIFY_AFTER_MS = 1e4;
695
- var CANCELLED = 130;
696
- function base64(text) {
697
- return Buffer.from(text).toString("base64");
735
+ // ../kit/src/folders.ts
736
+ var SKIPPED_FOLDERS;
737
+ var init_folders = __esm(() => {
738
+ init_user_config();
739
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
740
+ });
741
+
742
+ // ../kit/src/picker/line.ts
743
+ function isEditKey(key) {
744
+ return EDIT_KEYS.has(key);
698
745
  }
699
- function notification(title, body, env = process11.env) {
700
- const id = `kit${process11.pid}`;
701
- 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\\`];
702
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
746
+ function endsKills(key) {
747
+ return typeof key !== "object" && !isEditKey(key);
703
748
  }
704
- function notifyEnd(command, code, ms, { stream = process11.stderr, env = process11.env } = {}) {
705
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
706
- return;
707
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
749
+ function isWord(char) {
750
+ return char !== undefined && WORD_CHARACTER.test(char);
708
751
  }
709
-
710
- // ../kit/src/usage.ts
711
- import { appendFileSync, mkdirSync } from "fs";
712
- import { homedir as homedir3 } from "os";
713
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
714
- import process12 from "process";
715
-
716
- // ../kit/src/logs.ts
717
- var DAY_MS = 24 * 60 * 60 * 1000;
718
- var CLI_FOLDER = "kaynooo-cli";
719
-
720
- // ../kit/src/usage.ts
721
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
722
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
723
- var LONGEST_NAME = 40;
724
- var usageError;
725
- function noteUsageError(message) {
726
- usageError = message;
752
+ function wordStart(chars, from) {
753
+ let at = from;
754
+ while (at > 0 && !isWord(chars[at - 1]))
755
+ at--;
756
+ while (at > 0 && isWord(chars[at - 1]))
757
+ at--;
758
+ return at;
727
759
  }
728
- function stateHome(env = process12.env) {
729
- const dir = env.XDG_STATE_HOME;
730
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
760
+ function wordEnd(chars, from) {
761
+ let at = from;
762
+ while (at < chars.length && !isWord(chars[at]))
763
+ at++;
764
+ while (at < chars.length && isWord(chars[at]))
765
+ at++;
766
+ return at;
731
767
  }
732
- function usagePath(env = process12.env) {
733
- return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
768
+ function spacedStart(chars, from) {
769
+ let at = from;
770
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
771
+ at--;
772
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
773
+ at--;
774
+ return at;
734
775
  }
735
- function usageRecorded(env = process12.env) {
736
- const off = env.KAYNOOO_CLI_NO_USAGE;
737
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
776
+ function cut(chars, from, to) {
777
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
738
778
  }
739
- function flagNames(argv) {
740
- const end = argv.indexOf("--");
741
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
742
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
779
+ function insert(chars, at, text) {
780
+ const typed = [...text];
781
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
743
782
  }
744
- function usageEntry(bin, command, argv, code, now = new Date) {
745
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
746
- usageError = undefined;
747
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
783
+ function editLine(line, key) {
784
+ const { killed = "", chained = false } = line;
785
+ const chars = [...line.text];
786
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
787
+ const edited = edit(chars, at, key, killed);
788
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
789
+ return line.killed === undefined ? edited : { ...edited, killed };
790
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
791
+ if (taken === "")
792
+ return { ...edited, killed, chained };
793
+ if (!chained)
794
+ return { ...edited, killed: taken, chained: true };
795
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
748
796
  }
749
- function recordUsage(entry, env = process12.env) {
750
- if (!usageRecorded(env))
751
- return;
752
- try {
753
- const path = usagePath(env);
754
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
755
- appendFileSync(path, `${JSON.stringify(entry)}
756
- `, { mode: 384 });
757
- } catch {}
797
+ function edit(chars, at, key, killed) {
798
+ const text = chars.join("");
799
+ if (typeof key === "object")
800
+ return insert(chars, at, key.text);
801
+ switch (key) {
802
+ case "left":
803
+ return { text, caret: Math.max(at - 1, 0) };
804
+ case "right":
805
+ return { text, caret: Math.min(at + 1, chars.length) };
806
+ case "wordleft":
807
+ return { text, caret: wordStart(chars, at) };
808
+ case "wordright":
809
+ return { text, caret: wordEnd(chars, at) };
810
+ case "linestart":
811
+ return { text, caret: 0 };
812
+ case "lineend":
813
+ return { text, caret: chars.length };
814
+ case "erase":
815
+ return cut(chars, Math.max(at - 1, 0), at);
816
+ case "delete":
817
+ return cut(chars, at, Math.min(at + 1, chars.length));
818
+ case "word":
819
+ return cut(chars, spacedStart(chars, at), at);
820
+ case "killword":
821
+ return cut(chars, wordStart(chars, at), at);
822
+ case "killnext":
823
+ return cut(chars, at, wordEnd(chars, at));
824
+ case "clear":
825
+ return cut(chars, 0, at);
826
+ case "killend":
827
+ return cut(chars, at, chars.length);
828
+ case "yank":
829
+ return insert(chars, at, killed);
830
+ }
758
831
  }
759
-
760
- // ../kit/src/cli.ts
761
- var LEVEL_OPTIONS = {
762
- ...OUTPUT_OPTIONS,
763
- help: { type: "boolean", short: "h", description: "show this help" }
764
- };
765
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
766
- function printError(prefix, message, hint, cause) {
767
- const colors = paint(process13.stderr);
768
- const styled = takesControlCodes(process13.stderr);
769
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
770
- const under = (label, text, tint) => text === undefined ? "" : `
771
- ${styled ? tint(label) : `${label}:`} ${text}`;
772
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
832
+ function visible({ text, caret }, room) {
833
+ const chars = [...text];
834
+ const at = Math.min(Math.max(caret, 0), chars.length);
835
+ const cells = at === chars.length ? [...chars, " "] : chars;
836
+ const widths = cells.map((char) => Bun.stringWidth(char));
837
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
838
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
839
+ let start = at;
840
+ let end = at + 1;
841
+ while (start > 0 && fits(start - 1, end))
842
+ start--;
843
+ while (end < cells.length && fits(start, end + 1))
844
+ end++;
845
+ const left = start > 0 ? "\u2026" : "";
846
+ const right = end < cells.length ? "\u2026" : "";
847
+ 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) };
773
848
  }
774
- function printJsonError(message, hint, cause) {
775
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
776
- }
777
- function wantsJson(argv) {
778
- const end = argv.indexOf("--");
779
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
780
- }
781
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
782
- if (error instanceof HelpShown)
783
- return 0;
784
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
785
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
786
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
787
- if (error instanceof Exit && error.code === 2)
788
- noteUsageError(error.message);
789
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
790
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
791
- return error instanceof Exit ? error.code : 1;
792
- }
793
- var COMPLETE = "__complete";
794
- var FILES = "__files__";
795
- async function completingOf(run) {
796
- completion.active = true;
797
- try {
798
- await run([]);
799
- } catch (error) {
800
- if (error instanceof Completing)
801
- return error;
802
- } finally {
803
- completion.active = false;
804
- }
805
- return new Completing({});
806
- }
807
- function candidateLine(candidate) {
808
- return typeof candidate === "string" ? candidate : candidate.join("\t");
809
- }
810
- function positionalBeingTyped(before, { options, positionals }) {
811
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
812
- const typed = [];
813
- let at = 0;
814
- while (at < before.length) {
815
- const word = before[at];
816
- if (word === "--") {
817
- typed.push(...before.slice(at + 1));
818
- break;
819
- }
820
- if (!word.startsWith("-"))
821
- typed.push(word);
822
- else if (takesValue(word))
823
- at++;
824
- at++;
825
- }
826
- const last = positionals.at(-1);
827
- if (typed.length < positionals.length)
828
- return { name: positionals[typed.length], typed };
829
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
830
- }
831
- async function leafCandidates(run, words) {
832
- const completing = await completingOf(run);
833
- if ((words.at(-1) ?? "").startsWith("-"))
834
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
835
- const flag = words.at(-2);
836
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
837
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
838
- if (option?.type === "string") {
839
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
840
- return values === undefined ? [FILES] : values.map(candidateLine);
841
- }
842
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
843
- return values === undefined ? [FILES] : values.map(candidateLine);
844
- }
845
- async function printCandidates(found) {
846
- for (const line of await found)
847
- console.log(line);
848
- return 0;
849
- }
850
- function packageVersion(entry = Bun.main) {
851
- let resolved = entry;
852
- try {
853
- resolved = realpathSync2(entry);
854
- } catch {}
855
- for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
856
- try {
857
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
858
- if (typeof version === "string")
859
- return version;
860
- } catch {}
861
- if (dirname3(dir) === dir)
862
- return "0.0.0";
863
- }
864
- }
865
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
866
- if (argv[0] === COMPLETE)
867
- return printCandidates(leafCandidates(run, argv.slice(1)));
868
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
869
- console.log(version ?? packageVersion());
870
- return 0;
871
- }
872
- let code;
873
- const started = performance.now();
874
- try {
875
- code = await run(argv);
876
- } catch (error) {
877
- code = reportThrown(name, error, redact, wantsJson(argv));
878
- }
879
- notifyEnd(name, code, performance.now() - started);
880
- if (usage !== false) {
881
- try {
882
- recordUsage(usageEntry(name, undefined, argv, code));
883
- } catch {}
884
- }
885
- return code;
886
- }
887
- // ../kit/src/folders.ts
888
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
889
- // ../kit/src/secrets.ts
890
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
891
- // ../kit/src/sessions.ts
892
- var {Glob } = globalThis.Bun;
893
- var SESSION_FILES = new Glob("*.json");
894
- var ACCOUNT_DIRS = new Glob("*/sessions");
895
- // ../kit/src/picker/line.ts
896
- var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
897
- var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
898
- var FORWARD_KILLS = new Set(["killnext", "killend"]);
899
- function isEditKey(key) {
900
- return EDIT_KEYS.has(key);
901
- }
902
- function endsKills(key) {
903
- return typeof key !== "object" && !isEditKey(key);
904
- }
905
- var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
906
- var SPACE = /\s/;
907
- function isWord(char) {
908
- return char !== undefined && WORD_CHARACTER.test(char);
909
- }
910
- function wordStart(chars, from) {
911
- let at = from;
912
- while (at > 0 && !isWord(chars[at - 1]))
913
- at--;
914
- while (at > 0 && isWord(chars[at - 1]))
915
- at--;
916
- return at;
917
- }
918
- function wordEnd(chars, from) {
919
- let at = from;
920
- while (at < chars.length && !isWord(chars[at]))
921
- at++;
922
- while (at < chars.length && isWord(chars[at]))
923
- at++;
924
- return at;
925
- }
926
- function spacedStart(chars, from) {
927
- let at = from;
928
- while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
929
- at--;
930
- while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
931
- at--;
932
- return at;
933
- }
934
- function cut(chars, from, to) {
935
- return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
936
- }
937
- function insert(chars, at, text) {
938
- const typed = [...text];
939
- return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
940
- }
941
- function editLine(line, key) {
942
- const { killed = "", chained = false } = line;
943
- const chars = [...line.text];
944
- const at = Math.min(Math.max(line.caret, 0), chars.length);
945
- const edited = edit(chars, at, key, killed);
946
- if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
947
- return line.killed === undefined ? edited : { ...edited, killed };
948
- const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
949
- if (taken === "")
950
- return { ...edited, killed, chained };
951
- if (!chained)
952
- return { ...edited, killed: taken, chained: true };
953
- return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
954
- }
955
- function edit(chars, at, key, killed) {
956
- const text = chars.join("");
957
- if (typeof key === "object")
958
- return insert(chars, at, key.text);
959
- switch (key) {
960
- case "left":
961
- return { text, caret: Math.max(at - 1, 0) };
962
- case "right":
963
- return { text, caret: Math.min(at + 1, chars.length) };
964
- case "wordleft":
965
- return { text, caret: wordStart(chars, at) };
966
- case "wordright":
967
- return { text, caret: wordEnd(chars, at) };
968
- case "linestart":
969
- return { text, caret: 0 };
970
- case "lineend":
971
- return { text, caret: chars.length };
972
- case "erase":
973
- return cut(chars, Math.max(at - 1, 0), at);
974
- case "delete":
975
- return cut(chars, at, Math.min(at + 1, chars.length));
976
- case "word":
977
- return cut(chars, spacedStart(chars, at), at);
978
- case "killword":
979
- return cut(chars, wordStart(chars, at), at);
980
- case "killnext":
981
- return cut(chars, at, wordEnd(chars, at));
982
- case "clear":
983
- return cut(chars, 0, at);
984
- case "killend":
985
- return cut(chars, at, chars.length);
986
- case "yank":
987
- return insert(chars, at, killed);
988
- }
989
- }
990
- function visible({ text, caret }, room) {
991
- const chars = [...text];
992
- const at = Math.min(Math.max(caret, 0), chars.length);
993
- const cells = at === chars.length ? [...chars, " "] : chars;
994
- const widths = cells.map((char) => Bun.stringWidth(char));
995
- const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
996
- const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
997
- let start = at;
998
- let end = at + 1;
999
- while (start > 0 && fits(start - 1, end))
1000
- start--;
1001
- while (end < cells.length && fits(start, end + 1))
1002
- end++;
1003
- const left = start > 0 ? "\u2026" : "";
1004
- const right = end < cells.length ? "\u2026" : "";
1005
- 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) };
1006
- }
1007
-
1008
- // ../kit/src/picker/score.ts
1009
- var MATCH = 16;
1010
- var CONSECUTIVE = 12;
1011
- var BOUNDARY = 10;
1012
- var PREFIX = 8;
1013
- var GAP = 1;
1014
- var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1015
- var UPPER = /\p{Lu}/u;
1016
- var LOWER = /\p{Ll}/u;
1017
- var NONE = Number.NEGATIVE_INFINITY;
1018
- function startsWord(text, index) {
1019
- if (index === 0)
1020
- return true;
1021
- const before = text[index - 1];
1022
- return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
849
+ var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS, WORD_CHARACTER, SPACE;
850
+ var init_line = __esm(() => {
851
+ EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
852
+ BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
853
+ FORWARD_KILLS = new Set(["killnext", "killend"]);
854
+ WORD_CHARACTER = /[\p{L}\p{N}_]/u;
855
+ SPACE = /\s/;
856
+ });
857
+
858
+ // ../kit/src/picker/score.ts
859
+ function startsWord(text, index) {
860
+ if (index === 0)
861
+ return true;
862
+ const before = text[index - 1];
863
+ return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
1023
864
  }
1024
865
  function fuzzy(query, text) {
1025
866
  if (query === "")
@@ -1087,229 +928,671 @@ function rank(query, lines) {
1087
928
  }
1088
929
  return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
1089
930
  }
931
+ var MATCH = 16, CONSECUTIVE = 12, BOUNDARY = 10, PREFIX = 8, GAP = 1, BOUNDARY_AFTER, UPPER, LOWER, NONE;
932
+ var init_score = __esm(() => {
933
+ BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
934
+ UPPER = /\p{Lu}/u;
935
+ LOWER = /\p{Ll}/u;
936
+ NONE = Number.NEGATIVE_INFINITY;
937
+ });
1090
938
 
1091
939
  // ../kit/src/picker/state.ts
1092
- var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1093
- var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1094
- var SGR = /^\x1B\[[0-9;]*m$/;
1095
- var RESET = /^\x1B\[0?m$/;
1096
- var COLUMN_GAP = 2;
1097
- var PASTE_START = "\x1B[200~";
1098
- var PASTE_END = "\x1B[201~";
1099
- var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1100
- var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1101
- var WHEEL_LINES = 3;
1102
- var KEYS = {
1103
- "\x1B[A": "up",
1104
- "\x1BOA": "up",
1105
- "\x10": "up",
1106
- "\x1B[B": "down",
1107
- "\x1BOB": "down",
1108
- "\x0E": "down",
1109
- "\x1B[5~": "pageup",
1110
- "\x1B[6~": "pagedown",
1111
- "\x1B[H": "home",
1112
- "\x1B[1~": "home",
1113
- "\x1BOH": "home",
1114
- "\x1B[F": "end",
1115
- "\x1B[4~": "end",
1116
- "\x1BOF": "end",
1117
- "\r": "enter",
1118
- "\n": "enter",
1119
- "\x03": "cancel",
1120
- "\x1B": "cancel",
1121
- "\x1B[D": "left",
1122
- "\x1BOD": "left",
1123
- "\x1B[C": "right",
1124
- "\x1BOC": "right",
1125
- "\x1B[1;5D": "wordleft",
1126
- "\x1B[1;3D": "wordleft",
1127
- "\x1Bb": "wordleft",
1128
- "\x1B[1;5C": "wordright",
1129
- "\x1B[1;3C": "wordright",
1130
- "\x1Bf": "wordright",
1131
- "\x01": "linestart",
1132
- "\x05": "lineend",
1133
- "\x7F": "erase",
1134
- "\x1B[3~": "delete",
1135
- "\b": "killword",
1136
- "\x1B\x7F": "killword",
1137
- "\x1B[3;5~": "killnext",
1138
- "\x1Bd": "killnext",
1139
- "\x15": "clear",
1140
- "\v": "killend",
1141
- "\x17": "word",
1142
- "\x19": "yank",
1143
- "\x1A": "suspend",
1144
- "\t": "tab",
1145
- "\x1F": "help",
1146
- "\x1BOP": "help",
1147
- "\x1B[11~": "help"
1148
- };
1149
940
  function repeat(value, count) {
1150
941
  return Array.from({ length: count }).fill(value);
1151
942
  }
1152
- function styled(line) {
1153
- let text = "";
1154
- const styles = [];
1155
- let active = "";
1156
- let colored = false;
1157
- let last = 0;
1158
- function add(chunk) {
1159
- const flat = chunk.replace(CONTROL2, " ");
1160
- text += flat;
1161
- colored ||= active !== "" && flat !== "";
1162
- styles.push(...repeat(active, flat.length));
1163
- }
1164
- for (const found of line.matchAll(ANSI)) {
1165
- add(line.slice(last, found.index));
1166
- last = found.index + found[0].length;
1167
- if (SGR.test(found[0]))
1168
- active = RESET.test(found[0]) ? "" : active + found[0];
943
+ function styled(line) {
944
+ let text = "";
945
+ const styles = [];
946
+ let active = "";
947
+ let colored = false;
948
+ let last = 0;
949
+ function add(chunk) {
950
+ const flat = chunk.replace(CONTROL2, " ");
951
+ text += flat;
952
+ colored ||= active !== "" && flat !== "";
953
+ styles.push(...repeat(active, flat.length));
954
+ }
955
+ for (const found of line.matchAll(ANSI)) {
956
+ add(line.slice(last, found.index));
957
+ last = found.index + found[0].length;
958
+ if (SGR.test(found[0]))
959
+ active = RESET.test(found[0]) ? "" : active + found[0];
960
+ }
961
+ add(line.slice(last));
962
+ return { text, styles: colored ? styles : undefined };
963
+ }
964
+ function lay(rows, searched) {
965
+ const parsed = rows.map((row) => row.cells.map(styled));
966
+ const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
967
+ return parsed.map((cells, at) => {
968
+ let text = "";
969
+ const styles = [];
970
+ let colored = false;
971
+ let searchEnd = 0;
972
+ for (const [column, cell] of cells.entries()) {
973
+ const last = column === cells.length - 1;
974
+ const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
975
+ text += shown;
976
+ colored ||= cell.styles !== undefined;
977
+ styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
978
+ if (column < searched)
979
+ searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
980
+ if (!last) {
981
+ const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
982
+ text += " ".repeat(pad);
983
+ styles.push(...repeat("", pad));
984
+ }
985
+ }
986
+ return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
987
+ });
988
+ }
989
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
990
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
991
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
992
+ const wheel = MOUSE.exec(sequence)?.[1];
993
+ if (wheel !== undefined)
994
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
995
+ const named = codes.get(sequence);
996
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
997
+ if (sequence === PASTE_START || sequence === PASTE_END) {
998
+ paste.active = sequence === PASTE_START;
999
+ return [];
1000
+ }
1001
+ if (paste.active && (sequence === "\r" || sequence === `
1002
+ `))
1003
+ return [];
1004
+ if (key !== undefined)
1005
+ return [key];
1006
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1007
+ });
1008
+ }
1009
+ function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1010
+ const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, caret: [...query].length, killed: "", chained: false, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1011
+ return withRows(state, rows);
1012
+ }
1013
+ function withRows(state, rows, header = state.header) {
1014
+ const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1015
+ const laid = lay(cells, state.searched);
1016
+ const searchable = laid.map((row) => row.searchable);
1017
+ const matches = rank(state.query, searchable);
1018
+ return { ...state, rows: cells, items: laid.map((row) => row.text), styles: laid.map((row) => row.styles), searchable, header, matches, cursor: Math.max(0, Math.min(matches.length - 1, state.cursor)), marked: new Set };
1019
+ }
1020
+ function withQuery(state, key) {
1021
+ const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1022
+ return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1023
+ }
1024
+ function move(state, by) {
1025
+ return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
1026
+ }
1027
+ function highlighted(state) {
1028
+ return state.matches[state.cursor]?.index;
1029
+ }
1030
+ function press(state, key) {
1031
+ if (state.done !== undefined)
1032
+ return state;
1033
+ if (state.chained && endsKills(key))
1034
+ state = { ...state, chained: false };
1035
+ if (state.help)
1036
+ return { ...state, help: false };
1037
+ if (typeof key === "object") {
1038
+ if ("text" in key)
1039
+ return withQuery(state, key);
1040
+ return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1041
+ }
1042
+ if (isEditKey(key))
1043
+ return withQuery(state, key);
1044
+ switch (key) {
1045
+ case "up":
1046
+ return move(state, -1);
1047
+ case "down":
1048
+ return move(state, 1);
1049
+ case "pageup":
1050
+ return move(state, -state.page);
1051
+ case "pagedown":
1052
+ return move(state, state.page);
1053
+ case "home":
1054
+ return move(state, -state.matches.length);
1055
+ case "end":
1056
+ return move(state, state.matches.length);
1057
+ case "cancel":
1058
+ return { ...state, done: "cancel" };
1059
+ case "help":
1060
+ return { ...state, help: true };
1061
+ case "suspend":
1062
+ return state;
1063
+ case "enter":
1064
+ return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1065
+ case "tab": {
1066
+ const at = highlighted(state);
1067
+ if (!state.multi || at === undefined)
1068
+ return state;
1069
+ const marked = new Set(state.marked);
1070
+ if (!marked.delete(at))
1071
+ marked.add(at);
1072
+ return move({ ...state, marked }, 1);
1073
+ }
1074
+ }
1075
+ }
1076
+ function chosen(state) {
1077
+ if (state.marked.size > 0)
1078
+ return state.rows.filter((_, index) => state.marked.has(index));
1079
+ const at = highlighted(state);
1080
+ return at === undefined ? [] : [state.rows[at]];
1081
+ }
1082
+ var CONTROL2, IS_CONTROL, SGR, RESET, COLUMN_GAP = 2, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS;
1083
+ var init_state = __esm(() => {
1084
+ init_text();
1085
+ init_line();
1086
+ init_score();
1087
+ CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1088
+ IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1089
+ SGR = /^\x1B\[[0-9;]*m$/;
1090
+ RESET = /^\x1B\[0?m$/;
1091
+ KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1092
+ MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1093
+ KEYS = {
1094
+ "\x1B[A": "up",
1095
+ "\x1BOA": "up",
1096
+ "\x10": "up",
1097
+ "\x1B[B": "down",
1098
+ "\x1BOB": "down",
1099
+ "\x0E": "down",
1100
+ "\x1B[5~": "pageup",
1101
+ "\x1B[6~": "pagedown",
1102
+ "\x1B[H": "home",
1103
+ "\x1B[1~": "home",
1104
+ "\x1BOH": "home",
1105
+ "\x1B[F": "end",
1106
+ "\x1B[4~": "end",
1107
+ "\x1BOF": "end",
1108
+ "\r": "enter",
1109
+ "\n": "enter",
1110
+ "\x03": "cancel",
1111
+ "\x1B": "cancel",
1112
+ "\x1B[D": "left",
1113
+ "\x1BOD": "left",
1114
+ "\x1B[C": "right",
1115
+ "\x1BOC": "right",
1116
+ "\x1B[1;5D": "wordleft",
1117
+ "\x1B[1;3D": "wordleft",
1118
+ "\x1Bb": "wordleft",
1119
+ "\x1B[1;5C": "wordright",
1120
+ "\x1B[1;3C": "wordright",
1121
+ "\x1Bf": "wordright",
1122
+ "\x01": "linestart",
1123
+ "\x05": "lineend",
1124
+ "\x7F": "erase",
1125
+ "\x1B[3~": "delete",
1126
+ "\b": "killword",
1127
+ "\x1B\x7F": "killword",
1128
+ "\x1B[3;5~": "killnext",
1129
+ "\x1Bd": "killnext",
1130
+ "\x15": "clear",
1131
+ "\v": "killend",
1132
+ "\x17": "word",
1133
+ "\x19": "yank",
1134
+ "\x1A": "suspend",
1135
+ "\t": "tab",
1136
+ "\x1F": "help",
1137
+ "\x1BOP": "help",
1138
+ "\x1B[11~": "help"
1139
+ };
1140
+ });
1141
+
1142
+ // ../kit/src/job.ts
1143
+ import process16 from "process";
1144
+ function stopJob() {
1145
+ process16.kill(0, "SIGTSTP");
1146
+ }
1147
+ var init_job = () => {};
1148
+
1149
+ // ../kit/src/redraw.ts
1150
+ function overwrite(lines, columns) {
1151
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1152
+ `);
1153
+ }
1154
+ var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
1155
+ var init_redraw = __esm(() => {
1156
+ init_format();
1157
+ });
1158
+
1159
+ // src/pick.ts
1160
+ import process19 from "process";
1161
+
1162
+ // ../kit/src/index.ts
1163
+ init_args();
1164
+
1165
+ // ../kit/src/argv.ts
1166
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
1167
+ import { resolve as resolve3 } from "path";
1168
+ import process10 from "process";
1169
+ function commandLine() {
1170
+ try {
1171
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
1172
+ } catch {
1173
+ return;
1174
+ }
1175
+ }
1176
+ function realPath(word) {
1177
+ try {
1178
+ return realpathSync(resolve3(word));
1179
+ } catch {
1180
+ return;
1181
+ }
1182
+ }
1183
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
1184
+ const target = script === undefined ? undefined : realPath(script) ?? script;
1185
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
1186
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
1187
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
1188
+ }
1189
+ // ../kit/src/chart.ts
1190
+ init_format();
1191
+ init_mode();
1192
+ init_style();
1193
+ init_theme();
1194
+ // ../kit/src/ci.ts
1195
+ init_args();
1196
+ init_format();
1197
+
1198
+ // ../kit/src/progress.ts
1199
+ init_format();
1200
+ init_style();
1201
+ init_theme();
1202
+ var ESC = String.fromCharCode(27);
1203
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
1204
+ var RESET_STYLE = `${ESC}[0m`;
1205
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1206
+
1207
+ // ../kit/src/ci.ts
1208
+ init_style();
1209
+
1210
+ // ../kit/src/tool.ts
1211
+ init_format();
1212
+ // ../kit/src/cli.ts
1213
+ init_args();
1214
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
1215
+ import { dirname as dirname3, join as join5 } from "path";
1216
+ import process14 from "process";
1217
+
1218
+ // ../kit/src/askpass.ts
1219
+ import process11 from "process";
1220
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1221
+ async function askpassClient(argv) {
1222
+ const socketPath = process11.env[SOCKET_VARIABLE];
1223
+ if (socketPath === undefined)
1224
+ return;
1225
+ const request = { prompt: argv[0] ?? "", ...process11.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1226
+ const { promise, resolve } = Promise.withResolvers();
1227
+ let received = "";
1228
+ try {
1229
+ await Bun.connect({
1230
+ unix: socketPath,
1231
+ socket: {
1232
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
1233
+ `),
1234
+ data: (_, chunk) => {
1235
+ received += chunk.toString();
1236
+ },
1237
+ close: () => resolve(received),
1238
+ error: () => resolve("")
1239
+ }
1240
+ });
1241
+ } catch {
1242
+ return 1;
1243
+ }
1244
+ const reply = await promise;
1245
+ if (reply === "")
1246
+ return 1;
1247
+ const { answer } = JSON.parse(reply);
1248
+ if (request.notice === true)
1249
+ return 0;
1250
+ if (answer === undefined)
1251
+ return 1;
1252
+ process11.stdout.write(`${answer}
1253
+ `);
1254
+ return 0;
1255
+ }
1256
+
1257
+ // ../kit/src/completions.ts
1258
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1259
+ 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'
1260
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1261
+ set -l current (commandline -ct)
1262
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1263
+ if test "$line" = __files__
1264
+ __fish_complete_path $current
1265
+ else
1266
+ echo $line
1267
+ end
1268
+ end
1269
+ end`;
1270
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1271
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1272
+ local -a lines
1273
+ COMPREPLY=()
1274
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1275
+ for line in "\${lines[@]}"; do
1276
+ if [[ $line == __files__ ]]; then
1277
+ COMPREPLY+=($(compgen -f -- "$cur"))
1278
+ else
1279
+ words+="\${line%%$'\\t'*}"$'\\n'
1280
+ fi
1281
+ done
1282
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1283
+ }`;
1284
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1285
+ local line
1286
+ local -a described plain
1287
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1288
+ if [[ $line == __files__ ]]; then
1289
+ _files
1290
+ elif [[ $line == *$'\\t'* ]]; then
1291
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1292
+ else
1293
+ plain+=("$line")
1294
+ fi
1295
+ done
1296
+ (( \${#described} )) && _describe -V value described
1297
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1298
+ return 0
1299
+ }`;
1300
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1301
+ if (shell === "fish")
1302
+ return `${header}
1303
+ ${FISH_FUNCTION}
1304
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1305
+ `).join("")}`;
1306
+ if (shell === "bash")
1307
+ return `${header}
1308
+ ${BASH_FUNCTION}
1309
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1310
+ `;
1311
+ return `${header}
1312
+ ${ZSH_FUNCTION}
1313
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1314
+ `;
1315
+ }
1316
+
1317
+ // ../kit/src/notify.ts
1318
+ init_format();
1319
+ init_mode();
1320
+ import process12 from "process";
1321
+ var NOTIFY_AFTER_MS = 1e4;
1322
+ var CANCELLED = 130;
1323
+ function base64(text) {
1324
+ return Buffer.from(text).toString("base64");
1325
+ }
1326
+ function notification(title, body, env = process12.env) {
1327
+ const id = `kit${process12.pid}`;
1328
+ 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\\`];
1329
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1330
+ }
1331
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
1332
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1333
+ return;
1334
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1335
+ }
1336
+
1337
+ // ../kit/src/cli.ts
1338
+ init_style();
1339
+ init_text();
1340
+
1341
+ // ../kit/src/usage.ts
1342
+ import { appendFileSync, mkdirSync } from "fs";
1343
+ import { homedir as homedir3 } from "os";
1344
+ import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1345
+ import process13 from "process";
1346
+
1347
+ // ../kit/src/logs.ts
1348
+ var DAY_MS = 24 * 60 * 60 * 1000;
1349
+ var CLI_FOLDER = "kaynooo-cli";
1350
+
1351
+ // ../kit/src/usage.ts
1352
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1353
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1354
+ var LONGEST_NAME = 40;
1355
+ var usageError;
1356
+ function noteUsageError(message) {
1357
+ usageError = message;
1358
+ }
1359
+ function stateHome(env = process13.env) {
1360
+ const dir = env.XDG_STATE_HOME;
1361
+ return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1362
+ }
1363
+ function usagePath(env = process13.env) {
1364
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1365
+ }
1366
+ function usageRecorded(env = process13.env) {
1367
+ const off = env.KAYNOOO_CLI_NO_USAGE;
1368
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1369
+ }
1370
+ function flagNames(argv) {
1371
+ const end = argv.indexOf("--");
1372
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1373
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1374
+ }
1375
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1376
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1377
+ usageError = undefined;
1378
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1379
+ }
1380
+ function recordUsage(entry, env = process13.env) {
1381
+ if (!usageRecorded(env))
1382
+ return;
1383
+ try {
1384
+ const path = usagePath(env);
1385
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1386
+ appendFileSync(path, `${JSON.stringify(entry)}
1387
+ `, { mode: 384 });
1388
+ } catch {}
1389
+ }
1390
+
1391
+ // ../kit/src/cli.ts
1392
+ var LEVEL_OPTIONS = {
1393
+ ...OUTPUT_OPTIONS,
1394
+ help: { type: "boolean", short: "h", description: "show this help" }
1395
+ };
1396
+ var TOP_OPTIONS = {
1397
+ ...LEVEL_OPTIONS,
1398
+ version: { type: "boolean", short: "v", description: "print the version" },
1399
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1400
+ };
1401
+ function printError(prefix, message, hint, cause) {
1402
+ const colors = paint(process14.stderr);
1403
+ const styled = takesControlCodes(process14.stderr);
1404
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1405
+ const under = (label, text, tint) => text === undefined ? "" : `
1406
+ ${styled ? tint(label) : `${label}:`} ${text}`;
1407
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1408
+ }
1409
+ function printJsonError(message, hint, cause) {
1410
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1411
+ }
1412
+ function wantsJson(argv) {
1413
+ const end = argv.indexOf("--");
1414
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1415
+ }
1416
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
1417
+ if (error instanceof HelpShown)
1418
+ return 0;
1419
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1420
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1421
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1422
+ if (error instanceof Exit && error.code === 2)
1423
+ noteUsageError(error.message);
1424
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1425
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1426
+ return error instanceof Exit ? error.code : 1;
1427
+ }
1428
+ var COMPLETE = "__complete";
1429
+ var FILES = "__files__";
1430
+ async function completingOf(run) {
1431
+ completion.active = true;
1432
+ try {
1433
+ await run([]);
1434
+ } catch (error) {
1435
+ if (error instanceof Completing)
1436
+ return error;
1437
+ } finally {
1438
+ completion.active = false;
1169
1439
  }
1170
- add(line.slice(last));
1171
- return { text, styles: colored ? styles : undefined };
1440
+ return new Completing({});
1172
1441
  }
1173
- function lay(rows, searched) {
1174
- const parsed = rows.map((row) => row.cells.map(styled));
1175
- const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
1176
- return parsed.map((cells, at) => {
1177
- let text = "";
1178
- const styles = [];
1179
- let colored = false;
1180
- let searchEnd = 0;
1181
- for (const [column, cell] of cells.entries()) {
1182
- const last = column === cells.length - 1;
1183
- const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
1184
- text += shown;
1185
- colored ||= cell.styles !== undefined;
1186
- styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
1187
- if (column < searched)
1188
- searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
1189
- if (!last) {
1190
- const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
1191
- text += " ".repeat(pad);
1192
- styles.push(...repeat("", pad));
1193
- }
1194
- }
1195
- return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
1196
- });
1442
+ function candidateLine(candidate) {
1443
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
1197
1444
  }
1198
- function parseKeys(input, paste = { active: false }, ctrls = []) {
1199
- const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1200
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1201
- const wheel = MOUSE.exec(sequence)?.[1];
1202
- if (wheel !== undefined)
1203
- return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1204
- const named = codes.get(sequence);
1205
- const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1206
- if (sequence === PASTE_START || sequence === PASTE_END) {
1207
- paste.active = sequence === PASTE_START;
1208
- return [];
1445
+ function positionalBeingTyped(before, { options, positionals }) {
1446
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1447
+ const typed = [];
1448
+ let at = 0;
1449
+ while (at < before.length) {
1450
+ const word = before[at];
1451
+ if (word === "--") {
1452
+ typed.push(...before.slice(at + 1));
1453
+ break;
1209
1454
  }
1210
- if (paste.active && (sequence === "\r" || sequence === `
1211
- `))
1212
- return [];
1213
- if (key !== undefined)
1214
- return [key];
1215
- return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1216
- });
1455
+ if (!word.startsWith("-"))
1456
+ typed.push(word);
1457
+ else if (takesValue(word))
1458
+ at++;
1459
+ at++;
1460
+ }
1461
+ const last = positionals.at(-1);
1462
+ if (typed.length < positionals.length)
1463
+ return { name: positionals[typed.length], typed };
1464
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1217
1465
  }
1218
- function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1219
- const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, caret: [...query].length, killed: "", chained: false, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1220
- return withRows(state, rows);
1466
+ async function leafCandidates(run, words) {
1467
+ const completing = await completingOf(run);
1468
+ if ((words.at(-1) ?? "").startsWith("-"))
1469
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1470
+ const flag = words.at(-2);
1471
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1472
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1473
+ if (option?.type === "string") {
1474
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1475
+ return values === undefined ? [FILES] : values.map(candidateLine);
1476
+ }
1477
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1478
+ return values === undefined ? [FILES] : values.map(candidateLine);
1221
1479
  }
1222
- function withRows(state, rows, header = state.header) {
1223
- const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1224
- const laid = lay(cells, state.searched);
1225
- const searchable = laid.map((row) => row.searchable);
1226
- const matches = rank(state.query, searchable);
1227
- return { ...state, rows: cells, items: laid.map((row) => row.text), styles: laid.map((row) => row.styles), searchable, header, matches, cursor: Math.max(0, Math.min(matches.length - 1, state.cursor)), marked: new Set };
1480
+ var COMPLETIONS = "--completions";
1481
+ function flagValue([flag = "", ...rest]) {
1482
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1228
1483
  }
1229
- function withQuery(state, key) {
1230
- const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1231
- return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1484
+ function printCompletionScript(name, args) {
1485
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1486
+ if (shell === undefined || args.length !== 1) {
1487
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1488
+ return 2;
1489
+ }
1490
+ console.log(completionScript(shell, [name]).trimEnd());
1491
+ return 0;
1232
1492
  }
1233
- function move(state, by) {
1234
- return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
1493
+ async function printCandidates(found) {
1494
+ for (const line of await found)
1495
+ console.log(line);
1496
+ return 0;
1235
1497
  }
1236
- function highlighted(state) {
1237
- return state.matches[state.cursor]?.index;
1498
+ function packageVersion(entry = Bun.main) {
1499
+ let resolved = entry;
1500
+ try {
1501
+ resolved = realpathSync2(entry);
1502
+ } catch {}
1503
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1504
+ try {
1505
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1506
+ if (typeof version === "string")
1507
+ return version;
1508
+ } catch {}
1509
+ if (dirname3(dir) === dir)
1510
+ return "0.0.0";
1511
+ }
1238
1512
  }
1239
- function press(state, key) {
1240
- if (state.done !== undefined)
1241
- return state;
1242
- if (state.chained && endsKills(key))
1243
- state = { ...state, chained: false };
1244
- if (state.help)
1245
- return { ...state, help: false };
1246
- if (typeof key === "object") {
1247
- if ("text" in key)
1248
- return withQuery(state, key);
1249
- return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1513
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1514
+ const answered = await askpassClient(argv);
1515
+ if (answered !== undefined)
1516
+ return answered;
1517
+ if (argv[0] === COMPLETE)
1518
+ return printCandidates(leafCandidates(run, argv.slice(1)));
1519
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1520
+ return printCompletionScript(name, flagValue(argv));
1521
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1522
+ console.log(version ?? packageVersion());
1523
+ return 0;
1250
1524
  }
1251
- if (isEditKey(key))
1252
- return withQuery(state, key);
1253
- switch (key) {
1254
- case "up":
1255
- return move(state, -1);
1256
- case "down":
1257
- return move(state, 1);
1258
- case "pageup":
1259
- return move(state, -state.page);
1260
- case "pagedown":
1261
- return move(state, state.page);
1262
- case "home":
1263
- return move(state, -state.matches.length);
1264
- case "end":
1265
- return move(state, state.matches.length);
1266
- case "cancel":
1267
- return { ...state, done: "cancel" };
1268
- case "help":
1269
- return { ...state, help: true };
1270
- case "suspend":
1271
- return state;
1272
- case "enter":
1273
- return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1274
- case "tab": {
1275
- const at = highlighted(state);
1276
- if (!state.multi || at === undefined)
1277
- return state;
1278
- const marked = new Set(state.marked);
1279
- if (!marked.delete(at))
1280
- marked.add(at);
1281
- return move({ ...state, marked }, 1);
1282
- }
1525
+ let code;
1526
+ const started = performance.now();
1527
+ try {
1528
+ code = await run(argv);
1529
+ } catch (error) {
1530
+ code = reportThrown(name, error, redact, wantsJson(argv));
1283
1531
  }
1532
+ notifyEnd(name, code, performance.now() - started);
1533
+ if (usage !== false) {
1534
+ try {
1535
+ recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
1536
+ } catch {}
1537
+ }
1538
+ return code;
1284
1539
  }
1285
- function chosen(state) {
1286
- if (state.marked.size > 0)
1287
- return state.rows.filter((_, index) => state.marked.has(index));
1288
- const at = highlighted(state);
1289
- return at === undefined ? [] : [state.rows[at]];
1290
- }
1540
+
1541
+ // ../kit/src/index.ts
1542
+ init_config();
1543
+
1544
+ // ../kit/src/excerpt.ts
1545
+ init_text();
1546
+
1547
+ // ../kit/src/index.ts
1548
+ init_folders();
1549
+ init_format();
1550
+
1551
+ // ../kit/src/git.ts
1552
+ init_args();
1553
+ // ../kit/src/limit.ts
1554
+ init_args();
1555
+
1556
+ // ../kit/src/index.ts
1557
+ init_mode();
1558
+
1559
+ // ../kit/src/report.ts
1560
+ init_style();
1561
+ init_text();
1562
+ // ../kit/src/secrets.ts
1563
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1564
+ // ../kit/src/sessions.ts
1565
+ var {Glob } = globalThis.Bun;
1566
+ var SESSION_FILES = new Glob("*.json");
1567
+ var ACCOUNT_DIRS = new Glob("*/sessions");
1568
+
1569
+ // ../kit/src/index.ts
1570
+ init_style();
1571
+ init_text();
1572
+ init_theme();
1573
+ init_user_config();
1574
+
1575
+ // ../kit/src/watch.ts
1576
+ init_args();
1577
+ init_input();
1578
+ init_style();
1579
+ // ../kit/src/workspace-root.ts
1580
+ init_user_config();
1581
+ // ../kit/src/picker.ts
1582
+ init_folders();
1583
+ init_state();
1291
1584
 
1292
1585
  // ../kit/src/picker/terminal.ts
1586
+ init_args();
1587
+ init_job();
1588
+ init_redraw();
1589
+ init_style();
1293
1590
  import { openSync } from "fs";
1294
- import process17 from "process";
1591
+ import process18 from "process";
1295
1592
  import tty from "tty";
1296
1593
 
1297
- // ../kit/src/job.ts
1298
- import process15 from "process";
1299
- function stopJob() {
1300
- process15.kill(0, "SIGTSTP");
1301
- }
1302
-
1303
- // ../kit/src/redraw.ts
1304
- var SYNC_START = "\x1B[?2026h";
1305
- var SYNC_END = "\x1B[?2026l";
1306
- function overwrite(lines, columns) {
1307
- return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1308
- `);
1309
- }
1310
-
1311
1594
  // ../kit/src/picker/preview.ts
1312
- import process16 from "process";
1595
+ import process17 from "process";
1313
1596
 
1314
1597
  // ../kit/src/shell.ts
1315
1598
  var SEPARATORS = new Set([`
@@ -1378,7 +1661,7 @@ async function runPreview(template, line, signal, hidden = []) {
1378
1661
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1379
1662
  const stop = () => {
1380
1663
  try {
1381
- process16.kill(-proc.pid, "SIGKILL");
1664
+ process17.kill(-proc.pid, "SIGKILL");
1382
1665
  } catch {
1383
1666
  proc.kill();
1384
1667
  }
@@ -1403,7 +1686,12 @@ ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe",
1403
1686
  return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
1404
1687
  }
1405
1688
 
1689
+ // ../kit/src/picker/terminal.ts
1690
+ init_state();
1691
+
1406
1692
  // ../kit/src/picker/view.ts
1693
+ init_line();
1694
+ init_state();
1407
1695
  var MIN_HEIGHT = 4;
1408
1696
  var PREVIEW_MIN_COLUMNS = 80;
1409
1697
  var PREVIEW_MIN_ROWS = 10;
@@ -1537,7 +1825,7 @@ function openTerminal() {
1537
1825
  return fail("no terminal to read keys from (/dev/tty)");
1538
1826
  }
1539
1827
  const keys = Bun.file("/dev/tty").stream().getReader();
1540
- const out = process17.stderr;
1828
+ const out = process18.stderr;
1541
1829
  let resize;
1542
1830
  async function read(onChunk) {
1543
1831
  const decoder = new TextDecoder;
@@ -1726,9 +2014,9 @@ async function select(rows, settings, terminal = openTerminal()) {
1726
2014
  const ended = new Promise((resolve) => {
1727
2015
  finish = resolve;
1728
2016
  });
1729
- process17.once("exit", restore);
2017
+ process18.once("exit", restore);
1730
2018
  for (const signal of SIGNALS)
1731
- process17.once(signal, stop);
2019
+ process18.once(signal, stop);
1732
2020
  try {
1733
2021
  terminal.write(`${PASTE_ON}${MOUSE_ON}`);
1734
2022
  terminal.listen(onChunk, () => draw(true));
@@ -1741,8 +2029,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1741
2029
  await ended;
1742
2030
  } finally {
1743
2031
  for (const signal of SIGNALS)
1744
- process17.off(signal, stop);
1745
- process17.off("exit", restore);
2032
+ process18.off(signal, stop);
2033
+ process18.off("exit", restore);
1746
2034
  restore();
1747
2035
  }
1748
2036
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -1754,6 +2042,10 @@ async function previewOf(preview, hidden, signal) {
1754
2042
  return [error instanceof Error ? error.message : String(error)];
1755
2043
  }
1756
2044
  }
2045
+
2046
+ // ../kit/src/picker.ts
2047
+ init_score();
2048
+
1757
2049
  // src/fields.ts
1758
2050
  var INDEX = /^-?\d+$/;
1759
2051
  function splitFields(line, delimiter) {
@@ -1795,14 +2087,10 @@ function pickFields(line, select, delimiter) {
1795
2087
  // src/pick.ts
1796
2088
  var USAGE = `pick [options]: a fuzzy selector, the lines on stdin in, the chosen one on stdout out
1797
2089
 
1798
- Type to filter: the query matches as a subsequence, best matches first (a word start, a run of characters or a prefix scores higher; a lowercase query ignores case, an uppercase letter makes it exact). Up and down or ctrl-p and ctrl-n move, enter picks, esc and ctrl-c cancel, left, right, ctrl-a and ctrl-e move in the query (ctrl or alt for a word), ctrl-u and ctrl-k erase back to its start and on to its end, ctrl-y puts back what they erased, ctrl-z suspends, ctrl-/ or f1 shows the keys.
1799
- The keys are read from the terminal and the selector is drawn on stderr, so \`pick\` in a pipe or a command substitution prints only the choice. With --multi, tab marks the highlighted line and enter prints the marked lines in input order (the highlighted one when none is marked).
1800
- --preview runs a command for the highlighted line, \`{}\` standing for it shell-quoted, in a pane on the right when the terminal is at least 80 columns wide; its output is cut at 64 KiB and 200 lines.
1801
-
1802
- --delimiter splits each line into fields (a regex, whitespace by default), --nth names the fields the query is matched against and --with-nth the ones shown, in fzf's syntax: 1-based, \`-1\` the last, \`2..\`, \`..3\`, \`2..4\`, comma-separated. The printed line is always the whole input line. --read0 reads NUL-separated lines and --print0 ends each printed one with NUL.
1803
- --filter takes the query and prints every match best first with no terminal; --select-1 prints the only match without opening the selector, --exit-0 exits 1 at once when nothing matches.
1804
-
1805
- Without a terminal on stderr there is nobody to choose: it prints the best line the query matches, as the selector would rank it, or every match best first with --multi.`;
2090
+ Type to filter: the query matches as a subsequence, best matches first, and ctrl-/ or f1 shows the keys; enter picks, esc and ctrl-c cancel.
2091
+ The keys are read from the terminal and the selector is drawn on stderr, so \`pick\` in a pipe or a command substitution prints only the choice. With --multi, tab marks lines and enter prints them in input order.
2092
+ --delimiter, --nth and --with-nth split lines into fields in fzf's syntax, and the printed line is always the whole input line.
2093
+ Without a terminal on stderr it prints the best match, or every match with --multi.`;
1806
2094
  var EXITS = [[0, "it printed a choice"], [1, "nothing matches or there are no lines"], [2, "a usage error"], [130, "cancelled"]];
1807
2095
  var OPTIONS = {
1808
2096
  multi: { type: "boolean", short: "m", description: "tab marks several lines, enter prints them" },
@@ -1825,7 +2113,7 @@ function print(chosen, json, end) {
1825
2113
  if (json)
1826
2114
  printJson({ picked: chosen });
1827
2115
  else
1828
- process18.stdout.write(chosen.map((line) => line + end).join(""));
2116
+ process19.stdout.write(chosen.map((line) => line + end).join(""));
1829
2117
  }
1830
2118
  async function main(args) {
1831
2119
  const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, replaces: "fzf for a quick choice in a pipe, select in a shell script", examples: ["git branch --format='%(refname:short)' | pick", "ls | pick --multi --preview 'head -20 {}'", "git branch | pick --filter main # every match, best first, no terminal", "ps aux | pick --with-nth 2,11.. --nth 11.. # show some fields, search others"] });
@@ -1834,7 +2122,7 @@ async function main(args) {
1834
2122
  const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
1835
2123
  if (height === undefined)
1836
2124
  badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
1837
- if (process18.stdin.isTTY)
2125
+ if (process19.stdin.isTTY)
1838
2126
  badUsage("pipe the lines to pick on stdin");
1839
2127
  const fieldsOf = (name) => {
1840
2128
  const text = values[name];
@@ -1860,9 +2148,9 @@ async function main(args) {
1860
2148
  const json = values.json === true;
1861
2149
  const searched = lines.map((line) => nth === undefined ? line : pickFields(line, nth, delimiter));
1862
2150
  const matching = rank(query, searched).map(({ index }) => lines[index]);
1863
- if (matching.length === 0 && (values["exit-0"] === true || values.filter !== undefined || !process18.stderr.isTTY))
2151
+ if (matching.length === 0 && (values["exit-0"] === true || values.filter !== undefined || !process19.stderr.isTTY))
1864
2152
  return 1;
1865
- if (values.filter !== undefined || !process18.stderr.isTTY) {
2153
+ if (values.filter !== undefined || !process19.stderr.isTTY) {
1866
2154
  print(values.multi === true || values.filter !== undefined ? matching : matching.slice(0, 1), json, end);
1867
2155
  return 0;
1868
2156
  }
@@ -1877,4 +2165,4 @@ async function main(args) {
1877
2165
  print(picked.rows.map((row) => row.hidden[0]), json, end);
1878
2166
  return 0;
1879
2167
  }
1880
- process18.exitCode = await runMain({ name: "pick", run: main });
2168
+ process19.exitCode = await runMain({ name: "pick", run: main });