@kaynooo/cli-check 0.12.1 → 0.14.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.
package/dist/j-cli.js CHANGED
@@ -2,16 +2,16 @@
2
2
  // @bun
3
3
 
4
4
  // src/j-cli.ts
5
- import process16 from "process";
5
+ import process21 from "process";
6
6
  // ../kit/src/args.ts
7
- import process6 from "process";
7
+ import process9 from "process";
8
8
  import { parseArgs } from "util";
9
9
 
10
10
  // ../kit/src/format.ts
11
- import process3 from "process";
11
+ import process6 from "process";
12
12
 
13
13
  // ../kit/src/style.ts
14
- import process2 from "process";
14
+ import process5 from "process";
15
15
 
16
16
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
17
17
  function x(s) {
@@ -274,36 +274,232 @@ function le(i = {}) {
274
274
  }
275
275
  var t = le();
276
276
 
277
- // ../kit/src/style.ts
278
- var MARKS = {
279
- ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
280
- warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
281
- problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
282
- note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
277
+ // ../kit/src/theme.ts
278
+ import { existsSync as existsSync2, readFileSync, statSync } from "fs";
279
+ import { homedir as homedir2 } from "os";
280
+ import { join as join3, resolve as resolve2 } from "path";
281
+ import process4 from "process";
282
+
283
+ // ../kit/src/config.ts
284
+ import { existsSync } from "fs";
285
+ import { dirname, join, resolve } from "path";
286
+ import process2 from "process";
287
+ function findUp(names, from = process2.cwd(), stop = () => false) {
288
+ const wanted = typeof names === "string" ? [names] : names;
289
+ for (let dir = resolve(from);; dir = dirname(dir)) {
290
+ const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
291
+ if (found !== undefined)
292
+ return found;
293
+ if (stop(dir) || dirname(dir) === dir)
294
+ return;
295
+ }
296
+ }
297
+
298
+ // ../kit/src/user-config.ts
299
+ import { homedir } from "os";
300
+ import { join as join2 } from "path";
301
+ import process3 from "process";
302
+ function configBase(where = {}) {
303
+ const xdg = where.xdg ?? (where.home === undefined ? process3.env.XDG_CONFIG_HOME : undefined);
304
+ return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
305
+ }
306
+ function userConfigPath(bin, where = {}) {
307
+ return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
308
+ }
309
+
310
+ // ../kit/src/theme.ts
311
+ var DEFAULT = {
312
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
313
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501" },
314
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
315
+ bins: {}
283
316
  };
284
- function takesControlCodes(stream, env = process2.env) {
317
+ var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
318
+ var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
319
+ var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#" };
320
+ var PRESETS = {
321
+ default: {},
322
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"] },
323
+ mono: { colors: MONO, accents: ["bold"] },
324
+ ascii: { glyphs: ASCII }
325
+ };
326
+ 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"]);
327
+ var HEX = /^#[0-9a-f]{6}$/i;
328
+ var CONTROL = /\p{Cc}/u;
329
+ var MAX_FILE_BYTES = 64 * 1024;
330
+ var SPACES = /\s+/;
331
+ function isColorSpec(spec) {
332
+ if (typeof spec === "number")
333
+ return Number.isInteger(spec) && spec >= 0 && spec <= 255;
334
+ return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
335
+ }
336
+ function tinted(colors, spec) {
337
+ if (typeof spec === "number")
338
+ return colors.ansi256(spec);
339
+ return spec.trim().split(SPACES).reduce((chain, token) => HEX.test(token) ? chain.hex(token) : chain[token] ?? chain, colors);
340
+ }
341
+ function isRecord(value) {
342
+ return typeof value === "object" && value !== null && !Array.isArray(value);
343
+ }
344
+ function readThemeFile(path, warn) {
345
+ try {
346
+ const stat = statSync(path, { throwIfNoEntry: false });
347
+ if (stat === undefined)
348
+ return;
349
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
350
+ warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
351
+ return;
352
+ }
353
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
354
+ if (isRecord(parsed))
355
+ return parsed;
356
+ warn(`${path} is not a JSON object, theme ignored`);
357
+ } catch (error) {
358
+ warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
359
+ }
360
+ return;
361
+ }
362
+ function applyPreset(theme, name, warn, where) {
363
+ if (name === undefined)
364
+ return;
365
+ if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
366
+ warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
367
+ return;
368
+ }
369
+ const preset = PRESETS[name];
370
+ Object.assign(theme.colors, preset.colors);
371
+ Object.assign(theme.glyphs, preset.glyphs);
372
+ if (preset.accents !== undefined)
373
+ theme.accents = [...preset.accents];
374
+ return name;
375
+ }
376
+ function applyFile(theme, file, where, warn) {
377
+ if (isRecord(file.colors)) {
378
+ for (const [key, value] of Object.entries(file.colors)) {
379
+ if (!Object.hasOwn(DEFAULT.colors, key))
380
+ warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
381
+ else if (!isColorSpec(value))
382
+ warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
383
+ else
384
+ theme.colors[key] = value;
385
+ }
386
+ }
387
+ if (isRecord(file.glyphs)) {
388
+ for (const [key, value] of Object.entries(file.glyphs)) {
389
+ if (!Object.hasOwn(DEFAULT.glyphs, key))
390
+ warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
391
+ else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
392
+ warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
393
+ else
394
+ theme.glyphs[key] = value;
395
+ }
396
+ }
397
+ if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
398
+ theme.accents = [...file.accents];
399
+ else if (file.accents !== undefined)
400
+ warn(`${where}: accents must be a non-empty list of colours`);
401
+ if (isRecord(file.bins)) {
402
+ for (const [bin, value] of Object.entries(file.bins)) {
403
+ if (isColorSpec(value))
404
+ theme.bins[bin] = value;
405
+ else
406
+ warn(`${where}: bin ${bin} has no valid colour`);
407
+ }
408
+ }
409
+ }
410
+ function endsWalk(home) {
411
+ return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
412
+ }
413
+ var warned = new Set;
414
+ function warnOnce(message) {
415
+ if (warned.has(message))
416
+ return;
417
+ warned.add(message);
418
+ console.error(`warning: theme ${message}`);
419
+ }
420
+ function isPath(chosen) {
421
+ return chosen.includes("/") || chosen.endsWith(".json");
422
+ }
423
+ function loadTheme({ env = process4.env, from = process4.cwd(), home = homedir2(), warn = warnOnce } = {}) {
424
+ const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
425
+ const sources = [];
426
+ const chosen = env.KIT_THEME ?? "";
427
+ const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
428
+ if (isPath(chosen))
429
+ wanted.push(resolve2(from, chosen));
430
+ const files = [];
431
+ for (const path of wanted) {
432
+ const file = path === undefined ? undefined : readThemeFile(path, warn);
433
+ if (path !== undefined && file !== undefined)
434
+ files.push({ path, file });
435
+ }
436
+ let preset = "default";
437
+ if (chosen !== "" && !isPath(chosen)) {
438
+ preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
439
+ } else {
440
+ const named = files.findLast(({ file }) => file.preset !== undefined);
441
+ if (named !== undefined)
442
+ preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
443
+ }
444
+ for (const { path, file } of files) {
445
+ applyFile(theme, file, path, warn);
446
+ sources.push(path);
447
+ }
448
+ return { theme, sources, preset };
449
+ }
450
+ var current;
451
+ var currentKey = "";
452
+ function activeTheme() {
453
+ const key = `${process4.cwd()}\x00${process4.env.KIT_THEME ?? ""}\x00${process4.env.XDG_CONFIG_HOME ?? ""}`;
454
+ if (current === undefined || key !== currentKey) {
455
+ current = loadTheme();
456
+ currentKey = key;
457
+ }
458
+ return current;
459
+ }
460
+
461
+ // ../kit/src/style.ts
462
+ var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:" };
463
+ function takesControlCodes(stream, env = process5.env) {
285
464
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
286
465
  }
287
- function paint(stream, env = process2.env) {
466
+ function paint(stream, env = process5.env) {
288
467
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
289
468
  }
290
- function marked(mark, text, stream, detail, env = process2.env) {
469
+ function marked(mark, text, stream, detail, env = process5.env) {
291
470
  const colors = paint(stream, env);
292
- const { symbol, word, paint: tint } = MARKS[mark];
293
- const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
471
+ let head = MARK_WORDS[mark];
472
+ if (takesControlCodes(stream, env)) {
473
+ const { theme } = activeTheme();
474
+ head = tinted(colors.bold, theme.colors[mark])(theme.glyphs[mark]);
475
+ }
294
476
  return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
295
477
  }
296
478
  function warn(text, detail) {
297
- console.error(marked("warn", text, process2.stderr, detail));
298
- }
299
- var STATUSES = {
300
- passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
301
- failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
302
- running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
303
- queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
304
- skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
479
+ console.error(marked("warn", text, process5.stderr, detail));
480
+ }
481
+ function role(name, stream, env = process5.env) {
482
+ const colors = paint(stream, env);
483
+ return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name]) : colors;
484
+ }
485
+ var STATUS_WORDS = {
486
+ passed: ["passed", "success", "succeeded", "ok"],
487
+ failed: ["failed", "failure", "error", "errored"],
488
+ running: ["running", "in_progress", "started"],
489
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
490
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
305
491
  };
306
- var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
492
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
493
+ function header(bin, context, stream, env = process5.env) {
494
+ if (!takesControlCodes(stream, env))
495
+ return "";
496
+ const colors = paint(stream, env);
497
+ const hash = [...bin].reduce((sum, char) => sum + char.charCodeAt(0), 0);
498
+ const { theme } = activeTheme();
499
+ const spec = theme.bins[bin] ?? theme.accents[hash % theme.accents.length];
500
+ const accent = tinted(typeof spec === "string" && spec.split(" ").includes("bold") ? colors : colors.bold, spec);
501
+ return `${accent(bin)}${context === undefined ? "" : colors.dim(` \u203A ${context}`)}`;
502
+ }
307
503
 
308
504
  // ../kit/src/format.ts
309
505
  var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
@@ -335,7 +531,7 @@ var ESCAPE = String.fromCharCode(27);
335
531
  function textWidth(text) {
336
532
  return Bun.stringWidth(text);
337
533
  }
338
- function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
534
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process6.stdout } = {}) {
339
535
  const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
340
536
  const widths = [];
341
537
  for (const row of cells) {
@@ -343,7 +539,7 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
343
539
  widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
344
540
  }
345
541
  const shown = fit === undefined ? cells : narrow(cells, widths, fit);
346
- const colors = paint(process3.stdout);
542
+ const colors = paint(stream);
347
543
  const lines = shown.map((row) => row.map((cell, index) => {
348
544
  const width = widths[index] ?? 0;
349
545
  const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
@@ -351,7 +547,8 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
351
547
  return `${gap}${cell}`;
352
548
  return index === row.length - 1 ? cell : `${cell}${gap}`;
353
549
  }).join(" ").trimEnd());
354
- return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
550
+ const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
551
+ return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
355
552
  `);
356
553
  }
357
554
  function narrow(rows, widths, limit) {
@@ -375,27 +572,27 @@ function printJson(value) {
375
572
  }
376
573
 
377
574
  // ../kit/src/help.ts
378
- import process4 from "process";
575
+ import process7 from "process";
379
576
  var OPTIONAL = /\[[^\]]+\]/g;
380
577
  var USAGE_PREFIX = /^usage:\s*/i;
381
578
  var FULL_STOP = /\.$/;
382
- function usageLine(usage, colors = paint(process4.stdout)) {
579
+ function usageLine(usage, colors = paint(process7.stdout)) {
383
580
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
384
581
  }
385
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
582
+ function helpText(usage, options, colors = paint(process7.stdout), { examples = [], replaces, exits = [] } = {}) {
386
583
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
387
584
  `);
