@kaynooo/cli-base 0.11.0 → 0.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
3
-
4
- // src/cli.ts
5
- import process19 from "process";
6
- // ../kit/src/args.ts
7
- import process9 from "process";
8
- import { parseArgs } from "util";
9
-
10
- // ../kit/src/format.ts
11
- import process7 from "process";
3
+ var __esm = (fn, res, err) => () => {
4
+ if (fn)
5
+ try {
6
+ res = fn(fn = 0);
7
+ } catch (e) {
8
+ err = [e];
9
+ }
10
+ if (err)
11
+ throw err[0];
12
+ return res;
13
+ };
12
14
 
13
15
  // ../kit/src/mode.ts
14
16
  import process2 from "process";
15
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
16
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
17
17
  function isSet(value) {
18
18
  return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
19
19
  }
@@ -27,12 +27,13 @@ function outputMode(stream = process2.stdout, env = process2.env) {
27
27
  return "terminal";
28
28
  return isSet(env.CI) ? "ci" : "pipe";
29
29
  }
30
+ var MODES, AGENT_VARIABLES;
31
+ var init_mode = __esm(() => {
32
+ MODES = new Set(["terminal", "ci", "agent", "pipe"]);
33
+ AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
34
+ });
30
35
 
31
- // ../kit/src/style.ts
32
- import process6 from "process";
33
-
34
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
35
- var G = /^[a-f0-9]+$/i;
36
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
36
37
  function b(r) {
37
38
  let e = r.startsWith("#") ? r.slice(1) : r;
38
39
  if (!G.test(e))
@@ -43,11 +44,6 @@ function b(r) {
43
44
  throw Error(`Invalid hex color length: ${e.length}`);
44
45
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
45
46
  }
46
- var B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
47
- let [l, n, c] = b(r);
48
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
49
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
50
- var h = new Set(["", "1", "2", "3", "true"]);
51
47
  function C(r, e = globalThis.process?.env ?? {}) {
52
48
  if (e.FORCE_COLOR !== undefined)
53
49
  return h.has(e.FORCE_COLOR);
@@ -84,13 +80,21 @@ function f(r, e = []) {
84
80
  function Fe(r = {}) {
85
81
  return f(r);
86
82
  }
87
- var o = Fe();
83
+ var G, B, h, o;
84
+ var init_chunk_x450vn3m = __esm(() => {
85
+ G = /^[a-f0-9]+$/i;
86
+ B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
87
+ let [l, n, c] = b(r);
88
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
89
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
90
+ h = new Set(["", "1", "2", "3", "true"]);
91
+ o = Fe();
92
+ });
88
93
 
89
- // ../kit/src/theme.ts
90
- import { existsSync as existsSync2, readFileSync, statSync } from "fs";
91
- import { homedir as homedir2 } from "os";
92
- import { join as join3, resolve as resolve2 } from "path";
93
- import process5 from "process";
94
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
95
+ var init_colors = __esm(() => {
96
+ init_chunk_x450vn3m();
97
+ });
94
98
 
95
99
  // ../kit/src/config.ts
96
100
  import { existsSync } from "fs";
@@ -106,48 +110,36 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
106
110
  return;
107
111
  }
108
112
  }
113
+ var init_config = __esm(() => {
114
+ init_args();
115
+ });
109
116
 
110
117
  // ../kit/src/user-config.ts
111
118
  import { homedir } from "os";
112
- import { join as join2 } from "path";
119
+ import { isAbsolute, join as join2 } from "path";
113
120
  import process4 from "process";
121
+ function xdgFolder(value, fallback) {
122
+ return value !== undefined && isAbsolute(value) ? value : fallback;
123
+ }
114
124
  function configBase(where = {}) {
115
125
  const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
116
- return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
126
+ return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
117
127
  }
118
128
  function userConfigPath(bin, where = {}) {
119
129
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
120
130
  }
131
+ var init_user_config = () => {};
121
132
 
122
133
  // ../kit/src/theme.ts
123
- var ENDS = new Map;
124
- var DEFAULT = {
125
- colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
126
- glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
127
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
128
- bins: {},
129
- gradient: ["#c084fc", "#67e8f9"]
130
- };
131
- var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
132
- var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
133
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
134
- var PRESETS = {
135
- default: {},
136
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
137
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
138
- ascii: { glyphs: ASCII }
139
- };
140
- var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
141
- var HEX = /^#[0-9a-f]{6}$/i;
142
- var CONTROL = /\p{Cc}/u;
143
- var MAX_FILE_BYTES = 64 * 1024;
144
- var SPACES = /\s+/;
134
+ import { existsSync as existsSync2, readFileSync, statSync } from "fs";
135
+ import { homedir as homedir2 } from "os";
136
+ import { join as join3, resolve as resolve2 } from "path";
137
+ import process5 from "process";
145
138
  function isColorSpec(spec) {
146
139
  if (typeof spec === "number")
147
140
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
148
141
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
149
142
  }
150
- var CUBE = [0, 95, 135, 175, 215, 255];
151
143
  function cubeLevel(channel) {
152
144
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
153
145
  }
@@ -252,7 +244,6 @@ function applyFile(theme, file, where, warn) {
252
244
  function endsWalk(home) {
253
245
  return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
254
246
  }
255
- var warned = new Set;
256
247
  function warnOnce(message) {
257
248
  if (warned.has(message))
258
249
  return;
@@ -289,8 +280,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
289
280
  }
290
281
  return { theme, sources, preset };
291
282
  }
292
- var current;
293
- var currentKey = "";
294
283
  function activeTheme() {
295
284
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
296
285
  if (current === undefined || key !== currentKey) {
@@ -299,8 +288,38 @@ function activeTheme() {
299
288
  }
300
289
  return current;
301
290
  }
291
+ var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
292
+ var init_theme = __esm(() => {
293
+ init_config();
294
+ init_user_config();
295
+ ENDS = new Map;
296
+ DEFAULT = {
297
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
298
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
299
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
300
+ bins: {},
301
+ gradient: ["#c084fc", "#67e8f9"]
302
+ };
303
+ BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
304
+ MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
305
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
306
+ PRESETS = {
307
+ default: {},
308
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
309
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
310
+ ascii: { glyphs: ASCII }
311
+ };
312
+ 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"]);
313
+ HEX = /^#[0-9a-f]{6}$/i;
314
+ CONTROL = /\p{Cc}/u;
315
+ MAX_FILE_BYTES = 64 * 1024;
316
+ SPACES = /\s+/;
317
+ CUBE = [0, 95, 135, 175, 215, 255];
318
+ warned = new Set;
319
+ });
302
320
 
303
321
  // ../kit/src/style.ts
322
+ import process6 from "process";
304
323
  function takesControlCodes(stream, env = process6.env) {
305
324
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
306
325
  }
@@ -311,17 +330,23 @@ function role(name, stream, env = process6.env) {
311
330
  const colors = paint(stream, env);
312
331
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
313
332
  }
314
- var STATUS_WORDS = {
315
- passed: ["passed", "success", "succeeded", "ok"],
316
- failed: ["failed", "failure", "error", "errored"],
317
- running: ["running", "in_progress", "started", "holding"],
318
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
319
- skipped: ["skipped", "cancelled", "canceled", "manual"]
320
- };
321
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
333
+ var STATUS_WORDS, STATUS_OF;
334
+ var init_style = __esm(() => {
335
+ init_colors();
336
+ init_mode();
337
+ init_theme();
338
+ STATUS_WORDS = {
339
+ passed: ["passed", "success", "succeeded", "ok"],
340
+ failed: ["failed", "failure", "error", "errored"],
341
+ running: ["running", "in_progress", "started", "holding"],
342
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
343
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
344
+ };
345
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
346
+ });
322
347
 
323
348
  // ../kit/src/format.ts
324
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
349
+ import process7 from "process";
325
350
  function formatSeconds(total) {
326
351
  let rest = Math.max(0, Math.round(total));
327
352
  const amounts = UNITS.map(([unit, size]) => {
@@ -342,21 +367,44 @@ function upTo(text, separator) {
342
367
  const end = text.indexOf(separator);
343
368
  return end === -1 ? text : text.slice(0, end);
344
369
  }
345
- var ESCAPE = String.fromCharCode(27);
346
370
  function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
347
371
  return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
348
372
  }
349
373
  function printJson(value) {
350
374
  console.log(jsonText(value));
351
375
  }
376
+ var UNITS, ESCAPE;
377
+ var init_format = __esm(() => {
378
+ init_mode();
379
+ init_style();
380
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
381
+ ESCAPE = String.fromCharCode(27);
382
+ });
352
383
 
353
384
  // ../kit/src/help.ts
354
385
  import process8 from "process";
355
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
356
- var USAGE_PREFIX = /^usage:\s*/i;
357
- var FULL_STOP = /\.$/;
358
386
  function usageLine(usage, colors = paint(process8.stdout)) {
359
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
387
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
388
+ `);
389
+ const blank = lines.indexOf("");
390
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
391
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
392
+ const colon = synopses[0].indexOf(": ");
393
+ const inline = synopses[0].slice(colon + 2);
394
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
395
+ if (colon !== -1)
396
+ synopses[0] = synopses[0].slice(0, colon);
397
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
398
+ `)}`;
399
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
400
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
401
+ return [head, ...lead, ...rest].join(`
402
+ `);
403
+ }
404
+ function prose(line, colors) {
405
+ if (colors.cyan("x") === "x")
406
+ return line;
407
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
360
408
  }
361
409
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
362
410
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -391,7 +439,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
391
439
  return [];
392
440
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
393
441
  }
394
- var MAX_INLINE_CHOICES = 24;
395
442
  function optionRows(options, colors = paint(process8.stdout)) {
396
443
  const rows = Object.entries(options).map(([name, option]) => {
397
444
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -406,6 +453,15 @@ function optionRows(options, colors = paint(process8.stdout)) {
406
453
  const width = Math.max(0, ...rows.map((row) => row.width));
407
454
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
408
455
  }
456
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
457
+ var init_help = __esm(() => {
458
+ init_mode();
459
+ init_style();
460
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
461
+ USAGE_PREFIX = /^usage:\s*/i;
462
+ FULL_STOP = /\.$/;
463
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
464
+ });
409
465
 
410
466
  // ../kit/src/text.ts
411
467
  function distance(a, b) {
@@ -433,8 +489,9 @@ function closest(name, names) {
433
489
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
434
490
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
435
491
  }
492
+ var init_text = () => {};
493
+
436
494
  // ../kit/src/input.ts
437
- var WHOLE = /^\d+$/;
438
495
  function wholeNumber(value, name, fallback, min = 1) {
439
496
  if (value === undefined)
440
497
  return fallback;
@@ -443,8 +500,6 @@ function wholeNumber(value, name, fallback, min = 1) {
443
500
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
444
501
  return number;
445
502
  }
446
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
447
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
448
503
  function duration(value, name, fallback, unit = "s") {
449
504
  if (value === undefined)
450
505
  return fallback;
@@ -454,40 +509,27 @@ function duration(value, name, fallback, unit = "s") {
454
509
  badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
455
510
  return ms;
456
511
  }
512
+ var WHOLE, DURATION, UNIT_MS;
513
+ var init_input = __esm(() => {
514
+ init_args();
515
+ WHOLE = /^\d+$/;
516
+ DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
517
+ UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
518
+ });
457
519
 
458
520
  // ../kit/src/args.ts
459
- var DASHES = /^-+/;
521
+ import process9 from "process";
522
+ import { parseArgs } from "util";
460
523
  function jsonOption(holds) {
461
524
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
462
525
  }
463
- class Exit extends Error {
464
- code;
465
- hint;
466
- constructor(message, code, hint) {
467
- super(message);
468
- this.code = code;
469
- this.hint = hint;
470
- }
471
- }
472
526
  function fail(message, code = 2, hint) {
473
527
  throw new Exit(message, code, hint);
474
528
  }
475
-
476
- class UsageError extends Exit {
477
- constructor(message, hint) {
478
- super(message, 2, hint);
479
- }
480
- }
481
529
  function badUsage(message) {
482
530
  throw new UsageError(message);
483
531
  }
484
532
 
485
- class HelpShown extends Exit {
486
- constructor() {
487
- super("help shown", 0);
488
- }
489
- }
490
-
491
533
  class Completing {
492
534
  options;
493
535
  positionals;
@@ -498,11 +540,6 @@ class Completing {
498
540
  this.candidates = candidates;
499
541
  }
500
542
  }
501
- var completion = { active: false };
502
- var OUTPUT_OPTIONS = {
503
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
504
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
505
- };
506
543
  function applyOutput(color, plain, env = process9.env) {
507
544
  const when = plain === true ? "never" : color ?? "auto";
508
545
  if (when === "auto")
@@ -656,7 +693,6 @@ function parseError(error) {
656
693
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
657
694
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
658
695
  }
659
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
660
696
  function nearestOption(message, options, allowNegative) {
661
697
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
662
698
  if (typed === undefined)
@@ -672,6 +708,61 @@ function nearestOption(message, options, allowNegative) {
672
708
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
673
709
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
674
710
  }
711
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
712
+ var init_args = __esm(() => {
713
+ init_format();
714
+ init_help();
715
+ init_text();
716
+ init_help();
717
+ init_input();
718
+ DASHES = /^-+/;
719
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
720
+ Exit = class Exit extends Error {
721
+ code;
722
+ hint;
723
+ [EXIT] = true;
724
+ constructor(message, code, hint) {
725
+ super(message);
726
+ this.code = code;
727
+ this.hint = hint;
728
+ }
729
+ static [Symbol.hasInstance](value) {
730
+ if (this !== Exit)
731
+ return Function.prototype[Symbol.hasInstance].call(this, value);
732
+ return typeof value === "object" && value !== null && value[EXIT] === true;
733
+ }
734
+ };
735
+ UsageError = class UsageError extends Exit {
736
+ constructor(message, hint) {
737
+ super(message, 2, hint);
738
+ }
739
+ };
740
+ HelpShown = class HelpShown extends Exit {
741
+ constructor() {
742
+ super("help shown", 0);
743
+ }
744
+ };
745
+ completion = { active: false };
746
+ OUTPUT_OPTIONS = {
747
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
748
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
749
+ };
750
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
751
+ });
752
+
753
+ // ../kit/src/folders.ts
754
+ var SKIPPED_FOLDERS;
755
+ var init_folders = __esm(() => {
756
+ init_user_config();
757
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
758
+ });
759
+
760
+ // src/cli.ts
761
+ import process20 from "process";
762
+
763
+ // ../kit/src/index.ts
764
+ init_args();
765
+
675
766
  // ../kit/src/argv.ts
676
767
  import { readFileSync as readFileSync2, realpathSync } from "fs";
677
768
  import { resolve as resolve3 } from "path";
@@ -696,11 +787,25 @@ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), scr
696
787
  const after = at === -1 ? [] : cmdline.slice(at + 1);
697
788
  return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
698
789
  }
790
+ // ../kit/src/chart.ts
791
+ init_format();
792
+ init_mode();
793
+ init_style();
794
+ init_theme();
795
+ // ../kit/src/ci.ts
796
+ init_args();
797
+ init_format();
798
+
799
+ // ../kit/src/progress.ts
800
+ init_format();
801
+
699
802
  // ../kit/src/process.ts
803
+ import { readFileSync as readFileSync3 } from "fs";
700
804
  import { constants } from "os";
701
805
  import process11 from "process";
702
806
  var KILL_GRACE_MS = 2000;
703
807
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
808
+ var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
704
809
  function exitCodeOf(code, signal) {
705
810
  if (code !== null)
706
811
  return code;
@@ -708,6 +813,21 @@ function exitCodeOf(code, signal) {
708
813
  return 128 + signal;
709
814
  return signal === null ? 129 : 128 + constants.signals[signal];
710
815
  }
816
+ function groupsOf(pid) {
817
+ try {
818
+ const stat = readFileSync3(`/proc/${pid}/stat`, "utf8");
819
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
820
+ return { group: Number(fields[2]), foreground: Number(fields[5]) };
821
+ } catch {
822
+ return;
823
+ }
824
+ }
825
+ function heardTheTerminal(child) {
826
+ if (child.pid === undefined)
827
+ return false;
828
+ const own = groupsOf("self");
829
+ return own !== undefined && own.group === own.foreground && groupsOf(child.pid)?.group === own.group;
830
+ }
711
831
  function holdSignals(cleanup) {
712
832
  let received;
713
833
  let child;
@@ -726,7 +846,8 @@ function holdSignals(cleanup) {
726
846
  function onSignal(signal) {
727
847
  received = signal;
728
848
  if (child !== undefined) {
729
- child.kill(signal);
849
+ if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
850
+ child.kill(signal);
730
851
  return;
731
852
  }
732
853
  if (cleanup === undefined)
@@ -739,10 +860,10 @@ function holdSignals(cleanup) {
739
860
  process11.on(signal, onSignal);
740
861
  return held;
741
862
  }
742
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
863
+ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
743
864
  const chunks = [];
744
865
  const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
745
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
866
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin: input === undefined ? stdin : new TextEncoder().encode(input), stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
746
867
  const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
747
868
  const timers = [];
748
869
  const killGroup = (killing) => {
@@ -782,12 +903,19 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
782
903
  stop();
783
904
  continue;
784
905
  }
906
+ if (state.truncated)
907
+ continue;
908
+ let kept = data;
785
909
  if (state.kept + data.length > maxBytes) {
910
+ let cut = maxBytes - state.kept;
911
+ while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
912
+ cut--;
913
+ kept = data.subarray(0, cut);
786
914
  state.truncated = true;
787
- continue;
788
915
  }
789
- state.kept += data.length;
790
- chunks.push({ stream: name, data });
916
+ state.kept += kept.length;
917
+ if (kept.length > 0)
918
+ chunks.push({ stream: name, data: kept });
791
919
  }
792
920
  };
793
921
  try {
@@ -804,6 +932,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
804
932
  const joined = () => Buffer.concat(chunks.map(({ data }) => data));
805
933
  let output;
806
934
  let text;
935
+ let stdout;
807
936
  return {
808
937
  code: exitCodeOf(proc.exitCode, proc.signalCode),
809
938
  chunks,
@@ -814,49 +943,168 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
814
943
  },
815
944
  get text() {
816
945
  return text ??= (output ??= joined()).toString();
946
+ },
947
+ get stdout() {
948
+ return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
817
949
  }
818
950
  };
819
951
  }
820
952
 
821
953
  // ../kit/src/progress.ts
954
+ init_style();
955
+ init_theme();
822
956
  var ESC = String.fromCharCode(27);
823
957
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
824
958
  var RESET_STYLE = `${ESC}[0m`;
825
959
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
960
+
961
+ // ../kit/src/ci.ts
962
+ init_style();
963
+
964
+ // ../kit/src/tool.ts
965
+ init_format();
826
966
  // ../kit/src/cli.ts
827
- import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
967
+ init_args();
968
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
828
969
  import { dirname as dirname3, join as join5 } from "path";
829
- import process14 from "process";
970
+ import process15 from "process";
830
971
 
831
- // ../kit/src/notify.ts
972
+ // ../kit/src/askpass.ts
832
973
  import process12 from "process";
974
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
975
+ async function askpassClient(argv) {
976
+ const socketPath = process12.env[SOCKET_VARIABLE];
977
+ if (socketPath === undefined)
978
+ return;
979
+ const request = { prompt: argv[0] ?? "", ...process12.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
980
+ const { promise, resolve } = Promise.withResolvers();
981
+ let received = "";
982
+ try {
983
+ await Bun.connect({
984
+ unix: socketPath,
985
+ socket: {
986
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
987
+ `),
988
+ data: (_, chunk) => {
989
+ received += chunk.toString();
990
+ },
991
+ close: () => resolve(received),
992
+ error: () => resolve("")
993
+ }
994
+ });
995
+ } catch {
996
+ return 1;
997
+ }
998
+ const reply = await promise;
999
+ if (reply === "")
1000
+ return 1;
1001
+ const { answer } = JSON.parse(reply);
1002
+ if (request.notice === true)
1003
+ return 0;
1004
+ if (answer === undefined)
1005
+ return 1;
1006
+ process12.stdout.write(`${answer}
1007
+ `);
1008
+ return 0;
1009
+ }
1010
+
1011
+ // ../kit/src/completions.ts
1012
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1013
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
1014
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1015
+ set -l current (commandline -ct)
1016
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1017
+ if test "$line" = __files__
1018
+ __fish_complete_path $current
1019
+ else
1020
+ echo $line
1021
+ end
1022
+ end
1023
+ end`;
1024
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1025
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1026
+ local -a lines
1027
+ COMPREPLY=()
1028
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1029
+ for line in "\${lines[@]}"; do
1030
+ if [[ $line == __files__ ]]; then
1031
+ COMPREPLY+=($(compgen -f -- "$cur"))
1032
+ else
1033
+ words+="\${line%%$'\\t'*}"$'\\n'
1034
+ fi
1035
+ done
1036
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1037
+ }`;
1038
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1039
+ local line
1040
+ local -a described plain
1041
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1042
+ if [[ $line == __files__ ]]; then
1043
+ _files
1044
+ elif [[ $line == *$'\\t'* ]]; then
1045
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1046
+ else
1047
+ plain+=("$line")
1048
+ fi
1049
+ done
1050
+ (( \${#described} )) && _describe -V value described
1051
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1052
+ return 0
1053
+ }`;
1054
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1055
+ if (shell === "fish")
1056
+ return `${header}
1057
+ ${FISH_FUNCTION}
1058
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1059
+ `).join("")}`;
1060
+ if (shell === "bash")
1061
+ return `${header}
1062
+ ${BASH_FUNCTION}
1063
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1064
+ `;
1065
+ return `${header}
1066
+ ${ZSH_FUNCTION}
1067
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1068
+ `;
1069
+ }
1070
+
1071
+ // ../kit/src/notify.ts
1072
+ init_format();
1073
+ init_mode();
1074
+ import process13 from "process";
833
1075
  var NOTIFY_AFTER_MS = 1e4;
834
1076
  var CANCELLED = 130;
835
1077
  function base64(text) {
836
1078
  return Buffer.from(text).toString("base64");
837
1079
  }
838
- function notification(title, body, env = process12.env) {
839
- const id = `kit${process12.pid}`;
1080
+ function notification(title, body, env = process13.env) {
1081
+ const id = `kit${process13.pid}`;
840
1082
  const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
841
1083
  return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
842
1084
  }
843
- function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
1085
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
844
1086
  if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
845
1087
  return;
846
1088
  stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
847
1089
  }
848
1090
 
1091
+ // ../kit/src/cli.ts
1092
+ init_style();
1093
+ init_text();
1094
+
849
1095
  // ../kit/src/usage.ts
850
1096
  import { appendFileSync, mkdirSync } from "fs";
851
1097
  import { homedir as homedir3 } from "os";
852
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
853
- import process13 from "process";
1098
+ import { dirname as dirname2, join as join4 } from "path";
1099
+ import process14 from "process";
854
1100
 
855
1101
  // ../kit/src/logs.ts
1102
+ init_user_config();
856
1103
  var DAY_MS = 24 * 60 * 60 * 1000;
857
1104
  var CLI_FOLDER = "kaynooo-cli";
858
1105
 
859
1106
  // ../kit/src/usage.ts
1107
+ init_user_config();
860
1108
  var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
861
1109
  var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
862
1110
  var LONGEST_NAME = 40;
@@ -864,14 +1112,13 @@ var usageError;
864
1112
  function noteUsageError(message) {
865
1113
  usageError = message;
866
1114
  }
867
- function stateHome(env = process13.env) {
868
- const dir = env.XDG_STATE_HOME;
869
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1115
+ function stateHome(env = process14.env) {
1116
+ return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
870
1117
  }
871
- function usagePath(env = process13.env) {
1118
+ function usagePath(env = process14.env) {
872
1119
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
873
1120
  }
874
- function usageRecorded(env = process13.env) {
1121
+ function usageRecorded(env = process14.env) {
875
1122
  const off = env.KAYNOOO_CLI_NO_USAGE;
876
1123
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
877
1124
  }
@@ -880,12 +1127,12 @@ function flagNames(argv) {
880
1127
  const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
881
1128
  return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
882
1129
  }
883
- function usageEntry(bin, command, argv, code, now = new Date) {
1130
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
884
1131
  const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
885
1132
  usageError = undefined;
886
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1133
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
887
1134
  }
888
- function recordUsage(entry, env = process13.env) {
1135
+ function recordUsage(entry, env = process14.env) {
889
1136
  if (!usageRecorded(env))
890
1137
  return;
891
1138
  try {
@@ -901,7 +1148,11 @@ var LEVEL_OPTIONS = {
901
1148
  ...OUTPUT_OPTIONS,
902
1149
  help: { type: "boolean", short: "h", description: "show this help" }
903
1150
  };
904
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1151
+ var TOP_OPTIONS = {
1152
+ ...LEVEL_OPTIONS,
1153
+ version: { type: "boolean", short: "v", description: "print the version" },
1154
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1155
+ };
905
1156
  async function commandRows(all, colors) {
906
1157
  const commands = shown(all);
907
1158
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -936,6 +1187,10 @@ function takeOutputFlags(argv) {
936
1187
  async function resolveSummary(summary) {
937
1188
  return typeof summary === "string" ? summary : summary();
938
1189
  }
1190
+ function lookup({ commands, aliases }, word) {
1191
+ const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
1192
+ return Object.hasOwn(commands, name) ? commands[name] : undefined;
1193
+ }
939
1194
  function scopeOf(commands, extra, aliases) {
940
1195
  return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
941
1196
  }
@@ -975,8 +1230,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
975
1230
  `);
976
1231
  }
977
1232
  function printError(prefix, message, hint, cause) {
978
- const colors = paint(process14.stderr);
979
- const styled = takesControlCodes(process14.stderr);
1233
+ const colors = paint(process15.stderr);
1234
+ const styled = takesControlCodes(process15.stderr);
980
1235
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
981
1236
  const under = (label, text, tint) => text === undefined ? "" : `
982
1237
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1019,23 +1274,23 @@ async function dispatch(level, typed, { version, redact }) {
1019
1274
  }
1020
1275
  }
1021
1276
  if (name === undefined && level.path.length > 1) {
1022
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
1277
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
1023
1278
  return 2;
1024
1279
  }
1025
1280
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1026
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
1281
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
1027
1282
  return 0;
1028
1283
  }
1029
1284
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
1030
1285
  console.log(version);
1031
1286
  return 0;
1032
1287
  }
1033
- let command = level.commands[level.aliases?.[name] ?? name];
1288
+ let command = lookup(level, name);
1034
1289
  let rest = args;
1035
1290
  let ran = name;
1036
1291
  if (command === undefined && level.lazy.length > 0) {
1037
1292
  level = await expand(level, [...level.path.slice(1), ...argv]);
1038
- command = level.commands[level.aliases?.[name] ?? name];
1293
+ command = lookup(level, name);
1039
1294
  }
1040
1295
  if (command === undefined && level.defaultCommand !== undefined) {
1041
1296
  command = level.commands[level.defaultCommand];
@@ -1115,18 +1370,19 @@ async function leafCandidates(run, words) {
1115
1370
  async function candidates(scope, defaultCommand, words, before = []) {
1116
1371
  const [word = "", ...rest] = words;
1117
1372
  const listing = rest.length === 0 && !word.startsWith("-");
1118
- let { commands, aliases } = scope;
1119
- let command = commands[aliases?.[word] ?? word];
1373
+ let { commands } = scope;
1374
+ let command = lookup(scope, word);
1120
1375
  if (listing || command === undefined) {
1121
- ({ commands, aliases } = await expand(scope, [...before, ...words]));
1122
- command = commands[aliases?.[word] ?? word];
1376
+ const expanded = await expand(scope, [...before, ...words]);
1377
+ commands = expanded.commands;
1378
+ command = lookup(expanded, word);
1123
1379
  }
1124
1380
  if (listing) {
1125
1381
  const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1126
1382
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1127
1383
  const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1128
1384
  const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1129
- return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
1385
+ return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
1130
1386
  }
1131
1387
  if (command === undefined) {
1132
1388
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
@@ -1134,6 +1390,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1134
1390
  }
1135
1391
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1136
1392
  }
1393
+ var COMPLETIONS = "--completions";
1394
+ function flagValue([flag = "", ...rest]) {
1395
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1396
+ }
1397
+ function printCompletionScript(name, args) {
1398
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1399
+ if (shell === undefined || args.length !== 1) {
1400
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1401
+ return 2;
1402
+ }
1403
+ console.log(completionScript(shell, [name]).trimEnd());
1404
+ return 0;
1405
+ }
1137
1406
  async function printCandidates(found) {
1138
1407
  for (const line of await found)
1139
1408
  console.log(line);
@@ -1146,7 +1415,7 @@ function packageVersion(entry = Bun.main) {
1146
1415
  } catch {}
1147
1416
  for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1148
1417
  try {
1149
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1418
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1150
1419
  if (typeof version === "string")
1151
1420
  return version;
1152
1421
  } catch {}
@@ -1156,15 +1425,20 @@ function packageVersion(entry = Bun.main) {
1156
1425
  }
1157
1426
  async function runCli(cli, argv = scriptArgs()) {
1158
1427
  const version = cli.version ?? packageVersion();
1428
+ const answered = await askpassClient(argv);
1429
+ if (answered !== undefined)
1430
+ return answered;
1159
1431
  if (argv[0] === COMPLETE)
1160
1432
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1433
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1434
+ return printCompletionScript(cli.name, flagValue(argv));
1161
1435
  const started = performance.now();
1162
1436
  const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1163
1437
  const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1164
1438
  notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1165
1439
  if (cli.usage !== false) {
1166
1440
  try {
1167
- recordUsage(usageEntry(cli.name, command, argv, code));
1441
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
1168
1442
  } catch {}
1169
1443
  }
1170
1444
  return code;
@@ -1173,8 +1447,7 @@ function commandPath(scope, argv) {
1173
1447
  const path = [];
1174
1448
  let level = scope;
1175
1449
  for (const word of argv.filter((each) => !each.startsWith("-"))) {
1176
- const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1177
- const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1450
+ const command = lookup(level, word);
1178
1451
  if (command === undefined)
1179
1452
  break;
1180
1453
  path.push(word);
@@ -1184,44 +1457,56 @@ function commandPath(scope, argv) {
1184
1457
  }
1185
1458
  return path.length === 0 ? undefined : path.join(" ");
1186
1459
  }
1187
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1188
- if (argv[0] === COMPLETE)
1189
- return printCandidates(leafCandidates(run, argv.slice(1)));
1190
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1191
- console.log(version ?? packageVersion());
1192
- return 0;
1193
- }
1194
- let code;
1195
- const started = performance.now();
1196
- try {
1197
- code = await run(argv);
1198
- } catch (error) {
1199
- code = reportThrown(name, error, redact, wantsJson(argv));
1200
- }
1201
- notifyEnd(name, code, performance.now() - started);
1202
- if (usage !== false) {
1203
- try {
1204
- recordUsage(usageEntry(name, undefined, argv, code));
1205
- } catch {}
1206
- }
1207
- return code;
1208
- }
1209
- // ../kit/src/folders.ts
1210
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1460
+
1461
+ // ../kit/src/index.ts
1462
+ init_config();
1463
+
1464
+ // ../kit/src/excerpt.ts
1465
+ init_text();
1466
+
1467
+ // ../kit/src/index.ts
1468
+ init_folders();
1469
+ init_format();
1470
+
1471
+ // ../kit/src/git.ts
1472
+ init_args();
1473
+ // ../kit/src/limit.ts
1474
+ init_args();
1475
+
1476
+ // ../kit/src/index.ts
1477
+ init_mode();
1478
+
1479
+ // ../kit/src/report.ts
1480
+ init_style();
1481
+ init_text();
1211
1482
  // ../kit/src/secrets.ts
1212
1483
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1484
+ var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
1213
1485
  // ../kit/src/sessions.ts
1214
1486
  var {Glob } = globalThis.Bun;
1215
1487
  var SESSION_FILES = new Glob("*.json");
1216
1488
  var ACCOUNT_DIRS = new Glob("*/sessions");
1489
+
1490
+ // ../kit/src/index.ts
1491
+ init_style();
1492
+ init_text();
1493
+ init_theme();
1494
+ init_user_config();
1495
+
1496
+ // ../kit/src/watch.ts
1497
+ init_args();
1498
+ init_input();
1499
+ init_style();
1500
+ // ../kit/src/workspace-root.ts
1501
+ init_user_config();
1217
1502
  // src/base.ts
1218
- import process17 from "process";
1503
+ import process18 from "process";
1219
1504
 
1220
1505
  // src/worktree.ts
1221
- import { cpSync, existsSync as existsSync3, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync3, rmSync, symlinkSync, unlinkSync } from "fs";
1506
+ import { chmodSync, cpSync, existsSync as existsSync3, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync3, rmSync, symlinkSync, unlinkSync } from "fs";
1222
1507
  import { tmpdir } from "os";
1223
1508
  import { basename, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative, resolve as resolve4, sep } from "path";
1224
- import process16 from "process";
1509
+ import process17 from "process";
1225
1510
  var WHITESPACE = /\s/;
1226
1511
  var ORIGIN_PREFIX = /^origin\//;
1227
1512
  var ENV_FILE = /^\.env(?:\..+)?$/;
@@ -1230,9 +1515,6 @@ var TRAILING_SLASH = /\/$/;
1230
1515
  var PARENT = `..${sep}`;
1231
1516
  var BASE_DIR = /^base-\w{6}$/;
1232
1517
  var CONTAINER = /(?:^|[\s;&|(])(?:docker\s+compose|docker-compose)\s+(?:-\S+(?:\s+[^-\s]\S*)?\s+)*(?:exec|run)\b|(?:^|[\s;&|(])docker\s+exec\b/;
1233
- function stdoutOf(ran) {
1234
- return Buffer.concat(ran.chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString().trim();
1235
- }
1236
1518
  async function git2(args, cwd) {
1237
1519
  return runCommand(["git", ...args], { cwd });
1238
1520
  }
@@ -1243,7 +1525,7 @@ async function checkout(cwd) {
1243
1525
  const ran = await git2(["rev-parse", "--show-toplevel", "--show-prefix"], cwd);
1244
1526
  if (ran.code !== 0)
1245
1527
  fail("not inside a git repository");
1246
- const [root = "", prefix = ""] = stdoutOf(ran).split(`
1528
+ const [root = "", prefix = ""] = ran.stdout.trim().split(`
1247
1529
  `);
1248
1530
  return { root, prefix };
1249
1531
  }
@@ -1251,20 +1533,20 @@ async function resolveRef(root, ref) {
1251
1533
  const ran = await git2(["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`], root);
1252
1534
  if (ran.code !== 0)
1253
1535
  fail(`no commit ${ref} in this repository`);
1254
- return stdoutOf(ran);
1536
+ return ran.stdout.trim();
1255
1537
  }
1256
1538
  async function defaultRemoteRef(root) {
1257
1539
  const head = await git2(["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"], root);
1258
- return head.code === 0 && stdoutOf(head) !== "" ? stdoutOf(head) : "origin/main";
1540
+ return head.code === 0 && head.stdout.trim() !== "" ? head.stdout.trim() : "origin/main";
1259
1541
  }
1260
1542
  async function defaultProofRef(root) {
1261
1543
  const branch = await git2(["symbolic-ref", "--quiet", "--short", "HEAD"], root);
1262
1544
  const remote = await defaultRemoteRef(root);
1263
- if (branch.code !== 0 || stdoutOf(branch) === remote.replace(ORIGIN_PREFIX, ""))
1545
+ if (branch.code !== 0 || branch.stdout.trim() === remote.replace(ORIGIN_PREFIX, ""))
1264
1546
  return "HEAD";
1265
1547
  const base = await git2(["merge-base", "HEAD", remote], root);
1266
1548
  const head = await git2(["rev-parse", "HEAD"], root);
1267
- return base.code === 0 && stdoutOf(base) !== stdoutOf(head) ? stdoutOf(base) : "HEAD";
1549
+ return base.code === 0 && base.stdout.trim() !== head.stdout.trim() ? base.stdout.trim() : "HEAD";
1268
1550
  }
1269
1551
  function keptPaths(root, cwd, paths) {
1270
1552
  const realRoot = realpathSync3(root);
@@ -1292,7 +1574,7 @@ async function linkedEntries(root) {
1292
1574
  const ran = await git2(["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"], root);
1293
1575
  if (ran.code !== 0)
1294
1576
  return [];
1295
- return stdoutOf(ran).split("\x00").filter((entry) => {
1577
+ return ran.stdout.trim().split("\x00").filter((entry) => {
1296
1578
  const folder = entry.endsWith("/");
1297
1579
  const name = basename(entry);
1298
1580
  return folder ? DEPENDENCIES.has(name) : ENV_FILE.test(name);
@@ -1371,14 +1653,34 @@ function linkModules(root, dir, folder) {
1371
1653
  return links;
1372
1654
  }
1373
1655
  var STALE_AFTER = 24 * 60 * 60 * 1000;
1656
+ function makeWritable(path) {
1657
+ const stat = lstatSync(path, { throwIfNoEntry: false });
1658
+ if (stat?.isDirectory() !== true)
1659
+ return;
1660
+ chmodSync(path, stat.mode | 448);
1661
+ for (const entry of readdirSync(path))
1662
+ makeWritable(join6(path, entry));
1663
+ }
1664
+ function removeTree(path) {
1665
+ try {
1666
+ rmSync(path, { recursive: true, force: true });
1667
+ } catch {
1668
+ try {
1669
+ makeWritable(path);
1670
+ rmSync(path, { recursive: true, force: true });
1671
+ } catch (error) {
1672
+ console.error(`${role("warn", process17.stderr)("base:")} could not remove ${path}: ${error instanceof Error ? error.message : String(error)}`);
1673
+ }
1674
+ }
1675
+ }
1374
1676
  async function sweepStale(root) {
1375
1677
  for (const name of readdirSync(tmpdir())) {
1376
1678
  if (!BASE_DIR.test(name))
1377
1679
  continue;
1378
1680
  const path = join6(tmpdir(), name);
1379
1681
  const stat = lstatSync(path, { throwIfNoEntry: false });
1380
- if (stat?.isDirectory() === true && stat.uid === process16.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1381
- rmSync(path, { recursive: true, force: true });
1682
+ if (stat?.isDirectory() === true && stat.uid === process17.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1683
+ removeTree(path);
1382
1684
  }
1383
1685
  await git2(["worktree", "prune"], root);
1384
1686
  }
@@ -1388,7 +1690,7 @@ async function removeWorktree(root, dir, links) {
1388
1690
  unlinkSync(link);
1389
1691
  }
1390
1692
  await git2(["worktree", "remove", "--force", dir], root);
1391
- rmSync(dirname4(dir), { recursive: true, force: true });
1693
+ removeTree(dirname4(dir));
1392
1694
  await git2(["worktree", "prune"], root);
1393
1695
  }
1394
1696
  function shellCommand(given) {
@@ -1455,7 +1757,9 @@ async function inWorktree(options, body) {
1455
1757
  }
1456
1758
 
1457
1759
  // src/base.ts
1458
- var USAGE = `base [--ref <rev>] [--keep <path>...] [--no-link] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, the working tree untouched, exiting with its code
1760
+ var USAGE = `base [--ref <rev>] [--keep <path>...] [--no-link] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, exiting with its code
1761
+
1762
+ The changes of the working tree stay out of the run, but its ignored env files, node_modules, vendor and .venv are linked in, so a write to them lands in the working tree; --no-link runs fully apart.
1459
1763
 
1460
1764
  Exits with the code of the command, 127 when it cannot be started, 2 on a usage error, an unknown ref or a refused command.`;
1461
1765
  var OPTIONS = {
@@ -1474,23 +1778,23 @@ ${USAGE}`);
1474
1778
  if (runsInContainer(given))
1475
1779
  fail("a container of the compose project mounts the main checkout, not the temporary worktree, so the command would not run at the ref: run the tool on the host, or check the ref out by hand");
1476
1780
  const command = shellCommand(given);
1477
- const cwd = process17.cwd();
1781
+ const cwd = process18.cwd();
1478
1782
  const { root, prefix } = await checkout(cwd);
1479
1783
  const ref = parsed.values.ref ?? "HEAD";
1480
1784
  const sha = await resolveRef(root, ref);
1481
1785
  const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
1482
1786
  const ran = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true }, async (runDir, signals) => runIn(runDir, command, signals));
1483
1787
  if (!ran.started)
1484
- console.error(`${role("problem", process17.stderr)("base:")} ${ran.output}`);
1485
- console.error(`${role("label", process17.stderr)("base:")} ran at ${ref} (${sha.slice(0, 7)}), exit ${ran.code}`);
1788
+ console.error(`${role("problem", process18.stderr)("base:")} ${ran.output}`);
1789
+ console.error(`${role("label", process18.stderr)("base:")} ran at ${ref} (${sha.slice(0, 7)}), exit ${ran.code}`);
1486
1790
  return ran.code;
1487
1791
  }
1488
1792
 
1489
1793
  // src/proof.ts
1490
- import process18 from "process";
1491
- var USAGE2 = `proof [--ref <rev>] [--runs <n>] [--keep <path>...] [--timeout <duration>] [--no-link] [--json] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, then in the working tree, to show that a test fails before a change and passes after it
1794
+ import process19 from "process";
1795
+ var USAGE2 = `base proof [--ref <rev>] [--runs <n>] [--keep <path>...] [--timeout <duration>] [--no-link] [--json] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, then in the working tree, to show that a test fails before a change and passes after it
1492
1796
 
1493
- The ref defaults to the merge base with the default branch of origin (origin/main unless origin/HEAD names another) when HEAD is on a branch ahead of it, else HEAD. --runs <n> runs the command n times now, for a flaky test, and every run must pass. --timeout kills a run that lasts longer (a hung test), which says nothing about the change and ends with exit 2.`;
1797
+ The ignored env files, node_modules, vendor and .venv of the working tree are linked into the temporary worktree, writes included; --no-link runs fully apart. The ref defaults to the merge base with the default branch of origin (origin/main unless origin/HEAD names another) when HEAD is on a branch ahead of it, else HEAD. --runs <n> runs the command n times now, for a flaky test, and every run must pass. --timeout kills a run that lasts longer (a hung test), which says nothing about the change and ends with exit 2.`;
1494
1798
  var EXITS = [[0, "the command fails before and passes in every run now"], [1, "it passes before too, fails in any run now, or passes before and fails now"], [2, "a usage error, an unknown ref, a command that cannot start, ends with exit 126, 127, 125 or a signal, or runs past --timeout"], [130, "interrupted (128 plus the signal)"]];
1495
1799
  var OPTIONS2 = {
1496
1800
  ref: { type: "string", short: "r", description: "the commit to run before at (default: the merge base with the default branch of origin on a branch ahead of it, else HEAD)" },
@@ -1529,7 +1833,7 @@ function describe(outcome, at, now) {
1529
1833
  }
1530
1834
  async function proof(argv) {
1531
1835
  const bare = argv[0] !== undefined && !argv[0].startsWith("-");
1532
- const parsed = parse(bare ? [] : argv, USAGE2, OPTIONS2, { rest: true, exits: EXITS, replaces: "running a test, stashing the change and running it again", examples: [["proof --keep tests/fix.test.ts -- bun test tests/fix.test.ts", "the new test fails at HEAD and passes now"], ["proof --ref v1.2.0 --keep tests/fix.test.ts -- bun test tests/fix.test.ts", "the same against a release"]] });
1836
+ const parsed = parse(bare ? [] : argv, USAGE2, OPTIONS2, { rest: true, exits: EXITS, replaces: "running a test, stashing the change and running it again", examples: [["base proof --keep tests/fix.test.ts -- bun test tests/fix.test.ts", "the new test fails at HEAD and passes now"], ["base proof --ref v1.2.0 --keep tests/fix.test.ts -- bun test tests/fix.test.ts", "the same against a release"]] });
1533
1837
  const given = bare ? argv : parsed.rest ?? [];
1534
1838
  if (given.length === 0 || parsed.positionals.length > 0)
1535
1839
  fail(`give the command after --
@@ -1538,7 +1842,7 @@ ${USAGE2}`);
1538
1842
  if (runsInContainer(given))
1539
1843
  fail("a container of the compose project mounts the main checkout, not the temporary worktree, so the command would not run at the ref: run the tool on the host, or check the ref out by hand");
1540
1844
  const command = shellCommand(given);
1541
- const cwd = process18.cwd();
1845
+ const cwd = process19.cwd();
1542
1846
  const { root, prefix } = await checkout(cwd);
1543
1847
  const runs = wholeNumber(parsed.values.runs, "runs", 1, 1);
1544
1848
  const ref = parsed.values.ref ?? await defaultProofRef(root);
@@ -1578,7 +1882,7 @@ ${folded(run.output)}`}`);
1578
1882
  printJson({ outcome, proved, ref, sha, before: { code: before.code, output: before.output }, now: { code: now.code, output: now.output }, runs: nowRuns.map((run) => ({ code: run.code })) });
1579
1883
  return proved ? 0 : 1;
1580
1884
  }
1581
- console.log(role(proved ? "ok" : "problem", process18.stdout)(message));
1885
+ console.log(role(proved ? "ok" : "problem", process19.stdout)(message));
1582
1886
  if (runs > 1)
1583
1887
  console.log(`now: ${codes.map((code, i) => `run ${i + 1} ${code === 0 ? "passed" : `failed (exit ${code})`}`).join(", ")}`);
1584
1888
  const shown = side === "before" ? before : now;
@@ -1589,9 +1893,9 @@ ${folded(shown.output)}`);
1589
1893
  }
1590
1894
 
1591
1895
  // src/cli.ts
1592
- process19.exitCode = await runCli({
1896
+ process20.exitCode = await runCli({
1593
1897
  name: "base",
1594
- about: "runs a command at HEAD or another ref in a temporary worktree, the working tree untouched",
1898
+ about: "runs a command at HEAD or another ref in a temporary worktree, sharing node_modules and env files with the working tree unless --no-link",
1595
1899
  replaces: "git stash, a test run, then git stash pop",
1596
1900
  examples: [["base -- bun test tests/api.test.ts", "the test at HEAD, the working tree changes left out"], ["base proof -- bun test tests/new.test.ts", "it fails at HEAD and passes in the working tree"]],
1597
1901
  commands: {