@kaynooo/cli-git 0.17.0 → 0.17.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (11) hide show
  1. package/README.md +1 -1
  2. package/dist/gb.js +1674 -1141
  3. package/dist/gc.js +1089 -159
  4. package/dist/gcl.js +1124 -174
  5. package/dist/gd.js +1100 -170
  6. package/dist/gf.js +1131 -175
  7. package/dist/gm.js +1686 -1155
  8. package/dist/gp.js +1110 -174
  9. package/dist/gst.js +1108 -178
  10. package/dist/gu.js +1097 -167
  11. package/package.json +2 -2
package/dist/gb.js CHANGED
@@ -1,20 +1,19 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
3
+ var __esm = (fn, res, err) => () => {
4
+ if (fn)
5
+ try {
6
+ res = fn(fn = 0);
7
+ } catch (e) {
8
+ err = [e];
9
+ }
10
+ if (err)
11
+ throw err[0];
12
+ return res;
13
+ };
3
14
 
4
- // src/gb.ts
5
- import process23 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";
12
-
13
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
14
- var N = new Map;
15
- var Nt = /\s+\S*$/;
16
- var Y = /\s/;
17
- function ko(t, e, r = "...") {
15
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
16
+ function Ao(t, e, r = "...") {
18
17
  let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
19
18
  if (t.length <= e)
20
19
  return t;
@@ -25,13 +24,22 @@ function ko(t, e, r = "...") {
25
24
  c = c.trimEnd();
26
25
  return s ? (c + n).slice(0, l) : c + n;
27
26
  }
28
- var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
29
- var z = new Map;
27
+ var N, Nt, Y, be, W;
28
+ var init_chunk_rkhsft4a = __esm(() => {
29
+ N = new Map;
30
+ Nt = /\s+\S*$/;
31
+ Y = /\s/;
32
+ be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
33
+ W = new Map;
34
+ });
35
+
36
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
37
+ var init_text = __esm(() => {
38
+ init_chunk_rkhsft4a();
39
+ });
30
40
 
31
41
  // ../kit/src/mode.ts
32
42
  import process2 from "process";
33
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
34
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
35
43
  function isSet(value) {
36
44
  return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
37
45
  }
@@ -48,12 +56,13 @@ function outputMode(stream = process2.stdout, env = process2.env) {
48
56
  function isInteractive(streams = process2) {
49
57
  return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
50
58
  }
59
+ var MODES, AGENT_VARIABLES;
60
+ var init_mode = __esm(() => {
61
+ MODES = new Set(["terminal", "ci", "agent", "pipe"]);
62
+ AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
63
+ });
51
64
 
52
- // ../kit/src/style.ts
53
- import process6 from "process";
54
-
55
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
56
- var G2 = /^[a-f0-9]+$/i;
65
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
57
66
  function b(r) {
58
67
  let e = r.startsWith("#") ? r.slice(1) : r;
59
68
  if (!G2.test(e))
@@ -64,11 +73,6 @@ function b(r) {
64
73
  throw Error(`Invalid hex color length: ${e.length}`);
65
74
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
66
75
  }
67
- var B2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
68
- let [l, n, c] = b(r);
69
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
70
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
71
- var h = new Set(["", "1", "2", "3", "true"]);
72
76
  function C(r, e = globalThis.process?.env ?? {}) {
73
77
  if (e.FORCE_COLOR !== undefined)
74
78
  return h.has(e.FORCE_COLOR);
@@ -82,7 +86,7 @@ function f(r, e = []) {
82
86
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
83
87
  let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
84
88
  return new Proxy(c, { get(t, i) {
85
- let a = B2[i];
89
+ let a = B[i];
86
90
  if (Array.isArray(a)) {
87
91
  let s = g.get(i);
88
92
  if (s === undefined)
@@ -105,13 +109,21 @@ function f(r, e = []) {
105
109
  function Fe(r = {}) {
106
110
  return f(r);
107
111
  }
108
- var o = Fe();
112
+ var G2, B, h, o;
113
+ var init_chunk_x450vn3m = __esm(() => {
114
+ G2 = /^[a-f0-9]+$/i;
115
+ B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
116
+ let [l, n, c] = b(r);
117
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
118
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
119
+ h = new Set(["", "1", "2", "3", "true"]);
120
+ o = Fe();
121
+ });
109
122
 
110
- // ../kit/src/theme.ts
111
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
112
- import { homedir as homedir2 } from "os";
113
- import { join as join3, resolve as resolve2 } from "path";
114
- import process5 from "process";
123
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
124
+ var init_colors = __esm(() => {
125
+ init_chunk_x450vn3m();
126
+ });
115
127
 
116
128
  // ../kit/src/config.ts
117
129
  import { existsSync } from "fs";
@@ -127,6 +139,9 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
127
139
  return;
128
140
  }
129
141
  }
142
+ var init_config = __esm(() => {
143
+ init_args();
144
+ });
130
145
 
131
146
  // ../kit/src/user-config.ts
132
147
  import { existsSync as existsSync2, readFileSync } from "fs";
@@ -158,13 +173,17 @@ function readUserConfig(bin, where = {}, legacy = []) {
158
173
  return {};
159
174
  }
160
175
  }
176
+ var init_user_config = () => {};
161
177
 
162
178
  // ../kit/src/theme.ts
179
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
180
+ import { homedir as homedir2 } from "os";
181
+ import { join as join3, resolve as resolve2 } from "path";
182
+ import process5 from "process";
163
183
  function toLinear(channel) {
164
184
  const value = channel / 255;
165
185
  return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
166
186
  }
167
- var fromLinear = (value) => Math.round(255 * Math.min(1, Math.max(0, value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055)));
168
187
  function toOklab(hex) {
169
188
  const [r, g, b] = [1, 3, 5].map((at) => toLinear(Number.parseInt(hex.slice(at, at + 2), 16)));
170
189
  const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
@@ -179,7 +198,6 @@ function fromOklab([lightness, a, b]) {
179
198
  const channels = [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s];
180
199
  return `#${channels.map((channel) => fromLinear(channel).toString(16).padStart(2, "0")).join("")}`;
181
200
  }
182
- var ENDS = new Map;
183
201
  function gradientAt(theme, ratio) {
184
202
  if (theme.gradient === undefined)
185
203
  return;
@@ -193,33 +211,11 @@ function gradientAt(theme, ratio) {
193
211
  const [from, to] = ends;
194
212
  return fromOklab(from.map((start, index) => start + (to[index] - start) * at));
195
213
  }
196
- var DEFAULT = {
197
- 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" },
198
- 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" },
199
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
200
- bins: {},
201
- gradient: ["#c084fc", "#67e8f9"]
202
- };
203
- 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" };
204
- 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" };
205
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
206
- var PRESETS = {
207
- default: {},
208
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
209
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
210
- ascii: { glyphs: ASCII }
211
- };
212
- 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"]);
213
- var HEX = /^#[0-9a-f]{6}$/i;
214
- var CONTROL = /\p{Cc}/u;
215
- var MAX_FILE_BYTES = 64 * 1024;
216
- var SPACES = /\s+/;
217
214
  function isColorSpec(spec) {
218
215
  if (typeof spec === "number")
219
216
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
220
217
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
221
218
  }
222
- var CUBE = [0, 95, 135, 175, 215, 255];
223
219
  function cubeLevel(channel) {
224
220
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
225
221
  }
@@ -327,7 +323,6 @@ function applyFile(theme, file, where, warn) {
327
323
  function endsWalk(home) {
328
324
  return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
329
325
  }
330
- var warned = new Set;
331
326
  function warnOnce(message) {
332
327
  if (warned.has(message))
333
328
  return;
@@ -364,8 +359,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
364
359
  }
365
360
  return { theme, sources, preset };
366
361
  }
367
- var current;
368
- var currentKey = "";
369
362
  function activeTheme() {
370
363
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
371
364
  if (current === undefined || key !== currentKey) {
@@ -374,9 +367,38 @@ function activeTheme() {
374
367
  }
375
368
  return current;
376
369
  }
370
+ var fromLinear = (value) => Math.round(255 * Math.min(1, Math.max(0, value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055))), ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
371
+ var init_theme = __esm(() => {
372
+ init_config();
373
+ init_user_config();
374
+ ENDS = new Map;
375
+ DEFAULT = {
376
+ 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" },
377
+ 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" },
378
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
379
+ bins: {},
380
+ gradient: ["#c084fc", "#67e8f9"]
381
+ };
382
+ 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" };
383
+ 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" };
384
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
385
+ PRESETS = {
386
+ default: {},
387
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
388
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
389
+ ascii: { glyphs: ASCII }
390
+ };
391
+ 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"]);
392
+ HEX = /^#[0-9a-f]{6}$/i;
393
+ CONTROL = /\p{Cc}/u;
394
+ MAX_FILE_BYTES = 64 * 1024;
395
+ SPACES = /\s+/;
396
+ CUBE = [0, 95, 135, 175, 215, 255];
397
+ warned = new Set;
398
+ });
377
399
 
378
400
  // ../kit/src/style.ts
379
- var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
401
+ import process6 from "process";
380
402
  function takesControlCodes(stream, env = process6.env) {
381
403
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
382
404
  }
@@ -396,17 +418,24 @@ function role(name, stream, env = process6.env) {
396
418
  const colors = paint(stream, env);
397
419
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
398
420
  }
399
- var STATUS_WORDS = {
400
- passed: ["passed", "success", "succeeded", "ok"],
401
- failed: ["failed", "failure", "error", "errored"],
402
- running: ["running", "in_progress", "started", "holding"],
403
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
404
- skipped: ["skipped", "cancelled", "canceled", "manual"]
405
- };
406
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
421
+ var MARK_WORDS, STATUS_WORDS, STATUS_OF;
422
+ var init_style = __esm(() => {
423
+ init_colors();
424
+ init_mode();
425
+ init_theme();
426
+ MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
427
+ STATUS_WORDS = {
428
+ passed: ["passed", "success", "succeeded", "ok"],
429
+ failed: ["failed", "failure", "error", "errored"],
430
+ running: ["running", "in_progress", "started", "holding"],
431
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
432
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
433
+ };
434
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
435
+ });
407
436
 
408
437
  // ../kit/src/format.ts
409
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
438
+ import process7 from "process";
410
439
  function formatSeconds(total) {
411
440
  let rest = Math.max(0, Math.round(total));
412
441
  const amounts = UNITS.map(([unit, size]) => {
@@ -438,10 +467,8 @@ function formatAge(date, now = Date.now()) {
438
467
  return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
439
468
  }
440
469
  function truncate(text, width) {
441
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
470
+ return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
442
471
  }
443
- var LINE_BREAKS = /\s*\n\s*/g;
444
- var ESCAPE = String.fromCharCode(27);
445
472
  function textWidth(text) {
446
473
  return Bun.stringWidth(text);
447
474
  }
@@ -490,14 +517,40 @@ function jsonText(value, replacer, { stream = process7.stdout, env = process7.en
490
517
  function printJson(value) {
491
518
  console.log(jsonText(value));
492
519
  }
520
+ var UNITS, LINE_BREAKS, ESCAPE;
521
+ var init_format = __esm(() => {
522
+ init_text();
523
+ init_mode();
524
+ init_style();
525
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
526
+ LINE_BREAKS = /\s*\n\s*/g;
527
+ ESCAPE = String.fromCharCode(27);
528
+ });
493
529
 
494
530
  // ../kit/src/help.ts
495
531
  import process8 from "process";
496
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
497
- var USAGE_PREFIX = /^usage:\s*/i;
498
- var FULL_STOP = /\.$/;
499
532
  function usageLine(usage, colors = paint(process8.stdout)) {
500
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
533
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
534
+ `);
535
+ const blank = lines.indexOf("");
536
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
537
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
538
+ const colon = synopses[0].indexOf(": ");
539
+ const inline = synopses[0].slice(colon + 2);
540
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
541
+ if (colon !== -1)
542
+ synopses[0] = synopses[0].slice(0, colon);
543
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
544
+ `)}`;
545
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
546
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
547
+ return [head, ...lead, ...rest].join(`
548
+ `);
549
+ }
550
+ function prose(line, colors) {
551
+ if (colors.cyan("x") === "x")
552
+ return line;
553
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
501
554
  }
502
555
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
503
556
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -532,7 +585,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
532
585
  return [];
533
586
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
534
587
  }
535
- var MAX_INLINE_CHOICES = 24;
536
588
  function optionRows(options, colors = paint(process8.stdout)) {
537
589
  const rows = Object.entries(options).map(([name, option]) => {
538
590
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -547,9 +599,17 @@ function optionRows(options, colors = paint(process8.stdout)) {
547
599
  const width = Math.max(0, ...rows.map((row) => row.width));
548
600
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
549
601
  }
602
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
603
+ var init_help = __esm(() => {
604
+ init_mode();
605
+ init_style();
606
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
607
+ USAGE_PREFIX = /^usage:\s*/i;
608
+ FULL_STOP = /\.$/;
609
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
610
+ });
550
611
 
551
612
  // ../kit/src/text.ts
552
- var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
553
613
  function distance(a, b) {
554
614
  const left = [...a];
555
615
  const right = [...b];
@@ -575,8 +635,12 @@ function closest(name, names) {
575
635
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
576
636
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
577
637
  }
638
+ var ANSI;
639
+ var init_text2 = __esm(() => {
640
+ ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
641
+ });
642
+
578
643
  // ../kit/src/input.ts
579
- var WHOLE = /^\d+$/;
580
644
  function wholeNumber(value, name, fallback, min = 1) {
581
645
  if (value === undefined)
582
646
  return fallback;
@@ -585,8 +649,6 @@ function wholeNumber(value, name, fallback, min = 1) {
585
649
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
586
650
  return number;
587
651
  }
588
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
589
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
590
652
  function duration(value, name, fallback, unit = "s") {
591
653
  if (value === undefined)
592
654
  return fallback;
@@ -596,40 +658,27 @@ function duration(value, name, fallback, unit = "s") {
596
658
  badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
597
659
  return ms;
598
660
  }
661
+ var WHOLE, DURATION, UNIT_MS;
662
+ var init_input = __esm(() => {
663
+ init_args();
664
+ WHOLE = /^\d+$/;
665
+ DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
666
+ UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
667
+ });
599
668
 
600
669
  // ../kit/src/args.ts
601
- var DASHES = /^-+/;
670
+ import process9 from "process";
671
+ import { parseArgs } from "util";
602
672
  function jsonOption(holds) {
603
673
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
604
674
  }
605
- class Exit extends Error {
606
- code;
607
- hint;
608
- constructor(message, code, hint) {
609
- super(message);
610
- this.code = code;
611
- this.hint = hint;
612
- }
613
- }
614
675
  function fail(message, code = 2, hint) {
615
676
  throw new Exit(message, code, hint);
616
677
  }
617
-
618
- class UsageError extends Exit {
619
- constructor(message, hint) {
620
- super(message, 2, hint);
621
- }
622
- }
623
678
  function badUsage(message) {
624
679
  throw new UsageError(message);
625
680
  }
626
681
 
627
- class HelpShown extends Exit {
628
- constructor() {
629
- super("help shown", 0);
630
- }
631
- }
632
-
633
682
  class Completing {
634
683
  options;
635
684
  positionals;
@@ -640,11 +689,6 @@ class Completing {
640
689
  this.candidates = candidates;
641
690
  }
642
691
  }
643
- var completion = { active: false };
644
- var OUTPUT_OPTIONS = {
645
- color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
646
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
647
- };
648
692
  function applyOutput(color, plain, env = process9.env) {
649
693
  const when = plain === true ? "never" : color ?? "auto";
650
694
  if (when === "auto")
@@ -798,7 +842,6 @@ function parseError(error) {
798
842
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
799
843
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
800
844
  }
801
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
802
845
  function nearestOption(message, options, allowNegative) {
803
846
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
804
847
  if (typed === undefined)
@@ -814,1121 +857,1604 @@ function nearestOption(message, options, allowNegative) {
814
857
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
815
858
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
816
859
  }
817
- // ../kit/src/argv.ts
818
- import { readFileSync as readFileSync3, realpathSync } from "fs";
819
- import { resolve as resolve3 } from "path";
820
- import process10 from "process";
821
- function commandLine() {
860
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
861
+ var init_args = __esm(() => {
862
+ init_format();
863
+ init_help();
864
+ init_text2();
865
+ init_help();
866
+ init_input();
867
+ DASHES = /^-+/;
868
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
869
+ Exit = class Exit extends Error {
870
+ code;
871
+ hint;
872
+ [EXIT] = true;
873
+ constructor(message, code, hint) {
874
+ super(message);
875
+ this.code = code;
876
+ this.hint = hint;
877
+ }
878
+ static [Symbol.hasInstance](value) {
879
+ if (this !== Exit)
880
+ return Function.prototype[Symbol.hasInstance].call(this, value);
881
+ return typeof value === "object" && value !== null && value[EXIT] === true;
882
+ }
883
+ };
884
+ UsageError = class UsageError extends Exit {
885
+ constructor(message, hint) {
886
+ super(message, 2, hint);
887
+ }
888
+ };
889
+ HelpShown = class HelpShown extends Exit {
890
+ constructor() {
891
+ super("help shown", 0);
892
+ }
893
+ };
894
+ completion = { active: false };
895
+ OUTPUT_OPTIONS = {
896
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
897
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
898
+ };
899
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
900
+ });
901
+
902
+ // ../kit/src/folders.ts
903
+ import { homedir as homedir3 } from "os";
904
+ import { join as join4 } from "path";
905
+ import process13 from "process";
906
+ function cacheFolder({ home = homedir3(), env = process13.env } = {}) {
907
+ return env.XDG_CACHE_HOME ?? join4(home, ".cache");
908
+ }
909
+ var SKIPPED_FOLDERS;
910
+ var init_folders = __esm(() => {
911
+ init_user_config();
912
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
913
+ });
914
+
915
+ // ../kit/src/answers.ts
916
+ import { mkdirSync, readFileSync as readFileSync4, writeFileSync } from "fs";
917
+ import { dirname as dirname2, join as join5 } from "path";
918
+ function answersFile() {
919
+ return join5(cacheFolder(), "kaynooo-cli", "answers.json");
920
+ }
921
+ function stored() {
822
922
  try {
823
- return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
923
+ const parsed = JSON.parse(readFileSync4(answersFile(), "utf-8"));
924
+ if (typeof parsed !== "object" || parsed === null)
925
+ return {};
926
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
824
927
  } catch {
825
- return;
928
+ return {};
826
929
  }
827
930
  }
828
- function realPath(word) {
931
+ function earlierAnswers(key) {
932
+ return stored()[key] ?? [];
933
+ }
934
+ function rememberAnswer(key, answer) {
935
+ const all = stored();
936
+ const file = answersFile();
937
+ all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
829
938
  try {
830
- return realpathSync(resolve3(word));
831
- } catch {
832
- return;
833
- }
939
+ mkdirSync(dirname2(file), { recursive: true });
940
+ writeFileSync(file, JSON.stringify(all));
941
+ } catch {}
834
942
  }
835
- function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
836
- const target = script === undefined ? undefined : realPath(script) ?? script;
837
- const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
838
- const after = at === -1 ? [] : cmdline.slice(at + 1);
839
- return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
943
+ var KEPT = 50;
944
+ var init_answers = __esm(() => {
945
+ init_folders();
946
+ });
947
+
948
+ // ../kit/src/job.ts
949
+ import process14 from "process";
950
+ function stopJob() {
951
+ process14.kill(0, "SIGTSTP");
840
952
  }
841
- // ../kit/src/progress.ts
842
- import process12 from "process";
953
+ var init_job = () => {};
843
954
 
844
- // ../kit/src/process.ts
845
- import { constants } from "os";
846
- import process11 from "process";
847
- var KILL_GRACE_MS = 2000;
848
- var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
849
- function exitCodeOf(code, signal) {
850
- if (code !== null)
851
- return code;
852
- if (typeof signal === "number")
853
- return 128 + signal;
854
- return signal === null ? 129 : 128 + constants.signals[signal];
955
+ // ../kit/src/picker/line.ts
956
+ function isEditKey(key) {
957
+ return EDIT_KEYS.has(key);
855
958
  }
856
- function holdSignals(cleanup) {
857
- let received;
858
- let child;
859
- const held = {
860
- get signal() {
861
- return received;
862
- },
863
- forward: (to) => {
864
- child = to;
865
- },
866
- release: () => {
867
- for (const signal of SIGNALS)
868
- process11.off(signal, onSignal);
869
- }
870
- };
871
- function onSignal(signal) {
872
- received = signal;
873
- if (child !== undefined) {
874
- child.kill(signal);
875
- return;
876
- }
877
- if (cleanup === undefined)
878
- return;
879
- held.release();
880
- cleanup(signal);
881
- process11.kill(process11.pid, signal);
882
- }
883
- for (const signal of SIGNALS)
884
- process11.on(signal, onSignal);
885
- return held;
959
+ function endsKills(key) {
960
+ return typeof key !== "object" && !isEditKey(key);
886
961
  }
887
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
888
- const chunks = [];
889
- const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
890
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
891
- const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
892
- const timers = [];
893
- const killGroup = (killing) => {
894
- if (state.done)
895
- return;
896
- try {
897
- if (grouped)
898
- process11.kill(-proc.pid, killing);
899
- else
900
- proc.kill(killing);
901
- } catch {}
902
- };
903
- const stop = () => {
904
- killGroup("SIGTERM");
905
- timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
906
- };
907
- const onAbort = () => stop();
908
- if (timeoutMs !== undefined) {
909
- timers.push(setTimeout(() => {
910
- state.timedOut = true;
911
- stop();
912
- }, timeoutMs));
913
- }
914
- if (signal?.aborted === true)
915
- onAbort();
916
- else
917
- signal?.addEventListener("abort", onAbort, { once: true });
918
- onStart?.({ kill: (killing) => killGroup(killing) });
919
- const drain = async (stream, name) => {
920
- for await (const data of stream) {
921
- if (state.failure !== undefined)
922
- continue;
923
- try {
924
- onChunk?.({ stream: name, data });
925
- } catch (error) {
926
- state.failure = error;
927
- stop();
928
- continue;
929
- }
930
- if (state.kept + data.length > maxBytes) {
931
- state.truncated = true;
932
- continue;
933
- }
934
- state.kept += data.length;
935
- chunks.push({ stream: name, data });
936
- }
937
- };
938
- try {
939
- await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
940
- await proc.exited;
941
- } finally {
942
- state.done = true;
943
- for (const timer of timers)
944
- clearTimeout(timer);
945
- signal?.removeEventListener("abort", onAbort);
946
- }
947
- if (state.failure !== undefined)
948
- throw state.failure;
949
- const joined = () => Buffer.concat(chunks.map(({ data }) => data));
950
- let output;
951
- let text;
952
- return {
953
- code: exitCodeOf(proc.exitCode, proc.signalCode),
954
- chunks,
955
- timedOut: state.timedOut,
956
- truncated: state.truncated,
957
- get output() {
958
- return output ??= joined();
959
- },
960
- get text() {
961
- return text ??= (output ??= joined()).toString();
962
- }
963
- };
962
+ function isWord(char) {
963
+ return char !== undefined && WORD_CHARACTER.test(char);
964
964
  }
965
-
966
- // ../kit/src/progress.ts
967
- var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
968
- var FRAME_MS = 200;
969
- var BAR_WIDTH = 20;
970
- var CLEAR_BELOW = "\r\x1B[J";
971
- var ESC = String.fromCharCode(27);
972
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
973
- var RESET_STYLE = `${ESC}[0m`;
974
- var CTRL_C = 3;
975
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
976
- var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
977
- function liveRegion(render, stream = process12.stderr, env = process12.env) {
978
- if (!takesControlCodes(stream, env))
979
- return { redraw: () => {
980
- return;
981
- }, print: (text) => void stream.write(`${text}
982
- `), stop: () => {
983
- return;
984
- } };
985
- const write = stream.write.bind(stream);
986
- let frame = 0;
987
- let drawn = false;
988
- const columns = () => {
989
- const now = stream.getWindowSize?.()[0] ?? stream.columns;
990
- return now === undefined || now === 0 ? 80 : now;
991
- };
992
- const clear = () => {
993
- if (drawn)
994
- write(CLEAR_BELOW);
995
- drawn = false;
996
- };
997
- const draw = () => {
998
- const width = columns() - 1;
999
- const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
1000
- const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
1001
- if (lines.length === 0) {
1002
- clear();
1003
- return;
1004
- }
1005
- write(`${CLEAR_BELOW}${lines.join(`
1006
- `)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
1007
- drawn = true;
1008
- };
1009
- const timer = setInterval(draw, FRAME_MS);
1010
- stream.on?.("resize", draw);
1011
- const restore = interceptOutput(clear);
1012
- const release = swallowInput();
1013
- const onExit = () => {
1014
- clear();
1015
- release();
1016
- };
1017
- const signals = holdSignals(stop);
1018
- function stop() {
1019
- clearInterval(timer);
1020
- stream.off?.("resize", draw);
1021
- clear();
1022
- restore();
1023
- release();
1024
- process12.off("exit", onExit);
1025
- signals.release();
1026
- }
1027
- timer.unref();
1028
- process12.on("exit", onExit);
1029
- return {
1030
- redraw: draw,
1031
- print: (text) => {
1032
- clear();
1033
- write(`${text}
1034
- `);
1035
- draw();
1036
- },
1037
- stop
1038
- };
965
+ function wordStart(chars, from) {
966
+ let at = from;
967
+ while (at > 0 && !isWord(chars[at - 1]))
968
+ at--;
969
+ while (at > 0 && isWord(chars[at - 1]))
970
+ at--;
971
+ return at;
1039
972
  }
1040
- function progressLine(stream = process12.stderr, env = process12.env) {
1041
- const colors = paint(stream, env);
1042
- const write = stream.write.bind(stream);
1043
- const begun = performance.now();
1044
- let started = begun;
1045
- let current;
1046
- const region = liveRegion((spinner) => current === undefined ? [] : [tintedParts(progressParts(current, spinner, performance.now() - started), colors)], stream, env);
1047
- const end = (line) => {
1048
- region.stop();
1049
- write(`${line}
1050
- `);
1051
- };
1052
- return {
1053
- update: (progress) => {
1054
- const step = current?.step;
1055
- current = progress;
1056
- if (progress.step !== step) {
1057
- started = performance.now();
1058
- region.redraw();
1059
- }
1060
- },
1061
- stop: region.stop,
1062
- done: (text) => end(marked("ok", text, stream, formatDuration(performance.now() - begun), env)),
1063
- failed: (text) => end(marked("problem", text, stream, undefined, env))
1064
- };
973
+ function wordEnd(chars, from) {
974
+ let at = from;
975
+ while (at < chars.length && !isWord(chars[at]))
976
+ at++;
977
+ while (at < chars.length && isWord(chars[at]))
978
+ at++;
979
+ return at;
1065
980
  }
1066
- function progressParts({ step, done, total, unit }, spinner, ms) {
1067
- const { theme } = activeTheme();
1068
- const parts = [{ text: spinner, tint: (colors) => tinted(colors, theme.colors.accent) }, { text: ` ${step}`, tint: () => plain }];
1069
- if (total !== undefined && total > 0) {
1070
- const counted = Math.min(done ?? 0, total);
1071
- const filled = Math.round(counted / total * BAR_WIDTH);
1072
- parts.push({ text: " ", tint: () => plain }, { text: theme.glyphs.bar.repeat(filled), tint: (colors) => () => shaded(theme, colors, theme.glyphs.bar, filled, BAR_WIDTH) }, { text: theme.glyphs.bar.repeat(BAR_WIDTH - filled), tint: (colors) => colors.dim }, { text: ` ${counted}/${total}${unit === undefined ? "" : ` ${unit}`}`, tint: (colors) => colors.dim });
1073
- }
1074
- parts.push({ text: ` ${formatElapsed(ms)}`, tint: (colors) => colors.dim });
1075
- return parts;
981
+ function spacedStart(chars, from) {
982
+ let at = from;
983
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
984
+ at--;
985
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
986
+ at--;
987
+ return at;
1076
988
  }
1077
- function plain(text) {
1078
- return text;
989
+ function cut(chars, from, to) {
990
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
1079
991
  }
1080
- function tintedParts(parts, colors) {
1081
- return parts.map(({ text, tint }) => tint(colors)(text)).join("");
992
+ function insert(chars, at, text) {
993
+ const typed = [...text];
994
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
1082
995
  }
1083
- function cutToWidth(line, width) {
1084
- if (Bun.stringWidth(line) <= width)
1085
- return line;
1086
- let room = width;
1087
- let kept = "";
1088
- let index = 0;
1089
- let linked = false;
1090
- while (index < line.length) {
1091
- ESCAPE_CODE.lastIndex = index;
1092
- const escape = ESCAPE_CODE.exec(line);
1093
- if (escape !== null) {
1094
- kept += escape[0];
1095
- linked ||= escape[0].startsWith(`${ESC}]`);
1096
- index = ESCAPE_CODE.lastIndex;
1097
- continue;
1098
- }
1099
- const char = String.fromCodePoint(line.codePointAt(index));
1100
- const columns = Bun.stringWidth(char);
1101
- if (columns > room)
1102
- break;
1103
- kept += char;
1104
- room -= columns;
1105
- index += char.length;
996
+ function editLine(line, key) {
997
+ const { killed = "", chained = false } = line;
998
+ const chars = [...line.text];
999
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
1000
+ const edited = edit(chars, at, key, killed);
1001
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
1002
+ return line.killed === undefined ? edited : { ...edited, killed };
1003
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
1004
+ if (taken === "")
1005
+ return { ...edited, killed, chained };
1006
+ if (!chained)
1007
+ return { ...edited, killed: taken, chained: true };
1008
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
1009
+ }
1010
+ function edit(chars, at, key, killed) {
1011
+ const text = chars.join("");
1012
+ if (typeof key === "object")
1013
+ return insert(chars, at, key.text);
1014
+ switch (key) {
1015
+ case "left":
1016
+ return { text, caret: Math.max(at - 1, 0) };
1017
+ case "right":
1018
+ return { text, caret: Math.min(at + 1, chars.length) };
1019
+ case "wordleft":
1020
+ return { text, caret: wordStart(chars, at) };
1021
+ case "wordright":
1022
+ return { text, caret: wordEnd(chars, at) };
1023
+ case "linestart":
1024
+ return { text, caret: 0 };
1025
+ case "lineend":
1026
+ return { text, caret: chars.length };
1027
+ case "erase":
1028
+ return cut(chars, Math.max(at - 1, 0), at);
1029
+ case "delete":
1030
+ return cut(chars, at, Math.min(at + 1, chars.length));
1031
+ case "word":
1032
+ return cut(chars, spacedStart(chars, at), at);
1033
+ case "killword":
1034
+ return cut(chars, wordStart(chars, at), at);
1035
+ case "killnext":
1036
+ return cut(chars, at, wordEnd(chars, at));
1037
+ case "clear":
1038
+ return cut(chars, 0, at);
1039
+ case "killend":
1040
+ return cut(chars, at, chars.length);
1041
+ case "yank":
1042
+ return insert(chars, at, killed);
1106
1043
  }
1107
- return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
1108
1044
  }
1109
- function swallowInput() {
1110
- const input = process12.stdin;
1111
- if (!input.isTTY)
1112
- return () => {
1113
- return;
1114
- };
1115
- const onData = (data) => {
1116
- if (data.includes(CTRL_C))
1117
- process12.kill(process12.pid, "SIGINT");
1118
- };
1119
- input.setRawMode(true);
1120
- input.on("data", onData);
1121
- input.resume();
1122
- let released = false;
1123
- return () => {
1124
- if (released)
1125
- return;
1126
- released = true;
1127
- input.off("data", onData);
1128
- input.pause();
1129
- input.setRawMode(false);
1130
- };
1045
+ function visible({ text, caret }, room) {
1046
+ const chars = [...text];
1047
+ const at = Math.min(Math.max(caret, 0), chars.length);
1048
+ const cells = at === chars.length ? [...chars, " "] : chars;
1049
+ const widths = cells.map((char) => Bun.stringWidth(char));
1050
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
1051
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
1052
+ let start = at;
1053
+ let end = at + 1;
1054
+ while (start > 0 && fits(start - 1, end))
1055
+ start--;
1056
+ while (end < cells.length && fits(start, end + 1))
1057
+ end++;
1058
+ const left = start > 0 ? "\u2026" : "";
1059
+ const right = end < cells.length ? "\u2026" : "";
1060
+ return { before: left + chars.slice(start, at).join(""), at: chars[at], after: chars.slice(at + 1, end).join("") + right, column: left.length + width(start, at) };
1131
1061
  }
1132
- function interceptOutput(clear) {
1133
- const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
1134
- const wrapped = targets.map(([target, name]) => {
1135
- const original = Reflect.get(target, name);
1136
- const wrapper = (...args) => {
1137
- clear();
1138
- return original.apply(target, args);
1139
- };
1140
- Reflect.set(target, name, wrapper);
1141
- return { target, name, original, wrapper };
1142
- });
1143
- return () => {
1144
- for (const { target, name, original, wrapper } of wrapped) {
1145
- if (Reflect.get(target, name) === wrapper)
1146
- Reflect.set(target, name, original);
1062
+ var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS, WORD_CHARACTER, SPACE;
1063
+ var init_line = __esm(() => {
1064
+ EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
1065
+ BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
1066
+ FORWARD_KILLS = new Set(["killnext", "killend"]);
1067
+ WORD_CHARACTER = /[\p{L}\p{N}_]/u;
1068
+ SPACE = /\s/;
1069
+ });
1070
+
1071
+ // ../kit/src/picker/score.ts
1072
+ function startsWord(text, index) {
1073
+ if (index === 0)
1074
+ return true;
1075
+ const before = text[index - 1];
1076
+ return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
1077
+ }
1078
+ function fuzzy(query, text) {
1079
+ if (query === "")
1080
+ return { score: 0, positions: [] };
1081
+ const exact = query !== query.toLowerCase();
1082
+ const needle = exact ? query : query.toLowerCase();
1083
+ const haystack = exact ? text : text.toLowerCase();
1084
+ if (haystack.length !== text.length || needle.length > haystack.length)
1085
+ return;
1086
+ const width = haystack.length;
1087
+ const best = Array.from({ length: needle.length }, () => new Array(width).fill(NONE));
1088
+ const from = Array.from({ length: needle.length }, () => new Array(width).fill(-1));
1089
+ for (let j = 0;j < needle.length; j++) {
1090
+ let run = NONE;
1091
+ let runAt = -1;
1092
+ for (let i = j;i < width; i++) {
1093
+ if (j > 0 && i - 2 >= j - 1) {
1094
+ const candidate = best[j - 1][i - 2] + (i - 2) * GAP;
1095
+ if (candidate > run) {
1096
+ run = candidate;
1097
+ runAt = i - 2;
1098
+ }
1099
+ }
1100
+ if (haystack[i] !== needle[j])
1101
+ continue;
1102
+ const here = MATCH + (startsWord(text, i) ? BOUNDARY : 0) + (i === 0 ? PREFIX : 0);
1103
+ if (j === 0) {
1104
+ best[0][i] = here - i * GAP;
1105
+ continue;
1106
+ }
1107
+ const joined = best[j - 1][i - 1] + CONSECUTIVE;
1108
+ const skipped = run - (i - 1) * GAP;
1109
+ if (joined > NONE && joined >= skipped) {
1110
+ best[j][i] = joined + here;
1111
+ from[j][i] = i - 1;
1112
+ } else if (skipped > NONE) {
1113
+ best[j][i] = skipped + here;
1114
+ from[j][i] = runAt;
1115
+ }
1147
1116
  }
1148
- };
1117
+ }
1118
+ const last = best[needle.length - 1];
1119
+ let end = -1;
1120
+ for (let i = 0;i < width; i++) {
1121
+ if (last[i] > NONE && (end === -1 || last[i] > last[end]))
1122
+ end = i;
1123
+ }
1124
+ if (end === -1)
1125
+ return;
1126
+ const positions = [];
1127
+ for (let j = needle.length - 1, i = end;j >= 0; j--) {
1128
+ positions.unshift(i);
1129
+ i = from[j][i];
1130
+ }
1131
+ return { score: last[end], positions };
1149
1132
  }
1150
- // ../kit/src/cli.ts
1151
- import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
1152
- import { dirname as dirname3, join as join5 } from "path";
1153
- import process15 from "process";
1154
-
1155
- // ../kit/src/completions.ts
1156
- var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1157
- 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'
1158
- set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1159
- set -l current (commandline -ct)
1160
- for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1161
- if test "$line" = __files__
1162
- __fish_complete_path $current
1163
- else
1164
- echo $line
1165
- end
1166
- end
1167
- end`;
1168
- var BASH_FUNCTION = `__kaynooo_cli_complete() {
1169
- local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1170
- local -a lines
1171
- COMPREPLY=()
1172
- lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1173
- for line in "\${lines[@]}"; do
1174
- if [[ $line == __files__ ]]; then
1175
- COMPREPLY+=($(compgen -f -- "$cur"))
1176
- else
1177
- words+="\${line%%$'\\t'*}"$'\\n'
1178
- fi
1179
- done
1180
- COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1181
- }`;
1182
- var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1183
- local line
1184
- local -a described plain
1185
- for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1186
- if [[ $line == __files__ ]]; then
1187
- _files
1188
- elif [[ $line == *$'\\t'* ]]; then
1189
- described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1190
- else
1191
- plain+=("$line")
1192
- fi
1193
- done
1194
- (( \${#described} )) && _describe -V value described
1195
- (( \${#plain} )) && compadd -- "\${plain[@]}"
1196
- return 0
1197
- }`;
1198
- function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1199
- if (shell === "fish")
1200
- return `${header}
1201
- ${FISH_FUNCTION}
1202
- ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1203
- `).join("")}`;
1204
- if (shell === "bash")
1205
- return `${header}
1206
- ${BASH_FUNCTION}
1207
- complete -F __kaynooo_cli_complete ${bins.join(" ")}
1208
- `;
1209
- return `${header}
1210
- ${ZSH_FUNCTION}
1211
- compdef __kaynooo_cli_complete ${bins.join(" ")}
1212
- `;
1133
+ function rank(query, lines) {
1134
+ if (query === "")
1135
+ return lines.map((_, index) => ({ index, positions: [] }));
1136
+ const found = [];
1137
+ for (const [index, line] of lines.entries()) {
1138
+ const match = fuzzy(query, line);
1139
+ if (match !== undefined)
1140
+ found.push({ index, positions: match.positions, score: match.score });
1141
+ }
1142
+ return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
1213
1143
  }
1144
+ var MATCH = 16, CONSECUTIVE = 12, BOUNDARY = 10, PREFIX = 8, GAP = 1, BOUNDARY_AFTER, UPPER, LOWER, NONE;
1145
+ var init_score = __esm(() => {
1146
+ BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1147
+ UPPER = /\p{Lu}/u;
1148
+ LOWER = /\p{Ll}/u;
1149
+ NONE = Number.NEGATIVE_INFINITY;
1150
+ });
1214
1151
 
1215
- // ../kit/src/notify.ts
1216
- import process13 from "process";
1217
- var NOTIFY_AFTER_MS = 1e4;
1218
- var CANCELLED = 130;
1219
- function base64(text) {
1220
- return Buffer.from(text).toString("base64");
1152
+ // ../kit/src/picker/state.ts
1153
+ function repeat(value, count) {
1154
+ return Array.from({ length: count }).fill(value);
1221
1155
  }
1222
- function notification(title, body, env = process13.env) {
1223
- const id = `kit${process13.pid}`;
1224
- 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\\`];
1225
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1156
+ function styled(line) {
1157
+ let text = "";
1158
+ const styles = [];
1159
+ let active = "";
1160
+ let colored = false;
1161
+ let last = 0;
1162
+ function add(chunk) {
1163
+ const flat = chunk.replace(CONTROL2, " ");
1164
+ text += flat;
1165
+ colored ||= active !== "" && flat !== "";
1166
+ styles.push(...repeat(active, flat.length));
1167
+ }
1168
+ for (const found of line.matchAll(ANSI)) {
1169
+ add(line.slice(last, found.index));
1170
+ last = found.index + found[0].length;
1171
+ if (SGR.test(found[0]))
1172
+ active = RESET.test(found[0]) ? "" : active + found[0];
1173
+ }
1174
+ add(line.slice(last));
1175
+ return { text, styles: colored ? styles : undefined };
1226
1176
  }
1227
- function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1228
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1229
- return;
1230
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1177
+ function lay(rows, searched) {
1178
+ const parsed = rows.map((row) => row.cells.map(styled));
1179
+ const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
1180
+ return parsed.map((cells, at) => {
1181
+ let text = "";
1182
+ const styles = [];
1183
+ let colored = false;
1184
+ let searchEnd = 0;
1185
+ for (const [column, cell] of cells.entries()) {
1186
+ const last = column === cells.length - 1;
1187
+ const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
1188
+ text += shown;
1189
+ colored ||= cell.styles !== undefined;
1190
+ styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
1191
+ if (column < searched)
1192
+ searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
1193
+ if (!last) {
1194
+ const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
1195
+ text += " ".repeat(pad);
1196
+ styles.push(...repeat("", pad));
1197
+ }
1198
+ }
1199
+ return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
1200
+ });
1201
+ }
1202
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
1203
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1204
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1205
+ const wheel = MOUSE.exec(sequence)?.[1];
1206
+ if (wheel !== undefined)
1207
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1208
+ const named = codes.get(sequence);
1209
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1210
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1211
+ paste.active = sequence === PASTE_START;
1212
+ return [];
1213
+ }
1214
+ if (paste.active && (sequence === "\r" || sequence === `
1215
+ `))
1216
+ return [];
1217
+ if (key !== undefined)
1218
+ return [key];
1219
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1220
+ });
1231
1221
  }
1232
-
1233
- // ../kit/src/usage.ts
1234
- import { appendFileSync, mkdirSync } from "fs";
1235
- import { homedir as homedir3 } from "os";
1236
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1237
- import process14 from "process";
1238
-
1239
- // ../kit/src/logs.ts
1240
- var DAY_MS = 24 * 60 * 60 * 1000;
1241
- var CLI_FOLDER = "kaynooo-cli";
1242
-
1243
- // ../kit/src/usage.ts
1244
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1245
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1246
- var LONGEST_NAME = 40;
1247
- var usageError;
1248
- function noteUsageError(message) {
1249
- usageError = message;
1222
+ function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1223
+ const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, caret: [...query].length, killed: "", chained: false, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1224
+ return withRows(state, rows);
1250
1225
  }
1251
- function stateHome(env = process14.env) {
1252
- const dir = env.XDG_STATE_HOME;
1253
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1226
+ function withRows(state, rows, header = state.header) {
1227
+ const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1228
+ const laid = lay(cells, state.searched);
1229
+ const searchable = laid.map((row) => row.searchable);
1230
+ const matches = rank(state.query, searchable);
1231
+ 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 };
1254
1232
  }
1255
- function usagePath(env = process14.env) {
1256
- return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1233
+ function withQuery(state, key) {
1234
+ const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1235
+ return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1257
1236
  }
1258
- function usageRecorded(env = process14.env) {
1259
- const off = env.KAYNOOO_CLI_NO_USAGE;
1260
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1237
+ function move(state, by) {
1238
+ return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
1261
1239
  }
1262
- function flagNames(argv) {
1263
- const end = argv.indexOf("--");
1264
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1265
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1240
+ function highlighted(state) {
1241
+ return state.matches[state.cursor]?.index;
1266
1242
  }
1267
- function usageEntry(bin, command, argv, code, now = new Date) {
1268
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1269
- usageError = undefined;
1270
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1243
+ function press(state, key) {
1244
+ if (state.done !== undefined)
1245
+ return state;
1246
+ if (state.chained && endsKills(key))
1247
+ state = { ...state, chained: false };
1248
+ if (state.help)
1249
+ return { ...state, help: false };
1250
+ if (typeof key === "object") {
1251
+ if ("text" in key)
1252
+ return withQuery(state, key);
1253
+ return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1254
+ }
1255
+ if (isEditKey(key))
1256
+ return withQuery(state, key);
1257
+ switch (key) {
1258
+ case "up":
1259
+ return move(state, -1);
1260
+ case "down":
1261
+ return move(state, 1);
1262
+ case "pageup":
1263
+ return move(state, -state.page);
1264
+ case "pagedown":
1265
+ return move(state, state.page);
1266
+ case "home":
1267
+ return move(state, -state.matches.length);
1268
+ case "end":
1269
+ return move(state, state.matches.length);
1270
+ case "cancel":
1271
+ return { ...state, done: "cancel" };
1272
+ case "help":
1273
+ return { ...state, help: true };
1274
+ case "suspend":
1275
+ return state;
1276
+ case "enter":
1277
+ return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1278
+ case "tab": {
1279
+ const at = highlighted(state);
1280
+ if (!state.multi || at === undefined)
1281
+ return state;
1282
+ const marked = new Set(state.marked);
1283
+ if (!marked.delete(at))
1284
+ marked.add(at);
1285
+ return move({ ...state, marked }, 1);
1286
+ }
1287
+ }
1271
1288
  }
1272
- function recordUsage(entry, env = process14.env) {
1273
- if (!usageRecorded(env))
1274
- return;
1275
- try {
1276
- const path = usagePath(env);
1277
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1278
- appendFileSync(path, `${JSON.stringify(entry)}
1279
- `, { mode: 384 });
1280
- } catch {}
1289
+ function chosen(state) {
1290
+ if (state.marked.size > 0)
1291
+ return state.rows.filter((_, index) => state.marked.has(index));
1292
+ const at = highlighted(state);
1293
+ return at === undefined ? [] : [state.rows[at]];
1281
1294
  }
1295
+ var CONTROL2, IS_CONTROL, SGR, RESET, COLUMN_GAP = 2, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS, CTRL_KEY;
1296
+ var init_state = __esm(() => {
1297
+ init_text2();
1298
+ init_line();
1299
+ init_score();
1300
+ CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1301
+ IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1302
+ SGR = /^\x1B\[[0-9;]*m$/;
1303
+ RESET = /^\x1B\[0?m$/;
1304
+ KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1305
+ MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1306
+ KEYS = {
1307
+ "\x1B[A": "up",
1308
+ "\x1BOA": "up",
1309
+ "\x10": "up",
1310
+ "\x1B[B": "down",
1311
+ "\x1BOB": "down",
1312
+ "\x0E": "down",
1313
+ "\x1B[5~": "pageup",
1314
+ "\x1B[6~": "pagedown",
1315
+ "\x1B[H": "home",
1316
+ "\x1B[1~": "home",
1317
+ "\x1BOH": "home",
1318
+ "\x1B[F": "end",
1319
+ "\x1B[4~": "end",
1320
+ "\x1BOF": "end",
1321
+ "\r": "enter",
1322
+ "\n": "enter",
1323
+ "\x03": "cancel",
1324
+ "\x1B": "cancel",
1325
+ "\x1B[D": "left",
1326
+ "\x1BOD": "left",
1327
+ "\x1B[C": "right",
1328
+ "\x1BOC": "right",
1329
+ "\x1B[1;5D": "wordleft",
1330
+ "\x1B[1;3D": "wordleft",
1331
+ "\x1Bb": "wordleft",
1332
+ "\x1B[1;5C": "wordright",
1333
+ "\x1B[1;3C": "wordright",
1334
+ "\x1Bf": "wordright",
1335
+ "\x01": "linestart",
1336
+ "\x05": "lineend",
1337
+ "\x7F": "erase",
1338
+ "\x1B[3~": "delete",
1339
+ "\b": "killword",
1340
+ "\x1B\x7F": "killword",
1341
+ "\x1B[3;5~": "killnext",
1342
+ "\x1Bd": "killnext",
1343
+ "\x15": "clear",
1344
+ "\v": "killend",
1345
+ "\x17": "word",
1346
+ "\x19": "yank",
1347
+ "\x1A": "suspend",
1348
+ "\t": "tab",
1349
+ "\x1F": "help",
1350
+ "\x1BOP": "help",
1351
+ "\x1B[11~": "help"
1352
+ };
1353
+ CTRL_KEY = /^ctrl-[abd-gkln-z]$/;
1354
+ });
1282
1355
 
1283
- // ../kit/src/cli.ts
1284
- var LEVEL_OPTIONS = {
1285
- ...OUTPUT_OPTIONS,
1286
- help: { type: "boolean", short: "h", description: "show this help" }
1287
- };
1288
- var TOP_OPTIONS = {
1289
- ...LEVEL_OPTIONS,
1290
- version: { type: "boolean", short: "v", description: "print the version" },
1291
- completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1292
- };
1293
- function printError(prefix, message, hint, cause) {
1294
- const colors = paint(process15.stderr);
1295
- const styled = takesControlCodes(process15.stderr);
1296
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1297
- const under = (label, text, tint) => text === undefined ? "" : `
1298
- ${styled ? tint(label) : `${label}:`} ${text}`;
1299
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1300
- }
1301
- function runHint(command, effect) {
1302
- return `run \`${command}\`${effect === undefined ? "" : ` to ${effect}`}`;
1303
- }
1304
- function printJsonError(message, hint, cause) {
1305
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1306
- }
1307
- function wantsJson(argv) {
1308
- const end = argv.indexOf("--");
1309
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1356
+ // ../kit/src/redraw.ts
1357
+ function overwrite(lines, columns) {
1358
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1359
+ `);
1310
1360
  }
1311
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
1312
- if (error instanceof HelpShown)
1313
- return 0;
1314
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1315
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1316
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1317
- if (error instanceof Exit && error.code === 2)
1318
- noteUsageError(error.message);
1319
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1320
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1321
- return error instanceof Exit ? error.code : 1;
1361
+ function rowsTaken(lines, columns) {
1362
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1322
1363
  }
1323
- var COMPLETE = "__complete";
1324
- var FILES = "__files__";
1325
- async function completingOf(run) {
1326
- completion.active = true;
1364
+ var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
1365
+ var init_redraw = __esm(() => {
1366
+ init_format();
1367
+ });
1368
+
1369
+ // ../kit/src/prompt.ts
1370
+ import process15 from "process";
1371
+ function readKeys(input, paste = { active: false }) {
1372
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
1373
+ }
1374
+ function roomAfter(question, columns) {
1375
+ return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
1376
+ }
1377
+ function withCaret(colors, line, room, dim = false) {
1378
+ const { before, at, after } = visible(line, room);
1379
+ const tone = dim ? colors.dim : (text) => text;
1380
+ return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
1381
+ }
1382
+ function sharedStart(texts) {
1383
+ const [first = [], ...rest] = texts.map((text) => [...text]);
1384
+ let length = first.length;
1385
+ for (const chars of rest) {
1386
+ const differs = chars.findIndex((char, index) => char !== first[index]);
1387
+ length = Math.min(length, differs === -1 ? chars.length : differs);
1388
+ }
1389
+ return first.slice(0, length).join("");
1390
+ }
1391
+ function listed2(colors, found, columns) {
1392
+ const shared = sharedStart(found);
1393
+ const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
1394
+ const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
1395
+ const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
1396
+ return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
1397
+ }
1398
+ async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
1399
+ let line = { text: "", caret: 0 };
1400
+ let invalid;
1401
+ let completions = [];
1402
+ const remembered = history === undefined || mask ? undefined : history;
1403
+ const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
1404
+ let recalled = -1;
1405
+ let draft = line;
1406
+ const taken = () => line.text === "" ? fallback ?? "" : line.text;
1407
+ const shown = () => mask ? "*".repeat([...taken()].length) : taken();
1408
+ const accepted = await ask(question, settings, (colors, state, { columns }) => {
1409
+ if (state !== "asking")
1410
+ return [answer(colors, question, state, shown())];
1411
+ const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
1412
+ return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
1413
+ }, (key) => {
1414
+ if (key === "cancel")
1415
+ return "cancel";
1416
+ invalid = undefined;
1417
+ completions = [];
1418
+ if (line.chained === true && endsKills(key))
1419
+ line = { ...line, chained: false };
1420
+ if (key === "tab") {
1421
+ const chars = [...line.text];
1422
+ const before = chars.slice(0, line.caret).join("");
1423
+ const found = complete?.(before) ?? [];
1424
+ const filled = sharedStart(found);
1425
+ if ([...filled].length > [...before].length)
1426
+ line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
1427
+ else
1428
+ completions = found;
1429
+ return;
1430
+ }
1431
+ if (key === "enter") {
1432
+ invalid = validate?.(taken());
1433
+ return invalid === undefined ? "enter" : undefined;
1434
+ }
1435
+ if (key === "up" || key === "down") {
1436
+ const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
1437
+ if (recalled === -1)
1438
+ draft = line;
1439
+ recalled = to;
1440
+ const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
1441
+ line = { ...shown, killed: line.killed ?? "" };
1442
+ return;
1443
+ }
1444
+ const edit = { home: "linestart", end: "lineend" }[key] ?? key;
1445
+ if (typeof edit === "object" || isEditKey(edit))
1446
+ line = editLine(line, edit);
1447
+ return;
1448
+ });
1449
+ if (!accepted)
1450
+ return;
1451
+ if (remembered !== undefined && taken() !== "")
1452
+ rememberAnswer(remembered, taken());
1453
+ return taken();
1454
+ }
1455
+ function answer(colors, question, state, picked) {
1456
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1457
+ }
1458
+ async function ask(question, { hint, terminal = process15 }, render, press) {
1459
+ const { stdin, stderr } = terminal;
1460
+ if (!isInteractive(terminal))
1461
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
1462
+ const colors = paint(stderr);
1463
+ let current = "asking";
1464
+ let outcome;
1465
+ const columns = () => stderr.columns || 80;
1466
+ const draw = (state, last = false) => {
1467
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1468
+ const rows = rowsTaken(frame, columns());
1469
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
1470
+ current = state;
1471
+ };
1472
+ const redraw = () => draw(current);
1473
+ const paste = { active: false };
1474
+ const stop = terminal.stop ?? (terminal === process15 ? stopJob : undefined);
1475
+ const suspend = () => {
1476
+ if (stop === undefined)
1477
+ return;
1478
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
1479
+ stdin.setRawMode(false);
1480
+ stop();
1481
+ stdin.setRawMode(true);
1482
+ stderr.write("\x1B[?25l\x1B[?2004h");
1483
+ };
1327
1484
  try {
1328
- await run([]);
1329
- } catch (error) {
1330
- if (error instanceof Completing)
1331
- return error;
1485
+ stderr.on?.("resize", redraw);
1486
+ stdin.setRawMode(true);
1487
+ stdin.resume();
1488
+ stderr.write("\x1B[?25l\x1B[?2004h");
1489
+ draw("asking");
1490
+ return await new Promise((resolve) => {
1491
+ function onData(data) {
1492
+ for (const key of readKeys(data.toString(), paste)) {
1493
+ if (key === "suspend") {
1494
+ suspend();
1495
+ continue;
1496
+ }
1497
+ const pressed = press(key);
1498
+ if (pressed !== undefined) {
1499
+ settle(pressed);
1500
+ return;
1501
+ }
1502
+ }
1503
+ draw("asking");
1504
+ }
1505
+ function onEnd() {
1506
+ settle("cancel");
1507
+ }
1508
+ function settle(settled) {
1509
+ outcome = settled;
1510
+ stdin.off("data", onData);
1511
+ stdin.off("end", onEnd);
1512
+ resolve(settled === "enter");
1513
+ }
1514
+ stdin.on("data", onData);
1515
+ stdin.on("end", onEnd);
1516
+ });
1332
1517
  } finally {
1333
- completion.active = false;
1518
+ stderr.off?.("resize", redraw);
1519
+ draw(outcome ?? "cancel", true);
1520
+ stderr.write(`
1521
+ \x1B[?25h\x1B[?2004l`);
1522
+ stdin.setRawMode(false);
1523
+ stdin.pause();
1524
+ }
1525
+ }
1526
+ var PROMPT_KEYS, MAX_LISTED = 12;
1527
+ var init_prompt = __esm(() => {
1528
+ init_answers();
1529
+ init_args();
1530
+ init_format();
1531
+ init_job();
1532
+ init_mode();
1533
+ init_line();
1534
+ init_state();
1535
+ init_redraw();
1536
+ init_style();
1537
+ PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
1538
+ });
1539
+
1540
+ // src/gb.ts
1541
+ import process26 from "process";
1542
+
1543
+ // ../kit/src/index.ts
1544
+ init_args();
1545
+
1546
+ // ../kit/src/argv.ts
1547
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
1548
+ import { resolve as resolve3 } from "path";
1549
+ import process10 from "process";
1550
+ function commandLine() {
1551
+ try {
1552
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
1553
+ } catch {
1554
+ return;
1334
1555
  }
1335
- return new Completing({});
1336
- }
1337
- function candidateLine(candidate) {
1338
- return typeof candidate === "string" ? candidate : candidate.join("\t");
1339
1556
  }
1340
- function positionalBeingTyped(before, { options, positionals }) {
1341
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1342
- const typed = [];
1343
- let at = 0;
1344
- while (at < before.length) {
1345
- const word = before[at];
1346
- if (word === "--") {
1347
- typed.push(...before.slice(at + 1));
1348
- break;
1349
- }
1350
- if (!word.startsWith("-"))
1351
- typed.push(word);
1352
- else if (takesValue(word))
1353
- at++;
1354
- at++;
1557
+ function realPath(word) {
1558
+ try {
1559
+ return realpathSync(resolve3(word));
1560
+ } catch {
1561
+ return;
1355
1562
  }
1356
- const last = positionals.at(-1);
1357
- if (typed.length < positionals.length)
1358
- return { name: positionals[typed.length], typed };
1359
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1360
1563
  }
1361
- async function leafCandidates(run, words) {
1362
- const completing = await completingOf(run);
1363
- if ((words.at(-1) ?? "").startsWith("-"))
1364
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1365
- const flag = words.at(-2);
1366
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1367
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1368
- if (option?.type === "string") {
1369
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1370
- return values === undefined ? [FILES] : values.map(candidateLine);
1371
- }
1372
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1373
- return values === undefined ? [FILES] : values.map(candidateLine);
1564
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
1565
+ const target = script === undefined ? undefined : realPath(script) ?? script;
1566
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
1567
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
1568
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
1374
1569
  }
1375
- var COMPLETIONS = "--completions";
1376
- function flagValue([flag = "", ...rest]) {
1377
- return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1570
+ // ../kit/src/chart.ts
1571
+ init_format();
1572
+ init_mode();
1573
+ init_style();
1574
+ init_theme();
1575
+ // ../kit/src/ci.ts
1576
+ init_args();
1577
+ init_format();
1578
+
1579
+ // ../kit/src/progress.ts
1580
+ init_format();
1581
+ import process12 from "process";
1582
+
1583
+ // ../kit/src/process.ts
1584
+ import { constants } from "os";
1585
+ import process11 from "process";
1586
+ var KILL_GRACE_MS = 2000;
1587
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1588
+ function exitCodeOf(code, signal) {
1589
+ if (code !== null)
1590
+ return code;
1591
+ if (typeof signal === "number")
1592
+ return 128 + signal;
1593
+ return signal === null ? 129 : 128 + constants.signals[signal];
1378
1594
  }
1379
- function printCompletionScript(name, args) {
1380
- const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1381
- if (shell === undefined || args.length !== 1) {
1382
- printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1383
- return 2;
1595
+ function holdSignals(cleanup) {
1596
+ let received;
1597
+ let child;
1598
+ const held = {
1599
+ get signal() {
1600
+ return received;
1601
+ },
1602
+ forward: (to) => {
1603
+ child = to;
1604
+ },
1605
+ release: () => {
1606
+ for (const signal of SIGNALS)
1607
+ process11.off(signal, onSignal);
1608
+ }
1609
+ };
1610
+ function onSignal(signal) {
1611
+ received = signal;
1612
+ if (child !== undefined) {
1613
+ child.kill(signal);
1614
+ return;
1615
+ }
1616
+ if (cleanup === undefined)
1617
+ return;
1618
+ held.release();
1619
+ cleanup(signal);
1620
+ process11.kill(process11.pid, signal);
1384
1621
  }
1385
- console.log(completionScript(shell, [name]).trimEnd());
1386
- return 0;
1387
- }
1388
- async function printCandidates(found) {
1389
- for (const line of await found)
1390
- console.log(line);
1391
- return 0;
1622
+ for (const signal of SIGNALS)
1623
+ process11.on(signal, onSignal);
1624
+ return held;
1392
1625
  }
1393
- function packageVersion(entry = Bun.main) {
1394
- let resolved = entry;
1395
- try {
1396
- resolved = realpathSync2(entry);
1397
- } catch {}
1398
- for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1626
+ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
1627
+ const chunks = [];
1628
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
1629
+ 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 } : {} });
1630
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
1631
+ const timers = [];
1632
+ const killGroup = (killing) => {
1633
+ if (state.done)
1634
+ return;
1399
1635
  try {
1400
- const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1401
- if (typeof version === "string")
1402
- return version;
1636
+ if (grouped)
1637
+ process11.kill(-proc.pid, killing);
1638
+ else
1639
+ proc.kill(killing);
1403
1640
  } catch {}
1404
- if (dirname3(dir) === dir)
1405
- return "0.0.0";
1406
- }
1407
- }
1408
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1409
- if (argv[0] === COMPLETE)
1410
- return printCandidates(leafCandidates(run, argv.slice(1)));
1411
- if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1412
- return printCompletionScript(name, flagValue(argv));
1413
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1414
- console.log(version ?? packageVersion());
1415
- return 0;
1641
+ };
1642
+ const stop = () => {
1643
+ killGroup("SIGTERM");
1644
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
1645
+ };
1646
+ const onAbort = () => stop();
1647
+ if (timeoutMs !== undefined) {
1648
+ timers.push(setTimeout(() => {
1649
+ state.timedOut = true;
1650
+ stop();
1651
+ }, timeoutMs));
1416
1652
  }
1417
- let code;
1418
- const started = performance.now();
1653
+ if (signal?.aborted === true)
1654
+ onAbort();
1655
+ else
1656
+ signal?.addEventListener("abort", onAbort, { once: true });
1657
+ onStart?.({ kill: (killing) => killGroup(killing) });
1658
+ const drain = async (stream, name) => {
1659
+ for await (const data of stream) {
1660
+ if (state.failure !== undefined)
1661
+ continue;
1662
+ try {
1663
+ onChunk?.({ stream: name, data });
1664
+ } catch (error) {
1665
+ state.failure = error;
1666
+ stop();
1667
+ continue;
1668
+ }
1669
+ if (state.kept + data.length > maxBytes) {
1670
+ state.truncated = true;
1671
+ continue;
1672
+ }
1673
+ state.kept += data.length;
1674
+ chunks.push({ stream: name, data });
1675
+ }
1676
+ };
1419
1677
  try {
1420
- code = await run(argv);
1421
- } catch (error) {
1422
- code = reportThrown(name, error, redact, wantsJson(argv));
1678
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
1679
+ await proc.exited;
1680
+ } finally {
1681
+ state.done = true;
1682
+ for (const timer of timers)
1683
+ clearTimeout(timer);
1684
+ signal?.removeEventListener("abort", onAbort);
1423
1685
  }
1424
- notifyEnd(name, code, performance.now() - started);
1425
- if (usage !== false) {
1426
- try {
1427
- recordUsage(usageEntry(name, undefined, argv, code));
1428
- } catch {}
1686
+ if (state.failure !== undefined)
1687
+ throw state.failure;
1688
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
1689
+ let output;
1690
+ let text;
1691
+ return {
1692
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
1693
+ chunks,
1694
+ timedOut: state.timedOut,
1695
+ truncated: state.truncated,
1696
+ get output() {
1697
+ return output ??= joined();
1698
+ },
1699
+ get text() {
1700
+ return text ??= (output ??= joined()).toString();
1701
+ }
1702
+ };
1703
+ }
1704
+
1705
+ // ../kit/src/progress.ts
1706
+ init_style();
1707
+ init_theme();
1708
+ var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1709
+ var FRAME_MS = 200;
1710
+ var BAR_WIDTH = 20;
1711
+ var CLEAR_BELOW = "\r\x1B[J";
1712
+ var ESC = String.fromCharCode(27);
1713
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
1714
+ var RESET_STYLE = `${ESC}[0m`;
1715
+ var CTRL_C = 3;
1716
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1717
+ var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
1718
+ function liveRegion(render, stream = process12.stderr, env = process12.env) {
1719
+ if (!takesControlCodes(stream, env))
1720
+ return { redraw: () => {
1721
+ return;
1722
+ }, print: (text) => void stream.write(`${text}
1723
+ `), stop: () => {
1724
+ return;
1725
+ }, pause: () => () => {
1726
+ return;
1727
+ } };
1728
+ const write = stream.write.bind(stream);
1729
+ let frame = 0;
1730
+ let drawn = false;
1731
+ let paused = false;
1732
+ let stopped = false;
1733
+ const columns = () => {
1734
+ const now = stream.getWindowSize?.()[0] ?? stream.columns;
1735
+ return now === undefined || now === 0 ? 80 : now;
1736
+ };
1737
+ const clear = () => {
1738
+ if (drawn)
1739
+ write(CLEAR_BELOW);
1740
+ drawn = false;
1741
+ };
1742
+ const draw = () => {
1743
+ if (paused)
1744
+ return;
1745
+ const width = columns() - 1;
1746
+ const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
1747
+ const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
1748
+ if (lines.length === 0) {
1749
+ clear();
1750
+ return;
1751
+ }
1752
+ write(`${CLEAR_BELOW}${lines.join(`
1753
+ `)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
1754
+ drawn = true;
1755
+ };
1756
+ let timer = setInterval(draw, FRAME_MS);
1757
+ stream.on?.("resize", draw);
1758
+ let restore = interceptOutput(clear);
1759
+ let release = swallowInput();
1760
+ const onExit = () => {
1761
+ clear();
1762
+ release();
1763
+ };
1764
+ const signals = holdSignals(stop);
1765
+ function stop() {
1766
+ stopped = true;
1767
+ clearInterval(timer);
1768
+ stream.off?.("resize", draw);
1769
+ clear();
1770
+ restore();
1771
+ release();
1772
+ process12.off("exit", onExit);
1773
+ signals.release();
1429
1774
  }
1430
- return code;
1775
+ function pause() {
1776
+ if (paused || stopped)
1777
+ return () => {
1778
+ return;
1779
+ };
1780
+ paused = true;
1781
+ clearInterval(timer);
1782
+ stream.off?.("resize", draw);
1783
+ clear();
1784
+ restore();
1785
+ release();
1786
+ return () => {
1787
+ if (!paused || stopped)
1788
+ return;
1789
+ paused = false;
1790
+ timer = setInterval(draw, FRAME_MS);
1791
+ timer.unref();
1792
+ stream.on?.("resize", draw);
1793
+ restore = interceptOutput(clear);
1794
+ release = swallowInput();
1795
+ draw();
1796
+ };
1797
+ }
1798
+ timer.unref();
1799
+ process12.on("exit", onExit);
1800
+ return {
1801
+ redraw: draw,
1802
+ print: (text) => {
1803
+ clear();
1804
+ write(`${text}
1805
+ `);
1806
+ draw();
1807
+ },
1808
+ stop,
1809
+ pause
1810
+ };
1431
1811
  }
1432
- // ../kit/src/folders.ts
1433
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1434
- // ../kit/src/secrets.ts
1435
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1436
- // ../kit/src/sessions.ts
1437
- var {Glob } = globalThis.Bun;
1438
- var SESSION_FILES = new Glob("*.json");
1439
- var ACCOUNT_DIRS = new Glob("*/sessions");
1440
- // ../kit/src/watch.ts
1441
- import process16 from "process";
1442
- import { format } from "util";
1443
- var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1444
- var DEFAULT_SECONDS = 2;
1445
- var ATTACHED_SHORT = /^-w./;
1446
- var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
1447
- function watchOption(what) {
1448
- return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
1812
+ function progressLine(stream = process12.stderr, env = process12.env) {
1813
+ const colors = paint(stream, env);
1814
+ const write = stream.write.bind(stream);
1815
+ const begun = performance.now();
1816
+ let started = begun;
1817
+ let current;
1818
+ const region = liveRegion((spinner) => current === undefined ? [] : [tintedParts(progressParts(current, spinner, performance.now() - started), colors)], stream, env);
1819
+ const end = (line) => {
1820
+ region.stop();
1821
+ write(`${line}
1822
+ `);
1823
+ };
1824
+ return {
1825
+ update: (progress) => {
1826
+ const step = current?.step;
1827
+ current = progress;
1828
+ if (progress.step !== step) {
1829
+ started = performance.now();
1830
+ region.redraw();
1831
+ }
1832
+ },
1833
+ stop: region.stop,
1834
+ pause: region.pause,
1835
+ done: (text) => end(marked("ok", text, stream, formatDuration(performance.now() - begun), env)),
1836
+ failed: (text) => end(marked("problem", text, stream, undefined, env))
1837
+ };
1838
+ }
1839
+ function progressParts({ step, done, total, unit }, spinner, ms) {
1840
+ const { theme } = activeTheme();
1841
+ const parts = [{ text: spinner, tint: (colors) => tinted(colors, theme.colors.accent) }, { text: ` ${step}`, tint: () => plain }];
1842
+ if (total !== undefined && total > 0) {
1843
+ const counted = Math.min(done ?? 0, total);
1844
+ const filled = Math.round(counted / total * BAR_WIDTH);
1845
+ parts.push({ text: " ", tint: () => plain }, { text: theme.glyphs.bar.repeat(filled), tint: (colors) => () => shaded(theme, colors, theme.glyphs.bar, filled, BAR_WIDTH) }, { text: theme.glyphs.bar.repeat(BAR_WIDTH - filled), tint: (colors) => colors.dim }, { text: ` ${counted}/${total}${unit === undefined ? "" : ` ${unit}`}`, tint: (colors) => colors.dim });
1846
+ }
1847
+ parts.push({ text: ` ${formatElapsed(ms)}`, tint: (colors) => colors.dim });
1848
+ return parts;
1449
1849
  }
1450
- function withoutWatch(args) {
1451
- const rest = [];
1452
- for (let at = 0;at < args.length; at++) {
1453
- const arg = args[at];
1454
- if (arg === "--watch" || arg === "-w") {
1455
- if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
1456
- at++;
1457
- } else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
1458
- rest.push(arg);
1850
+ function plain(text) {
1851
+ return text;
1852
+ }
1853
+ function tintedParts(parts, colors) {
1854
+ return parts.map(({ text, tint }) => tint(colors)(text)).join("");
1855
+ }
1856
+ function cutToWidth(line, width) {
1857
+ if (Bun.stringWidth(line) <= width)
1858
+ return line;
1859
+ let room = width;
1860
+ let kept = "";
1861
+ let index = 0;
1862
+ let linked = false;
1863
+ while (index < line.length) {
1864
+ ESCAPE_CODE.lastIndex = index;
1865
+ const escape = ESCAPE_CODE.exec(line);
1866
+ if (escape !== null) {
1867
+ kept += escape[0];
1868
+ linked ||= escape[0].startsWith(`${ESC}]`);
1869
+ index = ESCAPE_CODE.lastIndex;
1870
+ continue;
1459
1871
  }
1872
+ const char = String.fromCodePoint(line.codePointAt(index));
1873
+ const columns = Bun.stringWidth(char);
1874
+ if (columns > room)
1875
+ break;
1876
+ kept += char;
1877
+ room -= columns;
1878
+ index += char.length;
1460
1879
  }
1461
- return rest;
1880
+ return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
1462
1881
  }
1463
- async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1464
- const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1465
- if (!takesControlCodes(stream))
1466
- badUsage("--watch redraws the screen, so it needs a terminal");
1467
- let code = 0;
1468
- for (let round = 0;round < rounds; round++) {
1469
- const held = [];
1470
- const { log, info } = console;
1471
- const write = process16.stdout.write.bind(process16.stdout);
1472
- const hold = (...parts) => void held.push(`${format(...parts)}
1473
- `);
1474
- console.log = hold;
1475
- console.info = hold;
1476
- process16.stdout.write = (text) => {
1477
- held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1478
- return true;
1882
+ function swallowInput() {
1883
+ const input = process12.stdin;
1884
+ if (!input.isTTY)
1885
+ return () => {
1886
+ return;
1887
+ };
1888
+ const onData = (data) => {
1889
+ if (data.includes(CTRL_C))
1890
+ process12.kill(process12.pid, "SIGINT");
1891
+ };
1892
+ input.setRawMode(true);
1893
+ input.on("data", onData);
1894
+ input.resume();
1895
+ let released = false;
1896
+ return () => {
1897
+ if (released)
1898
+ return;
1899
+ released = true;
1900
+ input.off("data", onData);
1901
+ input.pause();
1902
+ input.setRawMode(false);
1903
+ };
1904
+ }
1905
+ function interceptOutput(clear) {
1906
+ const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
1907
+ const wrapped = targets.map(([target, name]) => {
1908
+ const original = Reflect.get(target, name);
1909
+ const wrapper = (...args) => {
1910
+ clear();
1911
+ return original.apply(target, args);
1479
1912
  };
1913
+ Reflect.set(target, name, wrapper);
1914
+ return { target, name, original, wrapper };
1915
+ });
1916
+ return () => {
1917
+ for (const { target, name, original, wrapper } of wrapped) {
1918
+ if (Reflect.get(target, name) === wrapper)
1919
+ Reflect.set(target, name, original);
1920
+ }
1921
+ };
1922
+ }
1923
+
1924
+ // ../kit/src/ci.ts
1925
+ init_style();
1926
+
1927
+ // ../kit/src/tool.ts
1928
+ init_format();
1929
+ // ../kit/src/cli.ts
1930
+ init_args();
1931
+ import { readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
1932
+ import { dirname as dirname4, join as join8 } from "path";
1933
+ import process19 from "process";
1934
+
1935
+ // ../kit/src/askpass.ts
1936
+ import { chmodSync, mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
1937
+ import { tmpdir } from "os";
1938
+ import { join as join6 } from "path";
1939
+ import process16 from "process";
1940
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1941
+ var ECHOED = /username|yes\/no/i;
1942
+ var quoted = (text) => `'${text.replaceAll("'", `'\\''`)}'`;
1943
+ function askpass(pause = () => () => {
1944
+ return;
1945
+ }) {
1946
+ if (process16.stdin.isTTY !== true || process16.stderr.isTTY !== true || process16.argv[1] === undefined)
1947
+ return;
1948
+ const dir = mkdtempSync(join6(tmpdir(), "kaynooo-askpass-"));
1949
+ const socketPath = join6(dir, "socket");
1950
+ const script = join6(dir, "askpass");
1951
+ let turn = Promise.resolve();
1952
+ const answer = async ({ prompt, notice }) => {
1953
+ const resume = pause();
1480
1954
  try {
1481
- code = await step();
1955
+ if (notice === true) {
1956
+ process16.stderr.write(`${prompt.trim()}
1957
+ `);
1958
+ return {};
1959
+ }
1960
+ await Promise.resolve().then(() => init_prompt());
1961
+ return { answer: await input2(prompt.trim(), { mask: !ECHOED.test(prompt) }) };
1482
1962
  } finally {
1483
- console.log = log;
1484
- console.info = info;
1485
- process16.stdout.write = write;
1963
+ resume();
1486
1964
  }
1487
- stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1488
- await sleep(interval);
1489
- }
1490
- return code;
1491
- }
1492
- // ../kit/src/workspace-root.ts
1493
- import { homedir as homedir4 } from "os";
1494
- import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
1495
- import process17 from "process";
1496
- function expandHome(path, home) {
1497
- if (path === "~")
1498
- return home;
1499
- return path.startsWith("~/") ? join6(home, path.slice(2)) : path;
1500
- }
1501
- function configured(env, home) {
1502
- const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
1503
- return typeof folder === "string" && folder !== "" ? folder : undefined;
1965
+ };
1966
+ const respond = async (socket, request) => {
1967
+ const { promise, resolve } = Promise.withResolvers();
1968
+ const previous = turn;
1969
+ let reply = {};
1970
+ turn = promise;
1971
+ await previous;
1972
+ try {
1973
+ reply = await answer(request);
1974
+ } catch {} finally {
1975
+ socket.end(`${JSON.stringify(reply)}
1976
+ `);
1977
+ resolve();
1978
+ }
1979
+ };
1980
+ const server = Bun.listen({
1981
+ unix: socketPath,
1982
+ socket: {
1983
+ open: (socket) => {
1984
+ socket.data = { buffered: "" };
1985
+ },
1986
+ data: (socket, chunk) => {
1987
+ const before = socket.data.buffered;
1988
+ socket.data.buffered += chunk.toString();
1989
+ if (before.includes(`
1990
+ `) || !socket.data.buffered.includes(`
1991
+ `))
1992
+ return;
1993
+ respond(socket, JSON.parse(socket.data.buffered));
1994
+ }
1995
+ }
1996
+ });
1997
+ writeFileSync2(script, `#!/bin/sh
1998
+ ${SOCKET_VARIABLE}=${quoted(socketPath)} exec ${quoted(process16.execPath)} --no-env-file --config=/dev/null ${quoted(process16.argv[1])} "$@"
1999
+ `);
2000
+ chmodSync(script, 448);
2001
+ return {
2002
+ env: { GIT_ASKPASS: script, SSH_ASKPASS: script, SSH_ASKPASS_REQUIRE: "force" },
2003
+ close: () => {
2004
+ server.stop(true);
2005
+ rmSync(dir, { recursive: true, force: true });
2006
+ }
2007
+ };
1504
2008
  }
1505
- function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
1506
- const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1507
- return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
2009
+ async function askpassClient(argv) {
2010
+ const socketPath = process16.env[SOCKET_VARIABLE];
2011
+ if (socketPath === undefined)
2012
+ return;
2013
+ const request = { prompt: argv[0] ?? "", ...process16.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
2014
+ const { promise, resolve } = Promise.withResolvers();
2015
+ let received = "";
2016
+ try {
2017
+ await Bun.connect({
2018
+ unix: socketPath,
2019
+ socket: {
2020
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
2021
+ `),
2022
+ data: (_, chunk) => {
2023
+ received += chunk.toString();
2024
+ },
2025
+ close: () => resolve(received),
2026
+ error: () => resolve("")
2027
+ }
2028
+ });
2029
+ } catch {
2030
+ return 1;
2031
+ }
2032
+ const reply = await promise;
2033
+ if (reply === "")
2034
+ return 1;
2035
+ const { answer } = JSON.parse(reply);
2036
+ if (request.notice === true)
2037
+ return 0;
2038
+ if (answer === undefined)
2039
+ return 1;
2040
+ process16.stdout.write(`${answer}
2041
+ `);
2042
+ return 0;
1508
2043
  }
1509
- // src/branch.ts
1510
- import { basename } from "path";
1511
- import process22 from "process";
1512
2044
 
1513
- // ../kit/src/picker/line.ts
1514
- var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
1515
- var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
1516
- var FORWARD_KILLS = new Set(["killnext", "killend"]);
1517
- function isEditKey(key) {
1518
- return EDIT_KEYS.has(key);
2045
+ // ../kit/src/completions.ts
2046
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
2047
+ 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'
2048
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
2049
+ set -l current (commandline -ct)
2050
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
2051
+ if test "$line" = __files__
2052
+ __fish_complete_path $current
2053
+ else
2054
+ echo $line
2055
+ end
2056
+ end
2057
+ end`;
2058
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
2059
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
2060
+ local -a lines
2061
+ COMPREPLY=()
2062
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
2063
+ for line in "\${lines[@]}"; do
2064
+ if [[ $line == __files__ ]]; then
2065
+ COMPREPLY+=($(compgen -f -- "$cur"))
2066
+ else
2067
+ words+="\${line%%$'\\t'*}"$'\\n'
2068
+ fi
2069
+ done
2070
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
2071
+ }`;
2072
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
2073
+ local line
2074
+ local -a described plain
2075
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
2076
+ if [[ $line == __files__ ]]; then
2077
+ _files
2078
+ elif [[ $line == *$'\\t'* ]]; then
2079
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
2080
+ else
2081
+ plain+=("$line")
2082
+ fi
2083
+ done
2084
+ (( \${#described} )) && _describe -V value described
2085
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
2086
+ return 0
2087
+ }`;
2088
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
2089
+ if (shell === "fish")
2090
+ return `${header}
2091
+ ${FISH_FUNCTION}
2092
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
2093
+ `).join("")}`;
2094
+ if (shell === "bash")
2095
+ return `${header}
2096
+ ${BASH_FUNCTION}
2097
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
2098
+ `;
2099
+ return `${header}
2100
+ ${ZSH_FUNCTION}
2101
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
2102
+ `;
1519
2103
  }
1520
- function endsKills(key) {
1521
- return typeof key !== "object" && !isEditKey(key);
2104
+
2105
+ // ../kit/src/notify.ts
2106
+ init_format();
2107
+ init_mode();
2108
+ import process17 from "process";
2109
+ var NOTIFY_AFTER_MS = 1e4;
2110
+ var CANCELLED = 130;
2111
+ function base64(text) {
2112
+ return Buffer.from(text).toString("base64");
1522
2113
  }
1523
- var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
1524
- var SPACE = /\s/;
1525
- function isWord(char) {
1526
- return char !== undefined && WORD_CHARACTER.test(char);
2114
+ function notification(title, body, env = process17.env) {
2115
+ const id = `kit${process17.pid}`;
2116
+ 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\\`];
2117
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1527
2118
  }
1528
- function wordStart(chars, from) {
1529
- let at = from;
1530
- while (at > 0 && !isWord(chars[at - 1]))
1531
- at--;
1532
- while (at > 0 && isWord(chars[at - 1]))
1533
- at--;
1534
- return at;
2119
+ function notifyEnd(command, code, ms, { stream = process17.stderr, env = process17.env } = {}) {
2120
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
2121
+ return;
2122
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1535
2123
  }
1536
- function wordEnd(chars, from) {
1537
- let at = from;
1538
- while (at < chars.length && !isWord(chars[at]))
1539
- at++;
1540
- while (at < chars.length && isWord(chars[at]))
1541
- at++;
1542
- return at;
2124
+
2125
+ // ../kit/src/cli.ts
2126
+ init_style();
2127
+ init_text2();
2128
+
2129
+ // ../kit/src/usage.ts
2130
+ import { appendFileSync, mkdirSync as mkdirSync2 } from "fs";
2131
+ import { homedir as homedir4 } from "os";
2132
+ import { dirname as dirname3, isAbsolute, join as join7 } from "path";
2133
+ import process18 from "process";
2134
+
2135
+ // ../kit/src/logs.ts
2136
+ var DAY_MS = 24 * 60 * 60 * 1000;
2137
+ var CLI_FOLDER = "kaynooo-cli";
2138
+
2139
+ // ../kit/src/usage.ts
2140
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
2141
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
2142
+ var LONGEST_NAME = 40;
2143
+ var usageError;
2144
+ function noteUsageError(message) {
2145
+ usageError = message;
1543
2146
  }
1544
- function spacedStart(chars, from) {
1545
- let at = from;
1546
- while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
1547
- at--;
1548
- while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
1549
- at--;
1550
- return at;
2147
+ function stateHome(env = process18.env) {
2148
+ const dir = env.XDG_STATE_HOME;
2149
+ return dir !== undefined && isAbsolute(dir) ? dir : join7(homedir4(), ".local", "state");
1551
2150
  }
1552
- function cut(chars, from, to) {
1553
- return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
2151
+ function usagePath(env = process18.env) {
2152
+ return join7(stateHome(env), CLI_FOLDER, "usage.jsonl");
1554
2153
  }
1555
- function insert(chars, at, text) {
1556
- const typed = [...text];
1557
- return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
2154
+ function usageRecorded(env = process18.env) {
2155
+ const off = env.KAYNOOO_CLI_NO_USAGE;
2156
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1558
2157
  }
1559
- function editLine(line, key) {
1560
- const { killed = "", chained = false } = line;
1561
- const chars = [...line.text];
1562
- const at = Math.min(Math.max(line.caret, 0), chars.length);
1563
- const edited = edit(chars, at, key, killed);
1564
- if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
1565
- return line.killed === undefined ? edited : { ...edited, killed };
1566
- const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
1567
- if (taken === "")
1568
- return { ...edited, killed, chained };
1569
- if (!chained)
1570
- return { ...edited, killed: taken, chained: true };
1571
- return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
2158
+ function flagNames(argv) {
2159
+ const end = argv.indexOf("--");
2160
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
2161
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1572
2162
  }
1573
- function edit(chars, at, key, killed) {
1574
- const text = chars.join("");
1575
- if (typeof key === "object")
1576
- return insert(chars, at, key.text);
1577
- switch (key) {
1578
- case "left":
1579
- return { text, caret: Math.max(at - 1, 0) };
1580
- case "right":
1581
- return { text, caret: Math.min(at + 1, chars.length) };
1582
- case "wordleft":
1583
- return { text, caret: wordStart(chars, at) };
1584
- case "wordright":
1585
- return { text, caret: wordEnd(chars, at) };
1586
- case "linestart":
1587
- return { text, caret: 0 };
1588
- case "lineend":
1589
- return { text, caret: chars.length };
1590
- case "erase":
1591
- return cut(chars, Math.max(at - 1, 0), at);
1592
- case "delete":
1593
- return cut(chars, at, Math.min(at + 1, chars.length));
1594
- case "word":
1595
- return cut(chars, spacedStart(chars, at), at);
1596
- case "killword":
1597
- return cut(chars, wordStart(chars, at), at);
1598
- case "killnext":
1599
- return cut(chars, at, wordEnd(chars, at));
1600
- case "clear":
1601
- return cut(chars, 0, at);
1602
- case "killend":
1603
- return cut(chars, at, chars.length);
1604
- case "yank":
1605
- return insert(chars, at, killed);
1606
- }
2163
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
2164
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
2165
+ usageError = undefined;
2166
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1607
2167
  }
1608
- function visible({ text, caret }, room) {
1609
- const chars = [...text];
1610
- const at = Math.min(Math.max(caret, 0), chars.length);
1611
- const cells = at === chars.length ? [...chars, " "] : chars;
1612
- const widths = cells.map((char) => Bun.stringWidth(char));
1613
- const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
1614
- const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
1615
- let start = at;
1616
- let end = at + 1;
1617
- while (start > 0 && fits(start - 1, end))
1618
- start--;
1619
- while (end < cells.length && fits(start, end + 1))
1620
- end++;
1621
- const left = start > 0 ? "\u2026" : "";
1622
- const right = end < cells.length ? "\u2026" : "";
1623
- return { before: left + chars.slice(start, at).join(""), at: chars[at], after: chars.slice(at + 1, end).join("") + right, column: left.length + width(start, at) };
2168
+ function recordUsage(entry, env = process18.env) {
2169
+ if (!usageRecorded(env))
2170
+ return;
2171
+ try {
2172
+ const path = usagePath(env);
2173
+ mkdirSync2(dirname3(path), { recursive: true, mode: 448 });
2174
+ appendFileSync(path, `${JSON.stringify(entry)}
2175
+ `, { mode: 384 });
2176
+ } catch {}
1624
2177
  }
1625
2178
 
1626
- // ../kit/src/picker/score.ts
1627
- var MATCH = 16;
1628
- var CONSECUTIVE = 12;
1629
- var BOUNDARY = 10;
1630
- var PREFIX = 8;
1631
- var GAP = 1;
1632
- var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1633
- var UPPER = /\p{Lu}/u;
1634
- var LOWER = /\p{Ll}/u;
1635
- var NONE = Number.NEGATIVE_INFINITY;
1636
- function startsWord(text, index) {
1637
- if (index === 0)
1638
- return true;
1639
- const before = text[index - 1];
1640
- return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
2179
+ // ../kit/src/cli.ts
2180
+ var LEVEL_OPTIONS = {
2181
+ ...OUTPUT_OPTIONS,
2182
+ help: { type: "boolean", short: "h", description: "show this help" }
2183
+ };
2184
+ var TOP_OPTIONS = {
2185
+ ...LEVEL_OPTIONS,
2186
+ version: { type: "boolean", short: "v", description: "print the version" },
2187
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
2188
+ };
2189
+ function printError(prefix, message, hint, cause) {
2190
+ const colors = paint(process19.stderr);
2191
+ const styled = takesControlCodes(process19.stderr);
2192
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
2193
+ const under = (label, text, tint) => text === undefined ? "" : `
2194
+ ${styled ? tint(label) : `${label}:`} ${text}`;
2195
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1641
2196
  }
1642
- function fuzzy(query, text) {
1643
- if (query === "")
1644
- return { score: 0, positions: [] };
1645
- const exact = query !== query.toLowerCase();
1646
- const needle = exact ? query : query.toLowerCase();
1647
- const haystack = exact ? text : text.toLowerCase();
1648
- if (haystack.length !== text.length || needle.length > haystack.length)
1649
- return;
1650
- const width = haystack.length;
1651
- const best = Array.from({ length: needle.length }, () => new Array(width).fill(NONE));
1652
- const from = Array.from({ length: needle.length }, () => new Array(width).fill(-1));
1653
- for (let j = 0;j < needle.length; j++) {
1654
- let run = NONE;
1655
- let runAt = -1;
1656
- for (let i = j;i < width; i++) {
1657
- if (j > 0 && i - 2 >= j - 1) {
1658
- const candidate = best[j - 1][i - 2] + (i - 2) * GAP;
1659
- if (candidate > run) {
1660
- run = candidate;
1661
- runAt = i - 2;
1662
- }
1663
- }
1664
- if (haystack[i] !== needle[j])
1665
- continue;
1666
- const here = MATCH + (startsWord(text, i) ? BOUNDARY : 0) + (i === 0 ? PREFIX : 0);
1667
- if (j === 0) {
1668
- best[0][i] = here - i * GAP;
1669
- continue;
1670
- }
1671
- const joined = best[j - 1][i - 1] + CONSECUTIVE;
1672
- const skipped = run - (i - 1) * GAP;
1673
- if (joined > NONE && joined >= skipped) {
1674
- best[j][i] = joined + here;
1675
- from[j][i] = i - 1;
1676
- } else if (skipped > NONE) {
1677
- best[j][i] = skipped + here;
1678
- from[j][i] = runAt;
1679
- }
1680
- }
1681
- }
1682
- const last = best[needle.length - 1];
1683
- let end = -1;
1684
- for (let i = 0;i < width; i++) {
1685
- if (last[i] > NONE && (end === -1 || last[i] > last[end]))
1686
- end = i;
1687
- }
1688
- if (end === -1)
1689
- return;
1690
- const positions = [];
1691
- for (let j = needle.length - 1, i = end;j >= 0; j--) {
1692
- positions.unshift(i);
1693
- i = from[j][i];
1694
- }
1695
- return { score: last[end], positions };
2197
+ function runHint(command, effect) {
2198
+ return `run \`${command}\`${effect === undefined ? "" : ` to ${effect}`}`;
1696
2199
  }
1697
- function rank(query, lines) {
1698
- if (query === "")
1699
- return lines.map((_, index) => ({ index, positions: [] }));
1700
- const found = [];
1701
- for (const [index, line] of lines.entries()) {
1702
- const match = fuzzy(query, line);
1703
- if (match !== undefined)
1704
- found.push({ index, positions: match.positions, score: match.score });
1705
- }
1706
- return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
2200
+ function printJsonError(message, hint, cause) {
2201
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1707
2202
  }
1708
-
1709
- // ../kit/src/picker/state.ts
1710
- var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1711
- var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1712
- var SGR = /^\x1B\[[0-9;]*m$/;
1713
- var RESET = /^\x1B\[0?m$/;
1714
- var COLUMN_GAP = 2;
1715
- var PASTE_START = "\x1B[200~";
1716
- var PASTE_END = "\x1B[201~";
1717
- var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1718
- var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1719
- var WHEEL_LINES = 3;
1720
- var KEYS = {
1721
- "\x1B[A": "up",
1722
- "\x1BOA": "up",
1723
- "\x10": "up",
1724
- "\x1B[B": "down",
1725
- "\x1BOB": "down",
1726
- "\x0E": "down",
1727
- "\x1B[5~": "pageup",
1728
- "\x1B[6~": "pagedown",
1729
- "\x1B[H": "home",
1730
- "\x1B[1~": "home",
1731
- "\x1BOH": "home",
1732
- "\x1B[F": "end",
1733
- "\x1B[4~": "end",
1734
- "\x1BOF": "end",
1735
- "\r": "enter",
1736
- "\n": "enter",
1737
- "\x03": "cancel",
1738
- "\x1B": "cancel",
1739
- "\x1B[D": "left",
1740
- "\x1BOD": "left",
1741
- "\x1B[C": "right",
1742
- "\x1BOC": "right",
1743
- "\x1B[1;5D": "wordleft",
1744
- "\x1B[1;3D": "wordleft",
1745
- "\x1Bb": "wordleft",
1746
- "\x1B[1;5C": "wordright",
1747
- "\x1B[1;3C": "wordright",
1748
- "\x1Bf": "wordright",
1749
- "\x01": "linestart",
1750
- "\x05": "lineend",
1751
- "\x7F": "erase",
1752
- "\x1B[3~": "delete",
1753
- "\b": "killword",
1754
- "\x1B\x7F": "killword",
1755
- "\x1B[3;5~": "killnext",
1756
- "\x1Bd": "killnext",
1757
- "\x15": "clear",
1758
- "\v": "killend",
1759
- "\x17": "word",
1760
- "\x19": "yank",
1761
- "\x1A": "suspend",
1762
- "\t": "tab",
1763
- "\x1F": "help",
1764
- "\x1BOP": "help",
1765
- "\x1B[11~": "help"
1766
- };
1767
- var CTRL_KEY = /^ctrl-[abd-gkln-z]$/;
1768
- function repeat(value, count) {
1769
- return Array.from({ length: count }).fill(value);
2203
+ function wantsJson(argv) {
2204
+ const end = argv.indexOf("--");
2205
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1770
2206
  }
1771
- function styled(line) {
1772
- let text = "";
1773
- const styles = [];
1774
- let active = "";
1775
- let colored = false;
1776
- let last = 0;
1777
- function add(chunk) {
1778
- const flat = chunk.replace(CONTROL2, " ");
1779
- text += flat;
1780
- colored ||= active !== "" && flat !== "";
1781
- styles.push(...repeat(active, flat.length));
1782
- }
1783
- for (const found of line.matchAll(ANSI)) {
1784
- add(line.slice(last, found.index));
1785
- last = found.index + found[0].length;
1786
- if (SGR.test(found[0]))
1787
- active = RESET.test(found[0]) ? "" : active + found[0];
1788
- }
1789
- add(line.slice(last));
1790
- return { text, styles: colored ? styles : undefined };
2207
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
2208
+ if (error instanceof HelpShown)
2209
+ return 0;
2210
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
2211
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
2212
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
2213
+ if (error instanceof Exit && error.code === 2)
2214
+ noteUsageError(error.message);
2215
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
2216
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
2217
+ return error instanceof Exit ? error.code : 1;
1791
2218
  }
1792
- function lay(rows, searched) {
1793
- const parsed = rows.map((row) => row.cells.map(styled));
1794
- const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
1795
- return parsed.map((cells, at) => {
1796
- let text = "";
1797
- const styles = [];
1798
- let colored = false;
1799
- let searchEnd = 0;
1800
- for (const [column, cell] of cells.entries()) {
1801
- const last = column === cells.length - 1;
1802
- const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
1803
- text += shown;
1804
- colored ||= cell.styles !== undefined;
1805
- styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
1806
- if (column < searched)
1807
- searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
1808
- if (!last) {
1809
- const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
1810
- text += " ".repeat(pad);
1811
- styles.push(...repeat("", pad));
1812
- }
1813
- }
1814
- return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
1815
- });
2219
+ var COMPLETE = "__complete";
2220
+ var FILES = "__files__";
2221
+ async function completingOf(run) {
2222
+ completion.active = true;
2223
+ try {
2224
+ await run([]);
2225
+ } catch (error) {
2226
+ if (error instanceof Completing)
2227
+ return error;
2228
+ } finally {
2229
+ completion.active = false;
2230
+ }
2231
+ return new Completing({});
1816
2232
  }
1817
- function parseKeys(input, paste = { active: false }, ctrls = []) {
1818
- const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1819
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1820
- const wheel = MOUSE.exec(sequence)?.[1];
1821
- if (wheel !== undefined)
1822
- return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1823
- const named = codes.get(sequence);
1824
- const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1825
- if (sequence === PASTE_START || sequence === PASTE_END) {
1826
- paste.active = sequence === PASTE_START;
1827
- return [];
2233
+ function candidateLine(candidate) {
2234
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
2235
+ }
2236
+ function positionalBeingTyped(before, { options, positionals }) {
2237
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
2238
+ const typed = [];
2239
+ let at = 0;
2240
+ while (at < before.length) {
2241
+ const word = before[at];
2242
+ if (word === "--") {
2243
+ typed.push(...before.slice(at + 1));
2244
+ break;
1828
2245
  }
1829
- if (paste.active && (sequence === "\r" || sequence === `
1830
- `))
1831
- return [];
1832
- if (key !== undefined)
1833
- return [key];
1834
- return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1835
- });
2246
+ if (!word.startsWith("-"))
2247
+ typed.push(word);
2248
+ else if (takesValue(word))
2249
+ at++;
2250
+ at++;
2251
+ }
2252
+ const last = positionals.at(-1);
2253
+ if (typed.length < positionals.length)
2254
+ return { name: positionals[typed.length], typed };
2255
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1836
2256
  }
1837
- function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1838
- const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, caret: [...query].length, killed: "", chained: false, matches: [], cursor: 0, help: false, page: 10, marked: new Set, multi, prompt, done: undefined };
1839
- return withRows(state, rows);
2257
+ async function leafCandidates(run, words) {
2258
+ const completing = await completingOf(run);
2259
+ if ((words.at(-1) ?? "").startsWith("-"))
2260
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
2261
+ const flag = words.at(-2);
2262
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
2263
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
2264
+ if (option?.type === "string") {
2265
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
2266
+ return values === undefined ? [FILES] : values.map(candidateLine);
2267
+ }
2268
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
2269
+ return values === undefined ? [FILES] : values.map(candidateLine);
1840
2270
  }
1841
- function withRows(state, rows, header = state.header) {
1842
- const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1843
- const laid = lay(cells, state.searched);
1844
- const searchable = laid.map((row) => row.searchable);
1845
- const matches = rank(state.query, searchable);
1846
- 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 };
2271
+ var COMPLETIONS = "--completions";
2272
+ function flagValue([flag = "", ...rest]) {
2273
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1847
2274
  }
1848
- function withQuery(state, key) {
1849
- const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1850
- return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
2275
+ function printCompletionScript(name, args) {
2276
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
2277
+ if (shell === undefined || args.length !== 1) {
2278
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
2279
+ return 2;
2280
+ }
2281
+ console.log(completionScript(shell, [name]).trimEnd());
2282
+ return 0;
1851
2283
  }
1852
- function move(state, by) {
1853
- return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
2284
+ async function printCandidates(found) {
2285
+ for (const line of await found)
2286
+ console.log(line);
2287
+ return 0;
1854
2288
  }
1855
- function highlighted(state) {
1856
- return state.matches[state.cursor]?.index;
2289
+ function packageVersion(entry = Bun.main) {
2290
+ let resolved = entry;
2291
+ try {
2292
+ resolved = realpathSync2(entry);
2293
+ } catch {}
2294
+ for (let dir = dirname4(resolved);; dir = dirname4(dir)) {
2295
+ try {
2296
+ const { version } = JSON.parse(readFileSync5(join8(dir, "package.json"), "utf8"));
2297
+ if (typeof version === "string")
2298
+ return version;
2299
+ } catch {}
2300
+ if (dirname4(dir) === dir)
2301
+ return "0.0.0";
2302
+ }
1857
2303
  }
1858
- function press(state, key) {
1859
- if (state.done !== undefined)
1860
- return state;
1861
- if (state.chained && endsKills(key))
1862
- state = { ...state, chained: false };
1863
- if (state.help)
1864
- return { ...state, help: false };
1865
- if (typeof key === "object") {
1866
- if ("text" in key)
1867
- return withQuery(state, key);
1868
- return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
2304
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
2305
+ const answered = await askpassClient(argv);
2306
+ if (answered !== undefined)
2307
+ return answered;
2308
+ if (argv[0] === COMPLETE)
2309
+ return printCandidates(leafCandidates(run, argv.slice(1)));
2310
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
2311
+ return printCompletionScript(name, flagValue(argv));
2312
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
2313
+ console.log(version ?? packageVersion());
2314
+ return 0;
1869
2315
  }
1870
- if (isEditKey(key))
1871
- return withQuery(state, key);
1872
- switch (key) {
1873
- case "up":
1874
- return move(state, -1);
1875
- case "down":
1876
- return move(state, 1);
1877
- case "pageup":
1878
- return move(state, -state.page);
1879
- case "pagedown":
1880
- return move(state, state.page);
1881
- case "home":
1882
- return move(state, -state.matches.length);
1883
- case "end":
1884
- return move(state, state.matches.length);
1885
- case "cancel":
1886
- return { ...state, done: "cancel" };
1887
- case "help":
1888
- return { ...state, help: true };
1889
- case "suspend":
1890
- return state;
1891
- case "enter":
1892
- return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1893
- case "tab": {
1894
- const at = highlighted(state);
1895
- if (!state.multi || at === undefined)
1896
- return state;
1897
- const marked = new Set(state.marked);
1898
- if (!marked.delete(at))
1899
- marked.add(at);
1900
- return move({ ...state, marked }, 1);
2316
+ let code;
2317
+ const started = performance.now();
2318
+ try {
2319
+ code = await run(argv);
2320
+ } catch (error) {
2321
+ code = reportThrown(name, error, redact, wantsJson(argv));
2322
+ }
2323
+ notifyEnd(name, code, performance.now() - started);
2324
+ if (usage !== false) {
2325
+ try {
2326
+ recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
2327
+ } catch {}
2328
+ }
2329
+ return code;
2330
+ }
2331
+
2332
+ // ../kit/src/index.ts
2333
+ init_config();
2334
+
2335
+ // ../kit/src/excerpt.ts
2336
+ init_text2();
2337
+
2338
+ // ../kit/src/index.ts
2339
+ init_folders();
2340
+ init_format();
2341
+
2342
+ // ../kit/src/git.ts
2343
+ init_args();
2344
+ // ../kit/src/limit.ts
2345
+ init_args();
2346
+
2347
+ // ../kit/src/index.ts
2348
+ init_mode();
2349
+
2350
+ // ../kit/src/report.ts
2351
+ init_style();
2352
+ init_text2();
2353
+ // ../kit/src/secrets.ts
2354
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
2355
+ // ../kit/src/sessions.ts
2356
+ var {Glob } = globalThis.Bun;
2357
+ var SESSION_FILES = new Glob("*.json");
2358
+ var ACCOUNT_DIRS = new Glob("*/sessions");
2359
+
2360
+ // ../kit/src/index.ts
2361
+ init_style();
2362
+ init_text2();
2363
+ init_theme();
2364
+ init_user_config();
2365
+
2366
+ // ../kit/src/watch.ts
2367
+ init_args();
2368
+ init_input();
2369
+ init_style();
2370
+ import process20 from "process";
2371
+ import { format } from "util";
2372
+ var CLEAR_SCREEN = "\x1B[H\x1B[2J";
2373
+ var DEFAULT_SECONDS = 2;
2374
+ var ATTACHED_SHORT = /^-w./;
2375
+ var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
2376
+ function watchOption(what) {
2377
+ return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
2378
+ }
2379
+ function withoutWatch(args) {
2380
+ const rest = [];
2381
+ for (let at = 0;at < args.length; at++) {
2382
+ const arg = args[at];
2383
+ if (arg === "--watch" || arg === "-w") {
2384
+ if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
2385
+ at++;
2386
+ } else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
2387
+ rest.push(arg);
1901
2388
  }
1902
2389
  }
2390
+ return rest;
1903
2391
  }
1904
- function chosen(state) {
1905
- if (state.marked.size > 0)
1906
- return state.rows.filter((_, index) => state.marked.has(index));
1907
- const at = highlighted(state);
1908
- return at === undefined ? [] : [state.rows[at]];
2392
+ async function watching(value, step, stream = process20.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
2393
+ const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
2394
+ if (!takesControlCodes(stream))
2395
+ badUsage("--watch redraws the screen, so it needs a terminal");
2396
+ let code = 0;
2397
+ for (let round = 0;round < rounds; round++) {
2398
+ const held = [];
2399
+ const { log, info } = console;
2400
+ const write = process20.stdout.write.bind(process20.stdout);
2401
+ const hold = (...parts) => void held.push(`${format(...parts)}
2402
+ `);
2403
+ console.log = hold;
2404
+ console.info = hold;
2405
+ process20.stdout.write = (text) => {
2406
+ held.push(typeof text === "string" ? text : Buffer.from(text).toString());
2407
+ return true;
2408
+ };
2409
+ try {
2410
+ code = await step();
2411
+ } finally {
2412
+ console.log = log;
2413
+ console.info = info;
2414
+ process20.stdout.write = write;
2415
+ }
2416
+ stream.write(`${CLEAR_SCREEN}${held.join("")}`);
2417
+ await sleep(interval);
2418
+ }
2419
+ return code;
2420
+ }
2421
+ // ../kit/src/workspace-root.ts
2422
+ init_user_config();
2423
+ import { homedir as homedir5 } from "os";
2424
+ import { dirname as dirname5, join as join9, resolve as resolve4 } from "path";
2425
+ import process21 from "process";
2426
+ function expandHome(path, home) {
2427
+ if (path === "~")
2428
+ return home;
2429
+ return path.startsWith("~/") ? join9(home, path.slice(2)) : path;
2430
+ }
2431
+ function configured(env, home) {
2432
+ const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
2433
+ return typeof folder === "string" && folder !== "" ? folder : undefined;
2434
+ }
2435
+ function workspaceRoot({ given, env = process21.env, home = homedir5() } = {}) {
2436
+ const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
2437
+ return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join9(home, "Workspace"), home));
1909
2438
  }
2439
+ // src/branch.ts
2440
+ import { basename } from "path";
2441
+ import process25 from "process";
2442
+
2443
+ // ../kit/src/picker.ts
2444
+ init_folders();
2445
+ init_state();
1910
2446
 
1911
2447
  // ../kit/src/picker/terminal.ts
2448
+ init_args();
2449
+ init_job();
2450
+ init_redraw();
2451
+ init_style();
1912
2452
  import { openSync } from "fs";
1913
- import process21 from "process";
2453
+ import process24 from "process";
1914
2454
  import tty from "tty";
1915
2455
 
1916
- // ../kit/src/job.ts
1917
- import process19 from "process";
1918
- function stopJob() {
1919
- process19.kill(0, "SIGTSTP");
1920
- }
1921
-
1922
- // ../kit/src/redraw.ts
1923
- var SYNC_START = "\x1B[?2026h";
1924
- var SYNC_END = "\x1B[?2026l";
1925
- function overwrite(lines, columns) {
1926
- return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1927
- `);
1928
- }
1929
-
1930
2456
  // ../kit/src/picker/preview.ts
1931
- import process20 from "process";
2457
+ import process23 from "process";
1932
2458
 
1933
2459
  // ../kit/src/shell.ts
1934
2460
  var SEPARATORS = new Set([`
@@ -1997,7 +2523,7 @@ async function runPreview(template, line, signal, hidden = []) {
1997
2523
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1998
2524
  const stop = () => {
1999
2525
  try {
2000
- process20.kill(-proc.pid, "SIGKILL");
2526
+ process23.kill(-proc.pid, "SIGKILL");
2001
2527
  } catch {
2002
2528
  proc.kill();
2003
2529
  }
@@ -2022,7 +2548,12 @@ ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe",
2022
2548
  return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
2023
2549
  }
2024
2550
 
2551
+ // ../kit/src/picker/terminal.ts
2552
+ init_state();
2553
+
2025
2554
  // ../kit/src/picker/view.ts
2555
+ init_line();
2556
+ init_state();
2026
2557
  var MIN_HEIGHT = 4;
2027
2558
  var PREVIEW_MIN_COLUMNS = 80;
2028
2559
  var PREVIEW_MIN_ROWS = 10;
@@ -2155,7 +2686,7 @@ function openTerminal() {
2155
2686
  return fail("no terminal to read keys from (/dev/tty)");
2156
2687
  }
2157
2688
  const keys = Bun.file("/dev/tty").stream().getReader();
2158
- const out = process21.stderr;
2689
+ const out = process24.stderr;
2159
2690
  let resize;
2160
2691
  async function read(onChunk) {
2161
2692
  const decoder = new TextDecoder;
@@ -2344,9 +2875,9 @@ async function select(rows, settings, terminal = openTerminal()) {
2344
2875
  const ended = new Promise((resolve) => {
2345
2876
  finish = resolve;
2346
2877
  });
2347
- process21.once("exit", restore);
2878
+ process24.once("exit", restore);
2348
2879
  for (const signal of SIGNALS2)
2349
- process21.once(signal, stop);
2880
+ process24.once(signal, stop);
2350
2881
  try {
2351
2882
  terminal.write(`${PASTE_ON}${MOUSE_ON}`);
2352
2883
  terminal.listen(onChunk, () => draw(true));
@@ -2359,8 +2890,8 @@ async function select(rows, settings, terminal = openTerminal()) {
2359
2890
  await ended;
2360
2891
  } finally {
2361
2892
  for (const signal of SIGNALS2)
2362
- process21.off(signal, stop);
2363
- process21.off("exit", restore);
2893
+ process24.off(signal, stop);
2894
+ process24.off("exit", restore);
2364
2895
  restore();
2365
2896
  }
2366
2897
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -2372,7 +2903,9 @@ async function previewOf(preview, hidden, signal) {
2372
2903
  return [error instanceof Error ? error.message : String(error)];
2373
2904
  }
2374
2905
  }
2906
+
2375
2907
  // ../kit/src/picker.ts
2908
+ init_score();
2376
2909
  function table2(rows) {
2377
2910
  const widths = rows[0]?.cells.map((_, index) => Math.max(...rows.map((row) => Bun.stringWidth(row.cells[index])))) ?? [];
2378
2911
  return rows.map((row) => [
@@ -2407,14 +2940,14 @@ function list(rows) {
2407
2940
  }
2408
2941
 
2409
2942
  // src/branch.ts
2410
- var usage2 = `gb [branch]
2943
+ var usage2 = `gb [branch]: picks a git branch and switches to it
2411
2944
  gb -
2412
2945
  gb -c <name>
2413
2946
  gb -d <branch>
2414
2947
 
2415
- Without a branch, picks one when a terminal is attached: the branches last checked out first, as the reflog has them, then the other local ones, then the remote ones with no local branch yet. The header says where HEAD stands, each row how its branch stands against its upstream and whether it is merged into the base. enter switches to it (a remote one gets its local tracking branch), ctrl-n creates a branch named after the query, ctrl-d deletes the highlighted local branch with \`git branch -d\`, which refuses one not merged yet, and ctrl-r fetches, prunes and lists again. Without a terminal it lists the branches instead.
2416
- \`gb <branch>\` switches without the picker, a bare name finding the remote branch it would create. \`gb -\` goes back to the previous branch, \`gb -c <name>\` creates one and switches to it, \`gb -d <branch>\` deletes a local one.
2417
- A branch checked out in another worktree cannot be switched to: gb prints that worktree's path on stdout and a hint on stderr, since a command cannot change its parent shell's folder.`;
2948
+ Without a branch, on a terminal, picks one: the recently checked out first, then the other local ones, then the remote ones with no local branch yet (enter switches, ctrl-n creates, ctrl-d deletes a merged local branch with \`git branch -d\`, ctrl-r fetches and prunes); without a terminal it lists them.
2949
+ \`gb <branch>\` switches without the picker, \`gb -\` goes back to the previous branch, \`gb -c <name>\` creates one and switches to it, \`gb -d <branch>\` deletes a local one.
2950
+ A branch checked out in another worktree cannot be switched to: gb prints that worktree's path, since a command cannot change its shell's folder.`;
2418
2951
  var EXITS = [[0, "it switched, created, deleted or listed"], ["git", "the code of the git command it ran, when that failed"], [1, "there is no branch by that name or nothing was picked"], [2, "outside a git repository or a usage error"]];
2419
2952
  var options = {
2420
2953
  create: { type: "boolean", short: "c", description: "create the branch named by the rest of the line and switch to it" },
@@ -2557,7 +3090,7 @@ async function fetched() {
2557
3090
  const success = await proc.exited === 0;
2558
3091
  return header(branches(base()), read(["branch", "--show-current"]), success ? "" : "fetch failed");
2559
3092
  }
2560
- function listed2(all) {
3093
+ function listed3(all) {
2561
3094
  list([
2562
3095
  ...all.map((branch) => ({
2563
3096
  label: branch.name,
@@ -2584,7 +3117,7 @@ async function hidden(flag, rest) {
2584
3117
  return 0;
2585
3118
  }
2586
3119
  if (flag === "--list") {
2587
- listed2(load().all);
3120
+ listed3(load().all);
2588
3121
  return 0;
2589
3122
  }
2590
3123
  if (flag === "--names") {
@@ -2631,7 +3164,7 @@ async function gb(args) {
2631
3164
  if (parsed.values.json === true)
2632
3165
  printJson(all);
2633
3166
  else
2634
- console.log(table2(all.map(row)).map((line) => takesControlCodes(process22.stdout) ? line : Bun.stripANSI(line)).join(`
3167
+ console.log(table2(all.map(row)).map((line) => takesControlCodes(process25.stdout) ? line : Bun.stripANSI(line)).join(`
2635
3168
  `));
2636
3169
  return 0;
2637
3170
  }
@@ -2688,4 +3221,4 @@ async function finish(command, typed, emitting) {
2688
3221
  }
2689
3222
 
2690
3223
  // src/gb.ts
2691
- process23.exitCode = await runMain({ name: "gb", run: gb });
3224
+ process26.exitCode = await runMain({ name: "gb", run: gb });