388
585
  }
389
- function exitRows(exits, colors = paint(process4.stdout)) {
586
+ function exitRows(exits, colors = paint(process7.stdout)) {
390
587
  if (exits.length === 0)
391
588
  return [];
392
589
  const width = Math.max(...exits.map(([code]) => String(code).length));
393
590
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
394
591
  }
395
- function replacesRows(replaces, colors = paint(process4.stdout)) {
592
+ function replacesRows(replaces, colors = paint(process7.stdout)) {
396
593
  return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
397
594
  }
398
- function wantsHelpJson(env = process4.env) {
595
+ function wantsHelpJson(env = process7.env) {
399
596
  return env.KIT_HELP === "json";
400
597
  }
401
598
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -414,12 +611,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
414
611
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
415
612
  };
416
613
  }
417
- function exampleRows(examples, colors = paint(process4.stdout)) {
614
+ function exampleRows(examples, colors = paint(process7.stdout)) {
418
615
  if (examples.length === 0)
419
616
  return [];
420
617
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
421
618
  }
422
- function optionRows(options, colors = paint(process4.stdout)) {
619
+ function optionRows(options, colors = paint(process7.stdout)) {
423
620
  const rows = Object.entries(options).map(([name, option]) => {
424
621
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
425
622
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -454,7 +651,7 @@ function closest(name, names) {
454
651
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
455
652
  }
456
653
  // ../kit/src/input.ts
457
- import process5 from "process";
654
+ import process8 from "process";
458
655
  var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
459
656
  var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
460
657
  function duration(value, name, fallback, unit = "s") {
@@ -468,7 +665,7 @@ function duration(value, name, fallback, unit = "s") {
468
665
  }
469
666
  async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
470
667
  if (path === "-") {
471
- if (process5.stdin.isTTY)
668
+ if (process8.stdin.isTTY)
472
669
  fail(noStdin);
473
670
  return Bun.stdin.text();
474
671
  }
@@ -527,7 +724,7 @@ var OUTPUT_OPTIONS = {
527
724
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
528
725
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
529
726
  };
530
- function applyOutput(color, plain, env = process6.env) {
727
+ function applyOutput(color, plain, env = process9.env) {
531
728
  const when = plain === true ? "never" : color ?? "auto";
532
729
  if (when === "auto")
533
730
  return;
@@ -698,7 +895,7 @@ function nearestOption(message, options, allowNegative) {
698
895
  }
699
896
  // ../kit/src/process.ts
700
897
  import { constants } from "os";
701
- import process7 from "process";
898
+ import process10 from "process";
702
899
  var KILL_GRACE_MS = 2000;
703
900
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
704
901
  function exitCodeOf(code, signal) {
@@ -720,7 +917,7 @@ function holdSignals(cleanup) {
720
917
  },
721
918
  release: () => {
722
919
  for (const signal of SIGNALS)
723
- process7.off(signal, onSignal);
920
+ process10.off(signal, onSignal);
724
921
  }
725
922
  };
726
923
  function onSignal(signal) {
@@ -733,10 +930,10 @@ function holdSignals(cleanup) {
733
930
  return;
734
931
  held.release();
735
932
  cleanup(signal);
736
- process7.kill(process7.pid, signal);
933
+ process10.kill(process10.pid, signal);
737
934
  }
738
935
  for (const signal of SIGNALS)
739
- process7.on(signal, onSignal);
936
+ process10.on(signal, onSignal);
740
937
  return held;
741
938
  }
742
939
  async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
@@ -750,7 +947,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
750
947
  return;
751
948
  try {
752
949
  if (grouped)
753
- process7.kill(-proc.pid, killing);
950
+ process10.kill(-proc.pid, killing);
754
951
  else
755
952
  proc.kill(killing);
756
953
  } catch {}
@@ -824,42 +1021,42 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
824
1021
  var RESET_STYLE = `${ESC}[0m`;
825
1022
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
826
1023
  // ../kit/src/cli.ts
827
- import { readFileSync, realpathSync } from "fs";
828
- import { dirname as dirname2, join as join3 } from "path";
829
- import process10 from "process";
1024
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
1025
+ import { dirname as dirname3, join as join6 } from "path";
1026
+ import process13 from "process";
830
1027
 
831
1028
  // ../kit/src/usage.ts
832
1029
  import { appendFileSync, mkdirSync } from "fs";
833
- import { homedir as homedir2 } from "os";
834
- import { dirname, isAbsolute, join as join2 } from "path";
835
- import process9 from "process";
1030
+ import { homedir as homedir4 } from "os";
1031
+ import { dirname as dirname2, isAbsolute, join as join5 } from "path";
1032
+ import process12 from "process";
836
1033
 
837
1034
  // ../kit/src/logs.ts
838
1035
  import { lstatSync, openSync } from "fs";
839
1036
  import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
840
- import { homedir, tmpdir } from "os";
841
- import { join } from "path";
842
- import process8 from "process";
1037
+ import { homedir as homedir3, tmpdir } from "os";
1038
+ import { join as join4 } from "path";
1039
+ import process11 from "process";
843
1040
  var DAY_MS = 24 * 60 * 60 * 1000;
844
1041
  var CLI_FOLDER = "kaynooo-cli";
845
1042
  function isPrivateDirectory(path) {
846
1043
  try {
847
1044
  const info = lstatSync(path, { throwIfNoEntry: false });
848
- return info !== undefined && info.isDirectory() && info.uid === (process8.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
1045
+ return info !== undefined && info.isDirectory() && info.uid === (process11.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
849
1046
  } catch {
850
1047
  return false;
851
1048
  }
852
1049
  }
853
- async function privateLogDirectory(name, env = process8.env) {
1050
+ async function privateLogDirectory(name, env = process11.env) {
854
1051
  const runtime = env.XDG_RUNTIME_DIR;
855
- const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
856
- const path = join(base, name);
1052
+ const base = runtime === undefined || runtime === "" ? join4(homedir3(), ".cache", CLI_FOLDER) : join4(runtime, CLI_FOLDER);
1053
+ const path = join4(base, name);
857
1054
  try {
858
1055
  await mkdir(path, { recursive: true, mode: 448 });
859
1056
  if (isPrivateDirectory(path))
860
1057
  return path;
861
1058
  } catch {}
862
- return mkdtemp(join(tmpdir(), `${name.replaceAll("/", "-")}-`));
1059
+ return mkdtemp(join4(tmpdir(), `${name.replaceAll("/", "-")}-`));
863
1060
  }
864
1061
  async function sweepLogs(dir, maxAgeMs = DAY_MS, now = Date.now()) {
865
1062
  let names;
@@ -869,7 +1066,7 @@ async function sweepLogs(dir, maxAgeMs = DAY_MS, now = Date.now()) {
869
1066
  return;
870
1067
  }
871
1068
  for (const name of names) {
872
- const path = join(dir, name);
1069
+ const path = join4(dir, name);
873
1070
  try {
874
1071
  const info = await stat(path);
875
1072
  if (info.isDirectory())
@@ -890,14 +1087,14 @@ var usageError;
890
1087
  function noteUsageError(message) {
891
1088
  usageError = message;
892
1089
  }
893
- function stateHome(env = process9.env) {
1090
+ function stateHome(env = process12.env) {
894
1091
  const dir = env.XDG_STATE_HOME;
895
- return dir !== undefined && isAbsolute(dir) ? dir : join2(homedir2(), ".local", "state");
1092
+ return dir !== undefined && isAbsolute(dir) ? dir : join5(homedir4(), ".local", "state");
896
1093
  }
897
- function usagePath(env = process9.env) {
898
- return join2(stateHome(env), CLI_FOLDER, "usage.jsonl");
1094
+ function usagePath(env = process12.env) {
1095
+ return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
899
1096
  }
900
- function usageRecorded(env = process9.env) {
1097
+ function usageRecorded(env = process12.env) {
901
1098
  const off = env.KAYNOOO_CLI_NO_USAGE;
902
1099
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
903
1100
  }
@@ -911,12 +1108,12 @@ function usageEntry(bin, command, argv, code, now = new Date) {
911
1108
  usageError = undefined;
912
1109
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
913
1110
  }
914
- function recordUsage(entry, env = process9.env) {
1111
+ function recordUsage(entry, env = process12.env) {
915
1112
  if (!usageRecorded(env))
916
1113
  return;
917
1114
  try {
918
1115
  const path = usagePath(env);
919
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
1116
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
920
1117
  appendFileSync(path, `${JSON.stringify(entry)}
921
1118
  `, { mode: 384 });
922
1119
  } catch {}
@@ -929,8 +1126,8 @@ var LEVEL_OPTIONS = {
929
1126
  };
930
1127
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
931
1128
  function printError(prefix, message, hint, cause) {
932
- const colors = paint(process10.stderr);
933
- const styled = takesControlCodes(process10.stderr);
1129
+ const colors = paint(process13.stderr);
1130
+ const styled = takesControlCodes(process13.stderr);
934
1131
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
935
1132
  const under = (label, text, tint) => text === undefined ? "" : `
936
1133
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -949,7 +1146,7 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
949
1146
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
950
1147
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
951
1148
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
952
- if (error instanceof UsageError)
1149
+ if (error instanceof Exit && error.code === 2)
953
1150
  noteUsageError(error.message);
954
1151
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
955
1152
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
@@ -1013,17 +1210,17 @@ async function printCandidates(found) {
1013
1210
  return 0;
1014
1211
  }
1015
1212
  function packageVersion(entry = Bun.main) {
1016
- for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1213
+ for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1017
1214
  try {
1018
- const { version } = JSON.parse(readFileSync(join3(dir, "package.json"), "utf8"));
1215
+ const { version } = JSON.parse(readFileSync2(join6(dir, "package.json"), "utf8"));
1019
1216
  if (typeof version === "string")
1020
1217
  return version;
1021
1218
  } catch {}
1022
- if (dirname2(dir) === dir)
1219
+ if (dirname3(dir) === dir)
1023
1220
  return "0.0.0";
1024
1221
  }
1025
1222
  }
1026
- async function runMain({ name, version, run, redact, usage }, argv = process10.argv.slice(2)) {
1223
+ async function runMain({ name, version, run, redact, usage }, argv = process13.argv.slice(2)) {
1027
1224
  if (argv[0] === COMPLETE)
1028
1225
  return printCandidates(leafCandidates(run, argv.slice(1)));
1029
1226
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1050,88 +1247,670 @@ var {Glob } = globalThis.Bun;
1050
1247
  var SESSION_FILES = new Glob("*.json");
1051
1248
  var ACCOUNT_DIRS = new Glob("*/sessions");
1052
1249
  // package.json
1053
- var version = "0.12.1";
1250
+ var version = "0.14.0";
1054
1251
 
1055
1252
  // src/j.ts
1056
- import process15 from "process";
1253
+ import process20 from "process";
1057
1254
 
1058
- // ../kit/src/fzf.ts
1059
- import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
1060
- import { homedir as homedir3 } from "os";
1061
- import { dirname as dirname3, join as join4 } from "path";
1062
- import process12 from "process";
1063
- var REMEMBERED = 20;
1064
- function table2(rows) {
1065
- const widths = rows[0]?.cells.map((_, index) => Math.max(...rows.map((row) => Bun.stringWidth(row.cells[index])))) ?? [];
1066
- return rows.map((row) => [
1067
- ...row.hidden,
1068
- ...row.cells.map((cell, index) => index === row.cells.length - 1 ? cell.trimEnd() : `${cell}${" ".repeat(widths[index] + 1 - Bun.stringWidth(cell))}`)
1069
- ].join("\t"));
1070
- }
1071
- function fzf(rows, options) {
1072
- const hidden = options.hidden ?? rows[0]?.hidden.length ?? 0;
1073
- const proc = Bun.spawnSync([
1074
- "fzf",
1075
- "--prompt",
1076
- options.prompt,
1077
- ...options.header === undefined ? [] : ["--header", options.header],
1078
- ...(options.expect ?? []).length > 0 ? ["--expect", (options.expect ?? []).join(",")] : [],
1079
- "--ansi",
1080
- "--reverse",
1081
- "--height",
1082
- options.height ?? "100%",
1083
- "--delimiter",
1084
- "\t",
1085
- "--with-nth",
1086
- `${hidden + 1}..`,
1087
- "--nth",
1088
- `1..${options.searched}`,
1089
- "--tabstop",
1090
- "1",
1091
- "--tiebreak",
1092
- "chunk,index",
1093
- ...options.preview === undefined ? [] : ["--preview", options.preview, "--preview-window", "down,40%"],
1094
- ...(options.bind ?? []).flatMap((bind) => ["--bind", bind]),
1095
- ...options.query === true ? ["--print-query"] : []
1096
- ], {
1097
- stdin: new TextEncoder().encode(table2(rows).join(`
1098
- `)),
1099
- stdout: "pipe",
1100
- stderr: "inherit"
1255
+ // ../kit/src/picker.ts
1256
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
1257
+ import { homedir as homedir5 } from "os";
1258
+ import { dirname as dirname4, join as join7 } from "path";
1259
+ import process17 from "process";
1260
+
1261
+ // ../kit/src/picker/score.ts
1262
+ var MATCH = 16;
1263
+ var CONSECUTIVE = 12;
1264
+ var BOUNDARY = 10;
1265
+ var PREFIX = 8;
1266
+ var GAP = 1;
1267
+ var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1268
+ var UPPER = /\p{Lu}/u;
1269
+ var LOWER = /\p{Ll}/u;
1270
+ var NONE = Number.NEGATIVE_INFINITY;
1271
+ function startsWord(text, index) {
1272
+ if (index === 0)
1273
+ return true;
1274
+ const before = text[index - 1];
1275
+ return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
1276
+ }
1277
+ function fuzzy(query, text) {
1278
+ if (query === "")
1279
+ return { score: 0, positions: [] };
1280
+ const exact = query !== query.toLowerCase();
1281
+ const needle = exact ? query : query.toLowerCase();
1282
+ const haystack = exact ? text : text.toLowerCase();
1283
+ if (haystack.length !== text.length || needle.length > haystack.length)
1284
+ return;
1285
+ const width = haystack.length;
1286
+ const best = Array.from({ length: needle.length }, () => new Array(width).fill(NONE));
1287
+ const from = Array.from({ length: needle.length }, () => new Array(width).fill(-1));
1288
+ for (let j = 0;j < needle.length; j++) {
1289
+ let run = NONE;
1290
+ let runAt = -1;
1291
+ for (let i = j;i < width; i++) {
1292
+ if (j > 0 && i - 2 >= j - 1) {
1293
+ const candidate = best[j - 1][i - 2] + (i - 2) * GAP;
1294
+ if (candidate > run) {
1295
+ run = candidate;
1296
+ runAt = i - 2;
1297
+ }
1298
+ }
1299
+ if (haystack[i] !== needle[j])
1300
+ continue;
1301
+ const here = MATCH + (startsWord(text, i) ? BOUNDARY : 0) + (i === 0 ? PREFIX : 0);
1302
+ if (j === 0) {
1303
+ best[0][i] = here - i * GAP;
1304
+ continue;
1305
+ }
1306
+ const joined = best[j - 1][i - 1] + CONSECUTIVE;
1307
+ const skipped = run - (i - 1) * GAP;
1308
+ if (joined > NONE && joined >= skipped) {
1309
+ best[j][i] = joined + here;
1310
+ from[j][i] = i - 1;
1311
+ } else if (skipped > NONE) {
1312
+ best[j][i] = skipped + here;
1313
+ from[j][i] = runAt;
1314
+ }
1315
+ }
1316
+ }
1317
+ const last = best[needle.length - 1];
1318
+ let end = -1;
1319
+ for (let i = 0;i < width; i++) {
1320
+ if (last[i] > NONE && (end === -1 || last[i] > last[end]))
1321
+ end = i;
1322
+ }
1323
+ if (end === -1)
1324
+ return;
1325
+ const positions = [];
1326
+ for (let j = needle.length - 1, i = end;j >= 0; j--) {
1327
+ positions.unshift(i);
1328
+ i = from[j][i];
1329
+ }
1330
+ return { score: last[end], positions };
1331
+ }
1332
+ function rank(query, lines) {
1333
+ if (query === "")
1334
+ return lines.map((_, index) => ({ index, positions: [] }));
1335
+ const found = [];
1336
+ for (const [index, line] of lines.entries()) {
1337
+ const match = fuzzy(query, line);
1338
+ if (match !== undefined)
1339
+ found.push({ index, positions: match.positions, score: match.score });
1340
+ }
1341
+ return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
1342
+ }
1343
+
1344
+ // ../kit/src/picker/state.ts
1345
+ var ANSI2 = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
1346
+ var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1347
+ var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1348
+ var SGR = /^\x1B\[[0-9;]*m$/;
1349
+ var RESET = /^\x1B\[0?m$/;
1350
+ var COLUMN_GAP = 2;
1351
+ var PASTE_START = "\x1B[200~";
1352
+ var PASTE_END = "\x1B[201~";
1353
+ var LAST_WORD = /\S*\s*$/;
1354
+ var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1355
+ var KEYS = {
1356
+ "\x1B[A": "up",
1357
+ "\x1BOA": "up",
1358
+ "\x10": "up",
1359
+ "\x1B[B": "down",
1360
+ "\x1BOB": "down",
1361
+ "\x0E": "down",
1362
+ "\r": "enter",
1363
+ "\n": "enter",
1364
+ "\x03": "cancel",
1365
+ "\x1B": "cancel",
1366
+ "\x7F": "erase",
1367
+ "\b": "erase",
1368
+ "\x15": "clear",
1369
+ "\x17": "word",
1370
+ "\t": "tab"
1371
+ };
1372
+ var CTRL_KEY = /^ctrl-[abd-gkln-z]$/;
1373
+ function repeat(value, count) {
1374
+ return Array.from({ length: count }).fill(value);
1375
+ }
1376
+ function styled(line) {
1377
+ let text = "";
1378
+ const styles = [];
1379
+ let active = "";
1380
+ let colored = false;
1381
+ let last = 0;
1382
+ function add(chunk) {
1383
+ const flat = chunk.replace(CONTROL2, " ");
1384
+ text += flat;
1385
+ colored ||= active !== "" && flat !== "";
1386
+ styles.push(...repeat(active, flat.length));
1387
+ }
1388
+ for (const found of line.matchAll(ANSI2)) {
1389
+ add(line.slice(last, found.index));
1390
+ last = found.index + found[0].length;
1391
+ if (SGR.test(found[0]))
1392
+ active = RESET.test(found[0]) ? "" : active + found[0];
1393
+ }
1394
+ add(line.slice(last));
1395
+ return { text, styles: colored ? styles : undefined };
1396
+ }
1397
+ function lay(rows, searched) {
1398
+ const parsed = rows.map((row) => row.cells.map(styled));
1399
+ const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
1400
+ return parsed.map((cells) => {
1401
+ let text = "";
1402
+ const styles = [];
1403
+ let colored = false;
1404
+ let searchEnd = 0;
1405
+ for (const [column, cell] of cells.entries()) {
1406
+ const last = column === cells.length - 1;
1407
+ const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
1408
+ text += shown;
1409
+ colored ||= cell.styles !== undefined;
1410
+ styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
1411
+ if (column < searched)
1412
+ searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
1413
+ if (!last) {
1414
+ const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
1415
+ text += " ".repeat(pad);
1416
+ styles.push(...repeat("", pad));
1417
+ }
1418
+ }
1419
+ return { text, styles: colored ? styles : undefined, searchable: text.slice(0, searchEnd) };
1101
1420
  });
1102
- return picked(proc.stdout.toString(), hidden, options);
1103
1421
  }
1104
- function picked(output, hidden, options) {
1422
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
1423
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1424
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1425
+ const named = codes.get(sequence);
1426
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1427
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1428
+ paste.active = sequence === PASTE_START;
1429
+ return [];
1430
+ }
1431
+ if (paste.active && (sequence === "\r" || sequence === `
1432
+ `))
1433
+ return [];
1434
+ if (key !== undefined)
1435
+ return [key];
1436
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1437
+ });
1438
+ }
1439
+ function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1440
+ const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, matches: [], cursor: 0, marked: new Set, multi, prompt, done: undefined };
1441
+ return withRows(state, rows);
1442
+ }
1443
+ function withRows(state, rows, header = state.header) {
1444
+ const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1445
+ const laid = lay(cells, state.searched);
1446
+ const searchable = laid.map((row) => row.searchable);
1447
+ const matches = rank(state.query, searchable);
1448
+ 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 };
1449
+ }
1450
+ function withQuery(state, query) {
1451
+ return { ...state, query, matches: rank(query, state.searchable), cursor: 0 };
1452
+ }
1453
+ function move(state, by) {
1454
+ return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
1455
+ }
1456
+ function highlighted(state) {
1457
+ return state.matches[state.cursor]?.index;
1458
+ }
1459
+ function press(state, key) {
1460
+ if (state.done !== undefined)
1461
+ return state;
1462
+ if (typeof key === "object") {
1463
+ if ("text" in key)
1464
+ return withQuery(state, state.query + key.text);
1465
+ return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1466
+ }
1467
+ switch (key) {
1468
+ case "up":
1469
+ return move(state, -1);
1470
+ case "down":
1471
+ return move(state, 1);
1472
+ case "cancel":
1473
+ return { ...state, done: "cancel" };
1474
+ case "erase":
1475
+ return withQuery(state, [...state.query].slice(0, -1).join(""));
1476
+ case "clear":
1477
+ return withQuery(state, "");
1478
+ case "word":
1479
+ return withQuery(state, state.query.replace(LAST_WORD, ""));
1480
+ case "enter":
1481
+ return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1482
+ case "tab": {
1483
+ const at = highlighted(state);
1484
+ if (!state.multi || at === undefined)
1485
+ return state;
1486
+ const marked = new Set(state.marked);
1487
+ if (!marked.delete(at))
1488
+ marked.add(at);
1489
+ return move({ ...state, marked }, 1);
1490
+ }
1491
+ }
1492
+ }
1493
+ function chosen(state) {
1494
+ if (state.marked.size > 0)
1495
+ return state.rows.filter((_, index) => state.marked.has(index));
1496
+ const at = highlighted(state);
1497
+ return at === undefined ? [] : [state.rows[at]];
1498
+ }
1499
+
1500
+ // ../kit/src/picker/terminal.ts
1501
+ import { openSync as openSync2 } from "fs";
1502
+ import process16 from "process";
1503
+ import tty from "tty";
1504
+
1505
+ // ../kit/src/picker/preview.ts
1506
+ import process15 from "process";
1507
+
1508
+ // ../kit/src/shell.ts
1509
+ var SEPARATORS = new Set([`
1510
+ `, ";", "|"]);
1511
+ var PLAIN_BREAKERS = new Set(["<", ">", "(", ")", "&", "|"]);
1512
+ var GLOB_CHARS = new Set(["*", "?", "["]);
1513
+ var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
1514
+ var SAFE_WORD = /^[\w@%+=:,./-]+$/;
1515
+ var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
1516
+ var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
1517
+ var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
1518
+ var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
1519
+ var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
1520
+ var POWERSHELL = new Set(["pwsh", "powershell"]);
1521
+ var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
1522
+ var FISH_VALUE_OPTIONS = new Set(["-C", "--init-command"]);
1523
+ var PRINTERS = new Set(["echo", "printf"]);
1524
+ var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
1525
+ function wrapper(short = "", long = [], operands = 0, runsString = false) {
1526
+ return { short, long, operands, runsString };
1527
+ }
1528
+ var WRAPPERS = new Map([
1529
+ ["command", wrapper()],
1530
+ ["builtin", wrapper()],
1531
+ ["nohup", wrapper()],
1532
+ ["setsid", wrapper()],
1533
+ ["busybox", wrapper()],
1534
+ ["exec", wrapper("a")],
1535
+ ["time", wrapper("fo", ["--format", "--output"])],
1536
+ ["env", wrapper("uCS", ["--unset", "--chdir", "--split-string", "--argv0"])],
1537
+ ["sudo", wrapper("ughpCTrtUDR", ["--user", "--group", "--host", "--prompt", "--close-from", "--command-timeout", "--role", "--type", "--other-user", "--chdir", "--chroot"])],
1538
+ ["doas", wrapper("uC")],
1539
+ ["timeout", wrapper("sk", ["--signal", "--kill-after"], 1)],
1540
+ ["nice", wrapper("n", ["--adjustment"])],
1541
+ ["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
1542
+ ["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
1543
+ ["chroot", wrapper("", ["--userspec", "--groups"], 1)],
1544
+ ["watch", wrapper("n", ["--interval"], 0, true)],
1545
+ ["flock", wrapper("wE", ["--timeout", "--conflict-exit-code"], 1)],
1546
+ ["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
1547
+ ["unbuffer", wrapper()],
1548
+ ["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
1549
+ ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
1550
+ ]);
1551
+ function shellQuote(word) {
1552
+ return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
1553
+ }
1554
+
1555
+ // ../kit/src/picker/preview.ts
1556
+ var PREVIEW_BYTES = 64 * 1024;
1557
+ var PREVIEW_LINES = 200;
1558
+ var PREVIEW_TIMEOUT_MS = 3000;
1559
+ var PLACEHOLDER = /\{([1-9]\d*)?\}/g;
1560
+ function previewCommand(template, line, hidden = []) {
1561
+ return template.replace(PLACEHOLDER, (_, field) => shellQuote(field === undefined ? line : hidden[Number(field) - 1] ?? ""));
1562
+ }
1563
+ function previewLines(output) {
1105
1564
  const lines = output.split(`
1106
1565
  `);
1107
- const query = options.query === true ? lines.shift() : "";
1108
- const [key, line] = (options.expect ?? []).length > 0 ? [lines[0], lines[1]] : ["", lines[0]];
1109
- if (line !== undefined && line !== "")
1110
- return { key, hidden: line.split("\t").slice(0, hidden), query };
1111
- return options.query === true && key !== "" ? { key, hidden: [], query } : undefined;
1566
+ if (lines.at(-1) === "")
1567
+ lines.pop();
1568
+ return lines.slice(0, PREVIEW_LINES);
1569
+ }
1570
+ async function runPreview(template, line, signal, hidden = []) {
1571
+ const proc = Bun.spawn(["sh", "-c", `exec 2>&1
1572
+ ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1573
+ const stop = () => {
1574
+ try {
1575
+ process15.kill(-proc.pid, "SIGKILL");
1576
+ } catch {
1577
+ proc.kill();
1578
+ }
1579
+ };
1580
+ const timer = setTimeout(stop, PREVIEW_TIMEOUT_MS);
1581
+ const chunks = [];
1582
+ let size = 0;
1583
+ signal.addEventListener("abort", stop);
1584
+ try {
1585
+ for await (const chunk of proc.stdout) {
1586
+ chunks.push(chunk);
1587
+ size += chunk.length;
1588
+ if (size >= PREVIEW_BYTES) {
1589
+ stop();
1590
+ break;
1591
+ }
1592
+ }
1593
+ } finally {
1594
+ clearTimeout(timer);
1595
+ signal.removeEventListener("abort", stop);
1596
+ }
1597
+ return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
1598
+ }
1599
+
1600
+ // ../kit/src/picker/view.ts
1601
+ var MIN_HEIGHT = 4;
1602
+ var PREVIEW_MIN_COLUMNS = 80;
1603
+ var PREVIEW_MIN_ROWS = 10;
1604
+ var PREVIEW_SHARE = 0.4;
1605
+ var RESET2 = "\x1B[0m";
1606
+ var SEPARATOR = " \u2502 ";
1607
+ var HEIGHT = /^(\d+)(%?)$/;
1608
+ function parseHeight(text) {
1609
+ const found = HEIGHT.exec(text);
1610
+ if (found === null || Number(found[1]) < 1)
1611
+ return;
1612
+ return found[2] === "%" ? { percent: Math.min(100, Number(found[1])) } : { lines: Number(found[1]) };
1613
+ }
1614
+ function layoutFor(size, height, previewing, position = "right") {
1615
+ const wanted = "lines" in height ? height.lines : Math.round(size.rows * height.percent / 100);
1616
+ const rows = Math.min(size.rows, Math.max(MIN_HEIGHT, wanted));
1617
+ if (position === "down") {
1618
+ const previewHeight = previewing && rows >= PREVIEW_MIN_ROWS ? Math.round(rows * PREVIEW_SHARE) : 0;
1619
+ return { height: rows, listHeight: rows - previewHeight, listWidth: size.columns, previewWidth: 0, previewHeight };
1620
+ }
1621
+ const split = previewing && size.columns >= PREVIEW_MIN_COLUMNS;
1622
+ const listWidth = split ? Math.floor(size.columns / 2) : size.columns;
1623
+ return { height: rows, listHeight: rows, listWidth, previewWidth: split ? size.columns - listWidth - SEPARATOR.length : 0, previewHeight: 0 };
1624
+ }
1625
+ function fit(text, width, plain, mark = plain, marked = new Set, styles) {
1626
+ const room = Bun.stringWidth(text) > width ? width - 1 : width;
1627
+ let out = "";
1628
+ let used = 0;
1629
+ let at = 0;
1630
+ for (const char of text) {
1631
+ const size = Bun.stringWidth(char);
1632
+ if (used + size > room)
1633
+ break;
1634
+ const style = marked.has(at) ? "" : styles?.[at] ?? "";
1635
+ out += style === "" ? (marked.has(at) ? mark : plain)(char) : `${style}${char}${RESET2}`;
1636
+ used += size;
1637
+ at += char.length;
1638
+ }
1639
+ if (room < width) {
1640
+ out += plain("\u2026");
1641
+ used += 1;
1642
+ }
1643
+ return { text: out, width: used };
1644
+ }
1645
+ var identity = (text) => text;
1646
+ function fitStyled(line, width, plain = identity) {
1647
+ const { text, styles } = styled(line);
1648
+ return fit(text, width, plain, plain, new Set, styles);
1649
+ }
1650
+ function caretColumn(state, layout) {
1651
+ return Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + Bun.stringWidth(state.query) + 1);
1652
+ }
1653
+ function listLines(state, layout, theme) {
1654
+ const header = state.header === "" ? [] : state.header.split(`
1655
+ `).map((line) => fitStyled(line, layout.listWidth, theme.label));
1656
+ const rows = Math.max(1, layout.listHeight - 2 - header.length);
1657
+ const prefixWidth = state.multi ? 4 : 2;
1658
+ const top = Math.max(0, Math.min(state.cursor - Math.floor(rows / 2), state.matches.length - rows));
1659
+ const marks = (state.marked.size > 0 ? ` (${state.marked.size} marked)` : "") + (state.status === "" ? "" : ` ${state.status}`);
1660
+ const promptWidth = Bun.stringWidth(state.prompt);
1661
+ const query = fit(state.query, Math.max(1, layout.listWidth - promptWidth), identity);
1662
+ const count = fit(` ${state.matches.length}/${state.items.length}${marks}`, layout.listWidth, theme.label);
1663
+ const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count, ...header];
1664
+ if (state.matches.length === 0)
1665
+ lines.push(fit(" no match", layout.listWidth, theme.label));
1666
+ for (const [offset, match] of state.matches.slice(top, top + rows).entries()) {
1667
+ const current = top + offset === state.cursor;
1668
+ const pointer = current ? theme.accent("\u276F") : " ";
1669
+ const mark = state.multi ? `${state.marked.has(match.index) ? theme.id("\u25CF") : " "} ` : "";
1670
+ const text = fit(state.items[match.index], layout.listWidth - prefixWidth, current ? theme.value : identity, theme.accent, new Set(match.positions), state.styles[match.index]);
1671
+ lines.push({ text: `${pointer} ${mark}${text.text}`, width: prefixWidth + text.width });
1672
+ }
1673
+ return lines;
1674
+ }
1675
+ function render(state, layout, theme, preview = []) {
1676
+ const left = listLines(state, layout, theme);
1677
+ return Array.from({ length: layout.height }, (_, row) => {
1678
+ if (row >= layout.listHeight)
1679
+ return row === layout.listHeight ? theme.label("\u2500".repeat(layout.listWidth)) : fitStyled(preview[row - layout.listHeight - 1] ?? "", layout.listWidth).text;
1680
+ const list = left[row] ?? { text: "", width: 0 };
1681
+ if (layout.previewWidth === 0)
1682
+ return list.text;
1683
+ return `${list.text}${" ".repeat(Math.max(0, layout.listWidth - list.width))}${theme.label(SEPARATOR)}${fitStyled(preview[row] ?? "", layout.previewWidth).text}`;
1684
+ });
1685
+ }
1686
+
1687
+ // ../kit/src/picker/terminal.ts
1688
+ var PREVIEW_DELAY_MS = 120;
1689
+ var OPEN = { ctrl: "open" };
1690
+ var HIDE_CURSOR = "\x1B[?25l";
1691
+ var SHOW_CURSOR = "\x1B[?25h";
1692
+ var PASTE_ON = "\x1B[?2004h";
1693
+ var PASTE_OFF = "\x1B[?2004l";
1694
+ var CLEAR_BELOW = "\r\x1B[J";
1695
+ var SIGNALS2 = ["SIGINT", "SIGTERM", "SIGHUP"];
1696
+ function up(lines) {
1697
+ return lines > 0 ? `\x1B[${lines}A` : "";
1698
+ }
1699
+ function openTerminal() {
1700
+ let input;
1701
+ try {
1702
+ input = new tty.ReadStream(openSync2("/dev/tty", "r"));
1703
+ } catch {
1704
+ return fail("no terminal to read keys from (/dev/tty)");
1705
+ }
1706
+ const out = process16.stderr;
1707
+ let resize;
1708
+ return {
1709
+ get columns() {
1710
+ return out.columns || 80;
1711
+ },
1712
+ get rows() {
1713
+ return out.rows || 24;
1714
+ },
1715
+ theme: { accent: role("accent", out), label: role("label", out), value: role("value", out), id: role("id", out) },
1716
+ write: (text) => void out.write(text),
1717
+ listen(onChunk, onResize) {
1718
+ resize = onResize;
1719
+ input.setRawMode(true);
1720
+ out.on("resize", onResize);
1721
+ input.on("data", (chunk) => onChunk(chunk.toString()));
1722
+ },
1723
+ close() {
1724
+ if (resize !== undefined)
1725
+ out.off("resize", resize);
1726
+ try {
1727
+ input.setRawMode(false);
1728
+ } finally {
1729
+ input.destroy();
1730
+ }
1731
+ }
1732
+ };
1733
+ }
1734
+ async function select(rows, settings, terminal = openTerminal()) {
1735
+ const { theme } = terminal;
1736
+ let state = createState(rows, settings);
1737
+ let preview = [];
1738
+ let reserved = 0;
1739
+ let previewTimer;
1740
+ let previewing = new AbortController;
1741
+ let shownLine;
1742
+ let finish;
1743
+ let restored = false;
1744
+ function draw(clear = false) {
1745
+ if (restored)
1746
+ return;
1747
+ const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
1748
+ let frame = HIDE_CURSOR;
1749
+ if (reserved !== layout.height || clear) {
1750
+ frame += CLEAR_BELOW + `
1751
+ `.repeat(layout.height - 1) + up(layout.height - 1);
1752
+ reserved = layout.height;
1753
+ }
1754
+ frame += `\r${render(state, layout, theme, preview).map((line) => `\x1B[2K${line}`).join(`
1755
+ `)}${up(layout.height - 1)}\r\x1B[${caretColumn(state, layout)}G${SHOW_CURSOR}`;
1756
+ terminal.write(frame);
1757
+ }
1758
+ function refreshPreview() {
1759
+ const at = highlighted(state);
1760
+ if (settings.preview === undefined || at === shownLine)
1761
+ return;
1762
+ shownLine = at;
1763
+ clearTimeout(previewTimer);
1764
+ previewing.abort();
1765
+ previewing = new AbortController;
1766
+ if (at === undefined) {
1767
+ preview = [];
1768
+ return;
1769
+ }
1770
+ const { signal } = previewing;
1771
+ const template = settings.preview;
1772
+ const row = state.rows[at];
1773
+ async function show() {
1774
+ const shown = typeof template === "string" ? await runPreview(template, row.cells.join(" "), signal, row.hidden) : await previewOf(template, row.hidden, signal);
1775
+ if (!signal.aborted) {
1776
+ preview = shown;
1777
+ draw();
1778
+ }
1779
+ }
1780
+ previewTimer = setTimeout(() => void show(), PREVIEW_DELAY_MS);
1781
+ }
1782
+ function restore() {
1783
+ if (restored)
1784
+ return;
1785
+ restored = true;
1786
+ clearTimeout(previewTimer);
1787
+ previewing.abort();
1788
+ terminal.write(`${CLEAR_BELOW}${PASTE_OFF}${SHOW_CURSOR}`);
1789
+ terminal.close();
1790
+ }
1791
+ const stop = () => {
1792
+ state = { ...state, done: "cancel" };
1793
+ finish?.();
1794
+ };
1795
+ const paste = { active: false };
1796
+ const { reload } = settings;
1797
+ const pending = [];
1798
+ let busy = false;
1799
+ let draining = false;
1800
+ async function reloadRows() {
1801
+ if (reload === undefined)
1802
+ return;
1803
+ busy = true;
1804
+ state = { ...state, status: "reloading" };
1805
+ draw();
1806
+ try {
1807
+ const next = await reload.run();
1808
+ state = { ...withRows(state, next.rows, next.header), status: "" };
1809
+ shownLine = undefined;
1810
+ } catch (error) {
1811
+ state = { ...state, status: `reload failed: ${error instanceof Error ? error.message : String(error)}` };
1812
+ } finally {
1813
+ busy = false;
1814
+ }
1815
+ }
1816
+ async function drain() {
1817
+ if (draining)
1818
+ return;
1819
+ draining = true;
1820
+ try {
1821
+ for (let key = pending.shift();key !== undefined && state.done === undefined; key = pending.shift()) {
1822
+ if (key === OPEN || typeof key === "object" && "ctrl" in key && key.ctrl === reload?.key)
1823
+ await reloadRows();
1824
+ else
1825
+ state = press(state, key);
1826
+ }
1827
+ } finally {
1828
+ draining = false;
1829
+ }
1830
+ if (state.done !== undefined) {
1831
+ finish?.();
1832
+ return;
1833
+ }
1834
+ refreshPreview();
1835
+ draw();
1836
+ }
1837
+ function onChunk(chunk) {
1838
+ const keys = parseKeys(chunk, paste, [...settings.expect ?? [], ...reload?.key === undefined ? [] : [reload.key]]);
1839
+ if (busy && keys.includes("cancel")) {
1840
+ stop();
1841
+ return;
1842
+ }
1843
+ pending.push(...keys);
1844
+ drain();
1845
+ }
1846
+ const ended = new Promise((resolve) => {
1847
+ finish = resolve;
1848
+ });
1849
+ process16.once("exit", restore);
1850
+ for (const signal of SIGNALS2)
1851
+ process16.once(signal, stop);
1852
+ try {
1853
+ terminal.write(PASTE_ON);
1854
+ terminal.listen(onChunk, () => draw(true));
1855
+ refreshPreview();
1856
+ draw(true);
1857
+ if (reload?.onOpen === true) {
1858
+ pending.push(OPEN);
1859
+ drain();
1860
+ }
1861
+ await ended;
1862
+ } finally {
1863
+ for (const signal of SIGNALS2)
1864
+ process16.off(signal, stop);
1865
+ process16.off("exit", restore);
1866
+ restore();
1867
+ }
1868
+ return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
1869
+ }
1870
+ async function previewOf(preview, hidden, signal) {
1871
+ try {
1872
+ return previewLines(await preview(hidden, signal));
1873
+ } catch (error) {
1874
+ return [error instanceof Error ? error.message : String(error)];
1875
+ }
1876
+ }
1877
+
1878
+ // ../kit/src/picker.ts
1879
+ var REMEMBERED = 20;
1880
+ async function pick(rows, options) {
1881
+ const height = parseHeight(options.height ?? "100%");
1882
+ const keys = [...options.expect ?? [], ...options.reload?.key === undefined ? [] : [options.reload.key]];
1883
+ if (height === undefined)
1884
+ throw new Error(`pick: the height is lines or a percentage, not ${options.height}`);
1885
+ for (const key of keys) {
1886
+ if (!CTRL_KEY.test(key))
1887
+ throw new Error(`pick: ${key} is not a key it can report, one of ctrl-a to ctrl-z but ctrl-c, h, i, j and m`);
1888
+ }
1889
+ const found = await select(rows, { multi: false, prompt: options.prompt, query: "", height, preview: options.preview, previewPosition: "down", header: options.header, expect: options.expect, searched: options.searched, reload: options.reload });
1890
+ return found === undefined ? undefined : { key: found.key, hidden: found.rows[0]?.hidden ?? [], query: found.query };
1112
1891
  }
1113
1892
  function heightFor(count) {
1114
1893
  return String(Math.max(15, Math.ceil((count + 4) / 0.6)));
1115
1894
  }
1116
1895
  function historyFile(name) {
1117
- return join4(process12.env.XDG_CACHE_HOME ?? join4(homedir3(), ".cache"), name, "history.json");
1896
+ return join7(process17.env.XDG_CACHE_HOME ?? join7(homedir5(), ".cache"), name, "history.json");
1118
1897
  }
1119
1898
  function history(name) {
1120
1899
  try {
1121
1900
  const file = historyFile(name);
1122
- return existsSync(file) ? JSON.parse(readFileSync2(file, "utf-8")) : {};
1901
+ return existsSync3(file) ? JSON.parse(readFileSync3(file, "utf-8")) : {};
1123
1902
  } catch {
1124
1903
  return {};
1125
1904
  }
1126
1905
  }
1127
1906
  function runs(name) {
1128
- return history(name)[process12.cwd()] ?? [];
1907
+ return history(name)[process17.cwd()] ?? [];
1129
1908
  }
1130
1909
  function record(name, run) {
1131
1910
  const all = history(name);
1132
1911
  const file = historyFile(name);
1133
- all[process12.cwd()] = [run, ...(all[process12.cwd()] ?? []).filter((earlier) => earlier.id !== run.id)].slice(0, REMEMBERED);
1134
- mkdirSync2(dirname3(file), { recursive: true });
1912
+ all[process17.cwd()] = [run, ...(all[process17.cwd()] ?? []).filter((earlier) => earlier.id !== run.id)].slice(0, REMEMBERED);
1913
+ mkdirSync2(dirname4(file), { recursive: true });
1135
1914
  writeFileSync(file, JSON.stringify(all));
1136
1915
  }
1137
1916
  function byRecency(items, previous, idOf) {
@@ -1154,12 +1933,12 @@ function list(rows) {
1154
1933
  }
1155
1934
 
1156
1935
  // ../kit/src/prompt.ts
1157
- import process13 from "process";
1158
- var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|[\s\S]/giu;
1159
- var CONTROL = /^[\x00-\x1F\x7F]/;
1160
- var KEYS = { "\x1B[A": "up", "\x1BOA": "up", "\x1B[B": "down", "\x1BOB": "down", "\r": "enter", "\n": "enter", "\x03": "cancel", "\x1B": "cancel", "\x7F": "erase", "\b": "erase" };
1936
+ import process18 from "process";
1937
+ var KEY_SEQUENCES2 = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|[\s\S]/giu;
1938
+ var CONTROL3 = /^[\x00-\x1F\x7F]/;
1939
+ var KEYS2 = { "\x1B[A": "up", "\x1BOA": "up", "\x1B[B": "down", "\x1BOB": "down", "\r": "enter", "\n": "enter", "\x03": "cancel", "\x1B": "cancel", "\x7F": "erase", "\b": "erase" };
1161
1940
  function readKeys(input) {
1162
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => KEYS[sequence] ?? (CONTROL.test(sequence) ? [] : [{ text: sequence }]));
1941
+ return (input.match(KEY_SEQUENCES2) ?? []).flatMap((sequence) => KEYS2[sequence] ?? (CONTROL3.test(sequence) ? [] : [{ text: sequence }]));
1163
1942
  }
1164
1943
  async function input2(question, { default: fallback, mask = false, validate, ...settings } = {}) {
1165
1944
  let value = "";
@@ -1193,7 +1972,7 @@ async function input2(question, { default: fallback, mask = false, validate, ...
1193
1972
  function answer(colors, question, state, picked) {
1194
1973
  return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1195
1974
  }
1196
- async function ask(question, { hint, terminal = process13 }, render, press) {
1975
+ async function ask(question, { hint, terminal = process18 }, render, press) {
1197
1976
  const { stdin, stderr } = terminal;
1198
1977
  if (stdin.isTTY !== true || stderr.isTTY !== true)
1199
1978
  fail(`cannot ask "${question}" off a terminal`, 2, hint);
@@ -1244,15 +2023,15 @@ async function ask(question, { hint, terminal = process13 }, render, press) {
1244
2023
  }
1245
2024
 
1246
2025
  // src/job-picker.ts
1247
- import process14 from "process";
2026
+ import process19 from "process";
1248
2027
 
1249
2028
  // src/jobs.ts
1250
- import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync3 } from "fs";
1251
- import { dirname as dirname4, join as join6, resolve as resolvePath } from "path";
2029
+ import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync4 } from "fs";
2030
+ import { dirname as dirname5, join as join9, resolve as resolvePath } from "path";
1252
2031
 
1253
2032
  // src/steps.ts
1254
2033
  import { readdir as readdir2 } from "fs/promises";
1255
- import { join as join5 } from "path";
2034
+ import { join as join8 } from "path";
1256
2035
  var STEP_NAMES = ["check", "typecheck", "lint", "test"];
1257
2036
  var TARGET = /^@?([\w-]+)(?:[ \t][^:=\n]*)?:(?!=)/gm;
1258
2037
  var JUSTFILES = ["justfile", "Justfile", ".justfile"];
@@ -1264,7 +2043,7 @@ var PHPUNIT_CONFIGS = ["phpunit.xml", "phpunit.xml.dist", "phpunit.dist.xml"];
1264
2043
  var SKIPPED = new Set(["node_modules", "vendor", "dist", "build", "var", "tmp", "coverage"]);
1265
2044
  async function readFirst(dir, files) {
1266
2045
  for (const file of files) {
1267
- const handle = Bun.file(join5(dir, file));
2046
+ const handle = Bun.file(join8(dir, file));
1268
2047
  if (await handle.exists())
1269
2048
  return { file, text: await handle.text() };
1270
2049
  }
@@ -1272,7 +2051,7 @@ async function readFirst(dir, files) {
1272
2051
  }
1273
2052
  async function read(dir, ...files) {
1274
2053
  for (const file of files) {
1275
- const handle = Bun.file(join5(dir, file));
2054
+ const handle = Bun.file(join8(dir, file));
1276
2055
  if (await handle.exists())
1277
2056
  return handle.text();
1278
2057
  }
@@ -1332,7 +2111,7 @@ async function candidates(dir, bin) {
1332
2111
  }
1333
2112
  async function firstFile(dir, names) {
1334
2113
  for (const name of names) {
1335
- if (await Bun.file(join5(dir, name)).exists())
2114
+ if (await Bun.file(join8(dir, name)).exists())
1336
2115
  return name;
1337
2116
  }
1338
2117
  return;
@@ -1359,9 +2138,9 @@ async function discoverProjects(dir) {
1359
2138
  for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
1360
2139
  if (!entry.isDirectory() || entry.name.startsWith(".") || SKIPPED.has(entry.name))
1361
2140
  continue;
1362
- const steps = await discover(join5(dir, entry.name));
2141
+ const steps = await discover(join8(dir, entry.name));
1363
2142
  if (steps.length > 0)
1364
- projects.push({ name: entry.name, dir: join5(dir, entry.name), steps });
2143
+ projects.push({ name: entry.name, dir: join8(dir, entry.name), steps });
1365
2144
  }
1366
2145
  return projects;
1367
2146
  }
@@ -1404,12 +2183,12 @@ function list2(dir) {
1404
2183
  }
1405
2184
  }
1406
2185
  function locate(dir, here, names) {
1407
- for (let current = dir;; current = join6(current, "..")) {
1408
- const found = names.find((name) => existsSync2(join6(current, name)));
2186
+ for (let current = dir;; current = join9(current, "..")) {
2187
+ const found = names.find((name) => existsSync4(join9(current, name)));
1409
2188
  if (found !== undefined)
1410
- return join6(current, found);
2189
+ return join9(current, found);
1411
2190
  const absolute = resolvePath(current);
1412
- if (!here || existsSync2(join6(current, ".git")) || dirname4(absolute) === absolute)
2191
+ if (!here || existsSync4(join9(current, ".git")) || dirname5(absolute) === absolute)
1413
2192
  return;
1414
2193
  }
1415
2194
  }
@@ -1438,7 +2217,7 @@ function justFlags(dir, here) {
1438
2217
  if (here)
1439
2218
  return [];
1440
2219
  const file = list2(dir).find((name) => JUSTFILE.test(name));
1441
- return file === undefined ? undefined : ["--justfile", join6(dir, file)];
2220
+ return file === undefined ? undefined : ["--justfile", join9(dir, file)];
1442
2221
  }
1443
2222
  function just(dir, here) {
1444
2223
  const flags = justFlags(dir, here);
@@ -1498,10 +2277,10 @@ function show(source, target) {
1498
2277
  `).trimEnd();
1499
2278
  }
1500
2279
  function make(dir) {
1501
- const file = MAKEFILES.find((name) => existsSync2(join6(dir, name)));
2280
+ const file = MAKEFILES.find((name) => existsSync4(join9(dir, name)));
1502
2281
  if (file === undefined)
1503
2282
  return [];
1504
- const source = readFileSync3(join6(dir, file), "utf-8");
2283
+ const source = readFileSync4(join9(dir, file), "utf-8");
1505
2284
  return build({ kind: "make", tag: "make", runner: ["make"], separated: false, dir }, targets2(source).map((target) => ({ ...target, body: show(source, target.name) })));
1506
2285
  }
1507
2286
  function manager(dir, manifest) {
@@ -1509,53 +2288,53 @@ function manager(dir, manifest) {
1509
2288
  const known = LOCKFILES.find(([, name]) => name === declared);
1510
2289
  if (known !== undefined)
1511
2290
  return known[1];
1512
- for (let current = resolvePath(dir);; current = dirname4(current)) {
1513
- const found = LOCKFILES.find(([file]) => existsSync2(join6(current, file)));
2291
+ for (let current = resolvePath(dir);; current = dirname5(current)) {
2292
+ const found = LOCKFILES.find(([file]) => existsSync4(join9(current, file)));
1514
2293
  if (found !== undefined)
1515
2294
  return found[1];
1516
- if (dirname4(current) === current)
2295
+ if (dirname5(current) === current)
1517
2296
  return "bun";
1518
2297
  }
1519
2298
  }
1520
- function table3(value) {
2299
+ function table2(value) {
1521
2300
  return value !== null && typeof value === "object" ? value : {};
1522
2301
  }
1523
2302
  function packageScripts(dir, here) {
1524
2303
  const file = locate(dir, here, ["package.json"]);
1525
2304
  if (file === undefined)
1526
2305
  return [];
1527
- const manifest = JSON.parse(readFileSync3(file, "utf-8"));
1528
- const tool = manager(dirname4(file), manifest);
1529
- const items = Object.entries(table3(manifest.scripts)).map(([name, command]) => ({ name, body: text2(command) }));
1530
- return build({ kind: "package", tag: tool, runner: [tool, "run"], separated: tool === "npm", dir: dirname4(file) }, items);
2306
+ const manifest = JSON.parse(readFileSync4(file, "utf-8"));
2307
+ const tool = manager(dirname5(file), manifest);
2308
+ const items = Object.entries(table2(manifest.scripts)).map(([name, command]) => ({ name, body: text2(command) }));
2309
+ return build({ kind: "package", tag: tool, runner: [tool, "run"], separated: tool === "npm", dir: dirname5(file) }, items);
1531
2310
  }
1532
2311
  function composer(dir, here) {
1533
2312
  const file = locate(dir, here, ["composer.json"]);
1534
2313
  if (file === undefined)
1535
2314
  return [];
1536
- const manifest = JSON.parse(readFileSync3(file, "utf-8"));
1537
- const descriptions = table3(manifest["scripts-descriptions"]);
1538
- const items = Object.entries(table3(manifest.scripts)).map(([name, command]) => ({ name, doc: field(descriptions, name), body: text2(command) }));
1539
- return build({ kind: "composer", tag: "composer", runner: ["composer", "run"], separated: true, dir: dirname4(file) }, items);
2315
+ const manifest = JSON.parse(readFileSync4(file, "utf-8"));
2316
+ const descriptions = table2(manifest["scripts-descriptions"]);
2317
+ const items = Object.entries(table2(manifest.scripts)).map(([name, command]) => ({ name, doc: field(descriptions, name), body: text2(command) }));
2318
+ return build({ kind: "composer", tag: "composer", runner: ["composer", "run"], separated: true, dir: dirname5(file) }, items);
1540
2319
  }
1541
2320
  function deno(dir, here) {
1542
2321
  const file = locate(dir, here, ["deno.json", "deno.jsonc"]);
1543
2322
  if (file === undefined)
1544
2323
  return [];
1545
- const manifest = Bun.JSONC.parse(readFileSync3(file, "utf-8"));
1546
- const items = Object.entries(table3(manifest.tasks)).map(([name, task]) => ({ name, doc: field(task, "description"), body: field(task, "command") ?? text2(task) }));
1547
- return build({ kind: "deno", tag: "deno", runner: ["deno", "task"], separated: false, dir: dirname4(file) }, items);
2324
+ const manifest = Bun.JSONC.parse(readFileSync4(file, "utf-8"));
2325
+ const items = Object.entries(table2(manifest.tasks)).map(([name, task]) => ({ name, doc: field(task, "description"), body: field(task, "command") ?? text2(task) }));
2326
+ return build({ kind: "deno", tag: "deno", runner: ["deno", "task"], separated: false, dir: dirname5(file) }, items);
1548
2327
  }
1549
2328
  function taskfile(dir, here) {
1550
2329
  const file = locate(dir, here, TASKFILES);
1551
2330
  if (file === undefined)
1552
2331
  return [];
1553
- const tasks = table3(Bun.YAML.parse(readFileSync3(file, "utf-8"))?.tasks);
2332
+ const tasks = table2(Bun.YAML.parse(readFileSync4(file, "utf-8"))?.tasks);
1554
2333
  const items = Object.entries(tasks).filter(([, task]) => !(task !== null && typeof task === "object" && task.internal === true)).map(([name, task]) => ({ name, doc: field(task, "desc") ?? field(task, "summary"), body: text2(task) }));
1555
- return build({ kind: "task", tag: "task", runner: ["task"], separated: true, dir: dirname4(file) }, items);
2334
+ return build({ kind: "task", tag: "task", runner: ["task"], separated: true, dir: dirname5(file) }, items);
1556
2335
  }
1557
2336
  function mise(dir, here) {
1558
- if (!has("mise") || !here && !MISE_FILES.some((name) => existsSync2(join6(dir, name))))
2337
+ if (!has("mise") || !here && !MISE_FILES.some((name) => existsSync4(join9(dir, name))))
1559
2338
  return [];
1560
2339
  const proc = Bun.spawnSync(["mise", "tasks", "ls", "--json"], { cwd: dir, stderr: "pipe" });
1561
2340
  if (!proc.success)
@@ -1569,15 +2348,15 @@ function pyproject(dir, here) {
1569
2348
  const file = locate(dir, here, ["pyproject.toml"]);
1570
2349
  if (file === undefined)
1571
2350
  return [];
1572
- const manifest = Bun.TOML.parse(readFileSync3(file, "utf-8"));
1573
- const tool = table3(manifest.tool);
1574
- const project = table3(manifest.project);
1575
- const uv = locate(dirname4(file), true, ["uv.lock"]) !== undefined;
1576
- const poe = Object.entries(table3(table3(tool.poe).tasks)).filter(([name]) => !name.startsWith("_")).map(([name, task]) => ({ name, doc: field(task, "help"), body: field(task, "cmd") ?? field(task, "shell") ?? text2(task) }));
1577
- const entryPoints = Object.entries(table3(project.scripts)).map(([name, target]) => ({ name, body: text2(target) }));
2351
+ const manifest = Bun.TOML.parse(readFileSync4(file, "utf-8"));
2352
+ const tool = table2(manifest.tool);
2353
+ const project = table2(manifest.project);
2354
+ const uv = locate(dirname5(file), true, ["uv.lock"]) !== undefined;
2355
+ const poe = Object.entries(table2(table2(tool.poe).tasks)).filter(([name]) => !name.startsWith("_")).map(([name, task]) => ({ name, doc: field(task, "help"), body: field(task, "cmd") ?? field(task, "shell") ?? text2(task) }));
2356
+ const entryPoints = Object.entries(table2(project.scripts)).map(([name, target]) => ({ name, body: text2(target) }));
1578
2357
  return [
1579
- ...build({ kind: "poe", tag: "poe", runner: uv ? ["uv", "run", "poe"] : ["poe"], separated: false, dir: dirname4(file) }, poe),
1580
- ...build({ kind: "uv", tag: "uv", runner: ["uv", "run"], separated: false, dir: dirname4(file) }, entryPoints)
2358
+ ...build({ kind: "poe", tag: "poe", runner: uv ? ["uv", "run", "poe"] : ["poe"], separated: false, dir: dirname5(file) }, poe),
2359
+ ...build({ kind: "uv", tag: "uv", runner: ["uv", "run"], separated: false, dir: dirname5(file) }, entryPoints)
1581
2360
  ];
1582
2361
  }
1583
2362
  var READERS = [just, make, packageScripts, composer, deno, taskfile, mise, pyproject];
@@ -1601,12 +2380,12 @@ function readOr(read, fallback) {
1601
2380
  }
1602
2381
  }
1603
2382
  function workspaces() {
1604
- const manifest = readOr(() => JSON.parse(readFileSync3("package.json", "utf-8")), {});
1605
- const declared = Array.isArray(manifest.workspaces) ? manifest.workspaces : table3(manifest.workspaces).packages;
1606
- const pnpm = readOr(() => table3(Bun.YAML.parse(readFileSync3("pnpm-workspace.yaml", "utf-8"))).packages, undefined);
2383
+ const manifest = readOr(() => JSON.parse(readFileSync4("package.json", "utf-8")), {});
2384
+ const declared = Array.isArray(manifest.workspaces) ? manifest.workspaces : table2(manifest.workspaces).packages;
2385
+ const pnpm = readOr(() => table2(Bun.YAML.parse(readFileSync4("pnpm-workspace.yaml", "utf-8"))).packages, undefined);
1607
2386
  const patterns = [declared, pnpm].flatMap((value) => Array.isArray(value) ? value.filter((pattern) => typeof pattern === "string") : []);
1608
2387
  const excluded = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => new Bun.Glob(pattern.slice(1)));
1609
- return patterns.filter((pattern) => !pattern.startsWith("!")).flatMap((pattern) => [...new Bun.Glob(`${pattern.replace(TRAILING_SLASHES, "")}/package.json`).scanSync({ cwd: "." })].map((file) => dirname4(file))).filter((dir) => !dir.split("/").includes("node_modules") && !excluded.some((glob) => glob.match(dir)));
2388
+ return patterns.filter((pattern) => !pattern.startsWith("!")).flatMap((pattern) => [...new Bun.Glob(`${pattern.replace(TRAILING_SLASHES, "")}/package.json`).scanSync({ cwd: "." })].map((file) => dirname5(file))).filter((dir) => !dir.split("/").includes("node_modules") && !excluded.some((glob) => glob.match(dir)));
1610
2389
  }
1611
2390
  function folders() {
1612
2391
  return [...new Set([...children(), ...workspaces()])].filter((dir) => dir !== ".");
@@ -1616,7 +2395,7 @@ function guarded(reader, dir, here, isWarned = false) {
1616
2395
  return reader(dir, here);
1617
2396
  } catch (error) {
1618
2397
  if (isWarned)
1619
- console.error(`j: skipped ${join6(dir, MANIFEST_OF.get(reader) ?? "a manifest")}, it does not parse (${error instanceof Error ? error.message : String(error)})`);
2398
+ console.error(`j: skipped ${join9(dir, MANIFEST_OF.get(reader) ?? "a manifest")}, it does not parse (${error instanceof Error ? error.message : String(error)})`);
1620
2399
  return [];
1621
2400
  }
1622
2401
  }
@@ -1640,7 +2419,7 @@ function key(entry) {
1640
2419
  function id(entry) {
1641
2420
  return `${entry.tag}:${key(entry)}`;
1642
2421
  }
1643
- function resolve(entries, named) {
2422
+ function resolve3(entries, named) {
1644
2423
  const qualified = QUALIFIED.exec(named);
1645
2424
  const tagged = qualified && entries.some((entry) => entry.tag === qualified[1]) ? qualified : undefined;
1646
2425
  const pool = tagged ? entries.filter((entry) => entry.tag === tagged[1]) : entries;
@@ -1649,7 +2428,7 @@ function resolve(entries, named) {
1649
2428
  return exact.length > 0 ? exact : pool.filter((entry) => entry.name === rest);
1650
2429
  }
1651
2430
  function shortest(entries, entry) {
1652
- const found = resolve(entries, key(entry));
2431
+ const found = resolve3(entries, key(entry));
1653
2432
  return found.length === 1 && found[0] === entry ? key(entry) : id(entry);
1654
2433
  }
1655
2434
  function signature(entry) {
@@ -1662,21 +2441,21 @@ function labelled(entries) {
1662
2441
  return new Set(entries.map((entry) => entry.tag)).size > 1;
1663
2442
  }
1664
2443
  function row(entry, labels, signed) {
1665
- const colors = paint(process14.stderr);
2444
+ const colors = paint(process19.stderr);
1666
2445
  const keyed = entry.dir === "." ? entry.name : `${colors.dim(`${entry.dir}/`)}${entry.name}`;
1667
2446
  return {
1668
2447
  hidden: [entry.kind, entry.dir, entry.name, id(entry)],
1669
2448
  cells: [...labels ? [colors[TINTS[entry.kind]](entry.tag)] : [], keyed, ...signed ? [colors.cyan(signature(entry))] : [], colors.dim(entry.doc ?? "")]
1670
2449
  };
1671
2450
  }
1672
- function pickJob(entries, narrowed = false) {
2451
+ async function pickJob(entries, narrowed = false) {
1673
2452
  const labels = labelled(entries);
1674
2453
  const signed = entries.some((entry) => signature(entry) !== "");
1675
- const picked = fzf(entries.map((entry) => row(entry, labels, signed)), {
2454
+ const picked = await pick(entries.map((entry) => row(entry, labels, signed)), {
1676
2455
  prompt: `${[...new Set(entries.map((entry) => entry.tag))].join("/")}> `,
1677
2456
  searched: labels ? 2 : 1,
1678
2457
  ...narrowed ? { height: heightFor(entries.length) } : {},
1679
- preview: `${process14.execPath} ${process14.argv[1]} --show {1} {2} {3}`
2458
+ preview: `${process19.execPath} ${process19.argv[1]} --show {1} {2} {3}`
1680
2459
  });
1681
2460
  return entries.find((candidate) => id(candidate) === picked?.hidden[3]);
1682
2461
  }
@@ -1685,7 +2464,7 @@ function pickJob(entries, narrowed = false) {
1685
2464
  var usage2 = `j [name] [args...]
1686
2465
  j -
1687
2466
 
1688
- Without a name, picks a recipe, target, script or task of this folder, its parents and its child folders with fzf when it is installed and a terminal is attached, and runs it. The ones run last come first, per folder. Without fzf or a terminal it lists them instead.
2467
+ Without a name, picks a recipe, target, script or task of this folder, its parents and its child folders when a terminal is attached, and runs it. The ones run last come first, per folder. Without a terminal it lists them instead.
1689
2468
  \`j -\` runs the last one again with the same arguments, \`j <name> [args...]\` runs without the picker, the words after the name filling the parameters in order and the required ones left being asked for.
1690
2469
  The sources are a Justfile, a Makefile, the scripts of a package.json (through its package manager), composer.json scripts, deno tasks, a Taskfile, mise tasks and a pyproject (poe tasks and entry points).
1691
2470
  A name is the key behind the folder it runs from, \`api/test\`, bare for this folder. A name several entries share offers them, unless it comes qualified by its runner: \`just:check\`, \`bun:api/test\`.
@@ -1698,7 +2477,7 @@ function preview(kind, dir, name) {
1698
2477
  const entry = readKind(kind, dir).find((candidate) => candidate.name === name);
1699
2478
  if (entry === undefined)
1700
2479
  return;
1701
- const colors = paint(process15.stdout);
2480
+ const colors = paint(process20.stdout);
1702
2481
  console.log(`${colors.dim(`$ ${dir === "." ? "" : `env -C ${dir} `}`)}${colors.bold([...entry.runner, entry.name].join(" "))}
1703
2482
  `);
1704
2483
  if (entry.body !== undefined)
@@ -1709,7 +2488,7 @@ function preview(kind, dir, name) {
1709
2488
  function names(found) {
1710
2489
  const described = (entry) => entry.doc === null || entry.doc === "" ? entry.tag : entry.doc;
1711
2490
  return [...new Set(found.map(key))].flatMap((name) => {
1712
- const same = resolve(found, name);
2491
+ const same = resolve3(found, name);
1713
2492
  return same.length === 1 ? [[name, described(same[0])]] : [[name, same.map((entry) => entry.tag).join(", ")], ...same.map((entry) => [id(entry), described(entry)])];
1714
2493
  });
1715
2494
  }
@@ -1723,8 +2502,8 @@ function listed2(found) {
1723
2502
  editsTyped: true
1724
2503
  }));
1725
2504
  }
1726
- function table4(found) {
1727
- const colors = paint(process15.stdout);
2505
+ function table3(found) {
2506
+ const colors = paint(process20.stdout);
1728
2507
  const labels = labelled(found);
1729
2508
  const rows = found.map((entry) => [...labels ? [entry.tag] : [], key(entry), signature(entry)]);
1730
2509
  const widths = rows[0]?.map((_, column) => Math.max(...rows.map((cells) => cells[column].length))) ?? [];
@@ -1775,7 +2554,7 @@ async function j(argv) {
1775
2554
  if (found.length === 0)
1776
2555
  fail("nothing to run here: no recipe, target, script or task", 1);
1777
2556
  const previous = runs("j");
1778
- const interactive = process15.stdin.isTTY && process15.stderr.isTTY && parsed.values.json !== true;
2557
+ const interactive = process20.stdin.isTTY && process20.stderr.isTTY && parsed.values.json !== true;
1779
2558
  let entry;
1780
2559
  let words = given;
1781
2560
  if (named === "-") {
@@ -1785,27 +2564,25 @@ async function j(argv) {
1785
2564
  fail(earlier ? `${earlier.id} is gone` : "nothing run here yet", 1);
1786
2565
  words = [...earlier.args, ...given];
1787
2566
  } else if (named === undefined) {
1788
- if (!interactive || Bun.which("fzf") === null) {
2567
+ if (!interactive) {
1789
2568
  if (emitting)
1790
- fail("the picker needs a terminal and fzf", 1);
1791
- if (interactive)
1792
- console.error("fzf is not installed, listing what can run instead");
2569
+ fail("the picker needs a terminal", 1);
1793
2570
  if (parsed.values.json === true)
1794
2571
  printJson(found.map((each) => ({ id: id(each), key: key(each), runner: each.tag, dir: each.dir, name: each.name, doc: each.doc, parameters: each.parameters })));
1795
2572
  else
1796
- console.log(table4(found));
2573
+ console.log(table3(found));
1797
2574
  return 0;
1798
2575
  }
1799
- entry = pickJob(byRecency(found, previous, id));
2576
+ entry = await pickJob(byRecency(found, previous, id));
1800
2577
  } else {
1801
- const matching = resolve(found, named);
2578
+ const matching = resolve3(found, named);
1802
2579
  if (matching.length === 0) {
1803
2580
  const nearest = closest(named, found.map(key));
1804
2581
  fail(`nothing named ${named}${nearest === undefined ? "" : `, did you mean ${nearest}?`}`, 1);
1805
2582
  }
1806
- if (matching.length > 1 && (!interactive || Bun.which("fzf") === null))
2583
+ if (matching.length > 1 && !interactive)
1807
2584
  fail(`${named} is several: ${matching.map(id).join(", ")}`, 1, "qualify it with its runner");
1808
- entry = matching.length === 1 ? matching[0] : pickJob(matching, true);
2585
+ entry = matching.length === 1 ? matching[0] : await pickJob(matching, true);
1809
2586
  }
1810
2587
  if (entry === undefined)
1811
2588
  return 1;
@@ -1828,4 +2605,4 @@ async function j(argv) {
1828
2605
  }
1829
2606
 
1830
2607
  // src/j-cli.ts
1831
- process16.exitCode = await runMain({ name: "j", version, run: j });
2608
+ process21.exitCode = await runMain({ name: "j", version, run: j });