@kaynooo/cli-pick 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/dist/pick.js +100 -52
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @kaynooo/cli-pick
2
2
 
3
- `pick` is a fuzzy selector in the colours of the other @kaynooo CLIs: lines on stdin, the chosen one on stdout. It is for a person at a terminal, not for a Claude Code session, which has no terminal to answer it.
3
+ `pick` is a fuzzy selector in the colours of the other @kaynooo CLIs: lines on stdin, the chosen one on stdout. It is for a person at a terminal, not for a Claude Code session, which has no terminal to answer it; without a terminal on stderr it prints the first line containing `--query` (case-insensitive, every one with `--multi`) and exits 1 when none does.
4
4
 
5
5
  ```sh
6
6
  bun add -g @kaynooo/cli-pick
package/dist/pick.js CHANGED
@@ -2,13 +2,31 @@
2
2
  // @bun
3
3
 
4
4
  // src/pick.ts
5
- import process13 from "process";
5
+ import process14 from "process";
6
6
  // ../kit/src/args.ts
7
- import process7 from "process";
7
+ import process8 from "process";
8
8
  import { parseArgs } from "util";
9
9
 
10
+ // ../kit/src/mode.ts
11
+ import process2 from "process";
12
+ var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
13
+ var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
14
+ function isSet(value) {
15
+ return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
16
+ }
17
+ function outputMode(stream = process2.stdout, env = process2.env) {
18
+ const chosen = env.KIT_MODE;
19
+ if (chosen !== undefined && MODES.has(chosen))
20
+ return chosen;
21
+ if (AGENT_VARIABLES.some((name) => isSet(env[name])))
22
+ return "agent";
23
+ if (stream.isTTY === true)
24
+ return "terminal";
25
+ return isSet(env.CI) ? "ci" : "pipe";
26
+ }
27
+
10
28
  // ../kit/src/style.ts
11
- import process5 from "process";
29
+ import process6 from "process";
12
30
 
13
31
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
14
32
  function x(s) {
@@ -275,13 +293,13 @@ var t = le();
275
293
  import { existsSync as existsSync2, readFileSync, statSync } from "fs";
276
294
  import { homedir as homedir2 } from "os";
277
295
  import { join as join3, resolve as resolve2 } from "path";
278
- import process4 from "process";
296
+ import process5 from "process";
279
297
 
280
298
  // ../kit/src/config.ts
281
299
  import { existsSync } from "fs";
282
300
  import { dirname, join, resolve } from "path";
283
- import process2 from "process";
284
- function findUp(names, from = process2.cwd(), stop = () => false) {
301
+ import process3 from "process";
302
+ function findUp(names, from = process3.cwd(), stop = () => false) {
285
303
  const wanted = typeof names === "string" ? [names] : names;
286
304
  for (let dir = resolve(from);; dir = dirname(dir)) {
287
305
  const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
@@ -295,9 +313,9 @@ function findUp(names, from = process2.cwd(), stop = () => false) {
295
313
  // ../kit/src/user-config.ts
296
314
  import { homedir } from "os";
297
315
  import { join as join2 } from "path";
298
- import process3 from "process";
316
+ import process4 from "process";
299
317
  function configBase(where = {}) {
300
- const xdg = where.xdg ?? (where.home === undefined ? process3.env.XDG_CONFIG_HOME : undefined);
318
+ const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
301
319
  return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
302
320
  }
303
321
  function userConfigPath(bin, where = {}) {
@@ -330,10 +348,30 @@ function isColorSpec(spec) {
330
348
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
331
349
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
332
350
  }
333
- function tinted(colors, spec) {
351
+ var CUBE = [0, 95, 135, 175, 215, 255];
352
+ function cubeLevel(channel) {
353
+ return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
354
+ }
355
+ function nearest256(hex) {
356
+ const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
357
+ const levels = rgb.map(cubeLevel);
358
+ const cube = levels.map((level) => CUBE[level]);
359
+ const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
360
+ const greyValue = 8 + grey * 10;
361
+ const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
362
+ return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
363
+ }
364
+ function hasTrueColor(env) {
365
+ return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
366
+ }
367
+ function tinted(colors, spec, env = process5.env) {
334
368
  if (typeof spec === "number")
335
369
  return colors.ansi256(spec);
336
- return spec.trim().split(SPACES).reduce((chain, token) => HEX.test(token) ? chain.hex(token) : chain[token] ?? chain, colors);
370
+ return spec.trim().split(SPACES).reduce((chain, token) => {
371
+ if (HEX.test(token))
372
+ return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
373
+ return chain[token] ?? chain;
374
+ }, colors);
337
375
  }
338
376
  function isRecord(value) {
339
377
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -417,7 +455,7 @@ function warnOnce(message) {
417
455
  function isPath(chosen) {
418
456
  return chosen.includes("/") || chosen.endsWith(".json");
419
457
  }
420
- function loadTheme({ env = process4.env, from = process4.cwd(), home = homedir2(), warn = warnOnce } = {}) {
458
+ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
421
459
  const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
422
460
  const sources = [];
423
461
  const chosen = env.KIT_THEME ?? "";
@@ -447,7 +485,7 @@ function loadTheme({ env = process4.env, from = process4.cwd(), home = homedir2(
447
485
  var current;
448
486
  var currentKey = "";
449
487
  function activeTheme() {
450
- const key = `${process4.cwd()}\x00${process4.env.KIT_THEME ?? ""}\x00${process4.env.XDG_CONFIG_HOME ?? ""}`;
488
+ const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
451
489
  if (current === undefined || key !== currentKey) {
452
490
  current = loadTheme();
453
491
  currentKey = key;
@@ -456,20 +494,20 @@ function activeTheme() {
456
494
  }
457
495
 
458
496
  // ../kit/src/style.ts
459
- function takesControlCodes(stream, env = process5.env) {
460
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
497
+ function takesControlCodes(stream, env = process6.env) {
498
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
461
499
  }
462
- function paint(stream, env = process5.env) {
500
+ function paint(stream, env = process6.env) {
463
501
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
464
502
  }
465
- function role(name, stream, env = process5.env) {
503
+ function role(name, stream, env = process6.env) {
466
504
  const colors = paint(stream, env);
467
- return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name]) : colors;
505
+ return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
468
506
  }
469
507
  var STATUS_WORDS = {
470
508
  passed: ["passed", "success", "succeeded", "ok"],
471
509
  failed: ["failed", "failure", "error", "errored"],
472
- running: ["running", "in_progress", "started"],
510
+ running: ["running", "in_progress", "started", "holding"],
473
511
  queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
474
512
  skipped: ["skipped", "cancelled", "canceled", "manual"]
475
513
  };
@@ -483,27 +521,27 @@ function upTo(text, separator) {
483
521
  var ESCAPE = String.fromCharCode(27);
484
522
 
485
523
  // ../kit/src/help.ts
486
- import process6 from "process";
524
+ import process7 from "process";
487
525
  var OPTIONAL = /\[[^\]]+\]/g;
488
526
  var USAGE_PREFIX = /^usage:\s*/i;
489
527
  var FULL_STOP = /\.$/;
490
- function usageLine(usage, colors = paint(process6.stdout)) {
528
+ function usageLine(usage, colors = paint(process7.stdout)) {
491
529
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
492
530
  }
493
- function helpText(usage, options, colors = paint(process6.stdout), { examples = [], replaces, exits = [] } = {}) {
531
+ function helpText(usage, options, colors = paint(process7.stdout), { examples = [], replaces, exits = [] } = {}) {
494
532
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
495
533
  `);
496
534
  }
497
- function exitRows(exits, colors = paint(process6.stdout)) {
535
+ function exitRows(exits, colors = paint(process7.stdout)) {
498
536
  if (exits.length === 0)
499
537
  return [];
500
538
  const width = Math.max(...exits.map(([code]) => String(code).length));
501
539
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
502
540
  }
503
- function replacesRows(replaces, colors = paint(process6.stdout)) {
504
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
541
+ function replacesRows(replaces, colors = paint(process7.stdout)) {
542
+ return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
505
543
  }
506
- function wantsHelpJson(env = process6.env) {
544
+ function wantsHelpJson(env = process7.env) {
507
545
  return env.KIT_HELP === "json";
508
546
  }
509
547
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -522,12 +560,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
522
560
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
523
561
  };
524
562
  }
525
- function exampleRows(examples, colors = paint(process6.stdout)) {
526
- if (examples.length === 0)
563
+ function exampleRows(examples, colors = paint(process7.stdout)) {
564
+ if (examples.length === 0 || outputMode() === "agent")
527
565
  return [];
528
566
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
529
567
  }
530
- function optionRows(options, colors = paint(process6.stdout)) {
568
+ function optionRows(options, colors = paint(process7.stdout)) {
531
569
  const rows = Object.entries(options).map(([name, option]) => {
532
570
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
533
571
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -604,7 +642,7 @@ var OUTPUT_OPTIONS = {
604
642
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
605
643
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
606
644
  };
607
- function applyOutput(color, plain, env = process7.env) {
645
+ function applyOutput(color, plain, env = process8.env) {
608
646
  const when = plain === true ? "never" : color ?? "auto";
609
647
  if (when === "auto")
610
648
  return;
@@ -781,13 +819,13 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
781
819
  // ../kit/src/cli.ts
782
820
  import { readFileSync as readFileSync2, realpathSync } from "fs";
783
821
  import { dirname as dirname3, join as join5 } from "path";
784
- import process9 from "process";
822
+ import process10 from "process";
785
823
 
786
824
  // ../kit/src/usage.ts
787
825
  import { appendFileSync, mkdirSync } from "fs";
788
826
  import { homedir as homedir3 } from "os";
789
827
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
790
- import process8 from "process";
828
+ import process9 from "process";
791
829
 
792
830
  // ../kit/src/logs.ts
793
831
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -801,14 +839,14 @@ var usageError;
801
839
  function noteUsageError(message) {
802
840
  usageError = message;
803
841
  }
804
- function stateHome(env = process8.env) {
842
+ function stateHome(env = process9.env) {
805
843
  const dir = env.XDG_STATE_HOME;
806
844
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
807
845
  }
808
- function usagePath(env = process8.env) {
846
+ function usagePath(env = process9.env) {
809
847
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
810
848
  }
811
- function usageRecorded(env = process8.env) {
849
+ function usageRecorded(env = process9.env) {
812
850
  const off = env.KAYNOOO_CLI_NO_USAGE;
813
851
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
814
852
  }
@@ -822,7 +860,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
822
860
  usageError = undefined;
823
861
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
824
862
  }
825
- function recordUsage(entry, env = process8.env) {
863
+ function recordUsage(entry, env = process9.env) {
826
864
  if (!usageRecorded(env))
827
865
  return;
828
866
  try {
@@ -840,8 +878,8 @@ var LEVEL_OPTIONS = {
840
878
  };
841
879
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
842
880
  function printError(prefix, message, hint, cause) {
843
- const colors = paint(process9.stderr);
844
- const styled = takesControlCodes(process9.stderr);
881
+ const colors = paint(process10.stderr);
882
+ const styled = takesControlCodes(process10.stderr);
845
883
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
846
884
  const under = (label, text, tint) => text === undefined ? "" : `
847
885
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -934,7 +972,7 @@ function packageVersion(entry = Bun.main) {
934
972
  return "0.0.0";
935
973
  }
936
974
  }
937
- async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
975
+ async function runMain({ name, version, run, redact, usage }, argv = process10.argv.slice(2)) {
938
976
  if (argv[0] === COMPLETE)
939
977
  return printCandidates(leafCandidates(run, argv.slice(1)));
940
978
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1200,11 +1238,11 @@ function chosen(state) {
1200
1238
 
1201
1239
  // ../kit/src/picker/terminal.ts
1202
1240
  import { openSync } from "fs";
1203
- import process12 from "process";
1241
+ import process13 from "process";
1204
1242
  import tty from "tty";
1205
1243
 
1206
1244
  // ../kit/src/picker/preview.ts
1207
- import process11 from "process";
1245
+ import process12 from "process";
1208
1246
 
1209
1247
  // ../kit/src/shell.ts
1210
1248
  var SEPARATORS = new Set([`
@@ -1273,7 +1311,7 @@ async function runPreview(template, line, signal, hidden = []) {
1273
1311
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1274
1312
  const stop = () => {
1275
1313
  try {
1276
- process11.kill(-proc.pid, "SIGKILL");
1314
+ process12.kill(-proc.pid, "SIGKILL");
1277
1315
  } catch {
1278
1316
  proc.kill();
1279
1317
  }
@@ -1405,7 +1443,7 @@ function openTerminal() {
1405
1443
  } catch {
1406
1444
  return fail("no terminal to read keys from (/dev/tty)");
1407
1445
  }
1408
- const out = process12.stderr;
1446
+ const out = process13.stderr;
1409
1447
  let resize;
1410
1448
  return {
1411
1449
  get columns() {
@@ -1548,9 +1586,9 @@ async function select(rows, settings, terminal = openTerminal()) {
1548
1586
  const ended = new Promise((resolve) => {
1549
1587
  finish = resolve;
1550
1588
  });
1551
- process12.once("exit", restore);
1589
+ process13.once("exit", restore);
1552
1590
  for (const signal of SIGNALS)
1553
- process12.once(signal, stop);
1591
+ process13.once(signal, stop);
1554
1592
  try {
1555
1593
  terminal.write(PASTE_ON);
1556
1594
  terminal.listen(onChunk, () => draw(true));
@@ -1563,8 +1601,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1563
1601
  await ended;
1564
1602
  } finally {
1565
1603
  for (const signal of SIGNALS)
1566
- process12.off(signal, stop);
1567
- process12.off("exit", restore);
1604
+ process13.off(signal, stop);
1605
+ process13.off("exit", restore);
1568
1606
  restore();
1569
1607
  }
1570
1608
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -1587,7 +1625,9 @@ Type to filter: the query matches as a subsequence, best matches first (a word s
1587
1625
  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).
1588
1626
  --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.
1589
1627
 
1590
- Exits 0 when it printed a choice, 1 when cancelled or there are no lines, 2 on a usage error or without a terminal.`;
1628
+ Without a terminal on stderr there is nobody to choose: it prints the first line containing the query (case-insensitive), every one with --multi.
1629
+
1630
+ Exits 0 when it printed a choice, 1 when cancelled, nothing matches or there are no lines, 2 on a usage error.`;
1591
1631
  var OPTIONS = {
1592
1632
  multi: { type: "boolean", short: "m", description: "tab marks several lines, enter prints them" },
1593
1633
  prompt: { type: "string", short: "p", description: "the prompt before the query (> )" },
@@ -1602,20 +1642,28 @@ async function main(args) {
1602
1642
  const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
1603
1643
  if (height === undefined)
1604
1644
  badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
1605
- if (!process13.stderr.isTTY)
1606
- fail("pick draws on stderr and it is not a terminal");
1607
- if (process13.stdin.isTTY)
1645
+ if (process14.stdin.isTTY)
1608
1646
  badUsage("pipe the lines to pick on stdin");
1609
1647
  const lines = (await Bun.stdin.text()).split(`
1610
1648
  `).filter((line) => line !== "");
1611
1649
  if (lines.length === 0)
1612
1650
  fail("nothing to pick from", 1);
1651
+ if (!process14.stderr.isTTY) {
1652
+ const query = (values.query ?? "").toLowerCase();
1653
+ const matching = lines.filter((line) => line.toLowerCase().includes(query));
1654
+ if (matching.length === 0)
1655
+ return 1;
1656
+ process14.stdout.write(`${(values.multi === true ? matching : matching.slice(0, 1)).join(`
1657
+ `)}
1658
+ `);
1659
+ return 0;
1660
+ }
1613
1661
  const picked = await choose(lines, { multi: values.multi === true, prompt: values.prompt ?? "> ", query: values.query ?? "", height, preview: values.preview });
1614
1662
  if (picked === undefined)
1615
1663
  return 1;
1616
- process13.stdout.write(`${picked.join(`
1664
+ process14.stdout.write(`${picked.join(`
1617
1665
  `)}
1618
1666
  `);
1619
1667
  return 0;
1620
1668
  }
1621
- process13.exitCode = await runMain({ name: "pick", run: main });
1669
+ process14.exitCode = await runMain({ name: "pick", run: main });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-pick",
3
3
  "type": "module",
4
- "version": "0.3.0",
4
+ "version": "0.4.0",
5
5
  "description": "pick: a themed fuzzy selector, lines on stdin, the chosen one on stdout.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -35,6 +35,6 @@
35
35
  "pick": "$npm_execpath src/pick.ts"
36
36
  },
37
37
  "devDependencies": {
38
- "@kaynooo/cli-kit": "0.22.0"
38
+ "@kaynooo/cli-kit": "0.23.0"
39
39
  }
40
40
  }