@kaynooo/cli-check 0.20.0 → 0.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/j-cli.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/j-cli.ts
5
- import process26 from "process";
6
- // ../kit/src/args.ts
7
- import process10 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,15 +139,21 @@ 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";
133
148
  import { homedir } from "os";
134
- import { join as join2 } from "path";
149
+ import { isAbsolute, join as join2 } from "path";
135
150
  import process4 from "process";
151
+ function xdgFolder(value, fallback) {
152
+ return value !== undefined && isAbsolute(value) ? value : fallback;
153
+ }
136
154
  function configBase(where = {}) {
137
155
  const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
138
- return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
156
+ return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
139
157
  }
140
158
  function userConfigPath(bin, where = {}) {
141
159
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
@@ -158,36 +176,18 @@ function readUserConfig(bin, where = {}, legacy = []) {
158
176
  return {};
159
177
  }
160
178
  }
179
+ var init_user_config = () => {};
161
180
 
162
181
  // ../kit/src/theme.ts
163
- var ENDS = new Map;
164
- var DEFAULT = {
165
- 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" },
166
- 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" },
167
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
168
- bins: {},
169
- gradient: ["#c084fc", "#67e8f9"]
170
- };
171
- 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" };
172
- 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" };
173
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
174
- var PRESETS = {
175
- default: {},
176
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
177
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
178
- ascii: { glyphs: ASCII }
179
- };
180
- 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"]);
181
- var HEX = /^#[0-9a-f]{6}$/i;
182
- var CONTROL = /\p{Cc}/u;
183
- var MAX_FILE_BYTES = 64 * 1024;
184
- var SPACES = /\s+/;
182
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
183
+ import { homedir as homedir2 } from "os";
184
+ import { join as join3, resolve as resolve2 } from "path";
185
+ import process5 from "process";
185
186
  function isColorSpec(spec) {
186
187
  if (typeof spec === "number")
187
188
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
188
189
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
189
190
  }
190
- var CUBE = [0, 95, 135, 175, 215, 255];
191
191
  function cubeLevel(channel) {
192
192
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
193
193
  }
@@ -292,7 +292,6 @@ function applyFile(theme, file, where, warn) {
292
292
  function endsWalk(home) {
293
293
  return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
294
294
  }
295
- var warned = new Set;
296
295
  function warnOnce(message) {
297
296
  if (warned.has(message))
298
297
  return;
@@ -329,8 +328,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
329
328
  }
330
329
  return { theme, sources, preset };
331
330
  }
332
- var current;
333
- var currentKey = "";
334
331
  function activeTheme() {
335
332
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
336
333
  if (current === undefined || key !== currentKey) {
@@ -339,9 +336,38 @@ function activeTheme() {
339
336
  }
340
337
  return current;
341
338
  }
339
+ var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
340
+ var init_theme = __esm(() => {
341
+ init_config();
342
+ init_user_config();
343
+ ENDS = new Map;
344
+ DEFAULT = {
345
+ 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" },
346
+ 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" },
347
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
348
+ bins: {},
349
+ gradient: ["#c084fc", "#67e8f9"]
350
+ };
351
+ 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" };
352
+ 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" };
353
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
354
+ PRESETS = {
355
+ default: {},
356
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
357
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
358
+ ascii: { glyphs: ASCII }
359
+ };
360
+ 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"]);
361
+ HEX = /^#[0-9a-f]{6}$/i;
362
+ CONTROL = /\p{Cc}/u;
363
+ MAX_FILE_BYTES = 64 * 1024;
364
+ SPACES = /\s+/;
365
+ CUBE = [0, 95, 135, 175, 215, 255];
366
+ warned = new Set;
367
+ });
342
368
 
343
369
  // ../kit/src/style.ts
344
- var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
370
+ import process6 from "process";
345
371
  function takesControlCodes(stream, env = process6.env) {
346
372
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
347
373
  }
@@ -364,14 +390,6 @@ function role(name, stream, env = process6.env) {
364
390
  const colors = paint(stream, env);
365
391
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
366
392
  }
367
- var STATUS_WORDS = {
368
- passed: ["passed", "success", "succeeded", "ok"],
369
- failed: ["failed", "failure", "error", "errored"],
370
- running: ["running", "in_progress", "started", "holding"],
371
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
372
- skipped: ["skipped", "cancelled", "canceled", "manual"]
373
- };
374
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
375
393
  function header(bin, context, stream, env = process6.env) {
376
394
  if (!takesControlCodes(stream, env))
377
395
  return "";
@@ -382,9 +400,24 @@ function header(bin, context, stream, env = process6.env) {
382
400
  const accent = tinted(typeof spec === "string" && spec.split(" ").includes("bold") ? colors : colors.bold, spec, env);
383
401
  return `${accent(bin)}${context === undefined ? "" : colors.dim(` \u203A ${context}`)}`;
384
402
  }
403
+ var MARK_WORDS, STATUS_WORDS, STATUS_OF;
404
+ var init_style = __esm(() => {
405
+ init_colors();
406
+ init_mode();
407
+ init_theme();
408
+ MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
409
+ STATUS_WORDS = {
410
+ passed: ["passed", "success", "succeeded", "ok"],
411
+ failed: ["failed", "failure", "error", "errored"],
412
+ running: ["running", "in_progress", "started", "holding"],
413
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
414
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
415
+ };
416
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
417
+ });
385
418
 
386
419
  // ../kit/src/format.ts
387
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
420
+ import process7 from "process";
388
421
  function formatSeconds(total) {
389
422
  let rest = Math.max(0, Math.round(total));
390
423
  const amounts = UNITS.map(([unit, size]) => {
@@ -406,10 +439,8 @@ function upTo(text, separator) {
406
439
  return end === -1 ? text : text.slice(0, end);
407
440
  }
408
441
  function truncate(text, width) {
409
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
442
+ return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
410
443
  }
411
- var LINE_BREAKS = /\s*\n\s*/g;
412
- var ESCAPE = String.fromCharCode(27);
413
444
  function textWidth(text) {
414
445
  return Bun.stringWidth(text);
415
446
  }
@@ -458,14 +489,40 @@ function jsonText(value, replacer, { stream = process7.stdout, env = process7.en
458
489
  function printJson(value) {
459
490
  console.log(jsonText(value));
460
491
  }
492
+ var UNITS, LINE_BREAKS, ESCAPE;
493
+ var init_format = __esm(() => {
494
+ init_text();
495
+ init_mode();
496
+ init_style();
497
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
498
+ LINE_BREAKS = /\s*\n\s*/g;
499
+ ESCAPE = String.fromCharCode(27);
500
+ });
461
501
 
462
502
  // ../kit/src/help.ts
463
503
  import process8 from "process";
464
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
465
- var USAGE_PREFIX = /^usage:\s*/i;
466
- var FULL_STOP = /\.$/;
467
504
  function usageLine(usage, colors = paint(process8.stdout)) {
468
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
505
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
506
+ `);
507
+ const blank = lines.indexOf("");
508
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
509
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
510
+ const colon = synopses[0].indexOf(": ");
511
+ const inline = synopses[0].slice(colon + 2);
512
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
513
+ if (colon !== -1)
514
+ synopses[0] = synopses[0].slice(0, colon);
515
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
516
+ `)}`;
517
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
518
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
519
+ return [head, ...lead, ...rest].join(`
520
+ `);
521
+ }
522
+ function prose(line, colors) {
523
+ if (colors.cyan("x") === "x")
524
+ return line;
525
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
469
526
  }
470
527
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
471
528
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -500,7 +557,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
500
557
  return [];
501
558
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
502
559
  }
503
- var MAX_INLINE_CHOICES = 24;
504
560
  function optionRows(options, colors = paint(process8.stdout)) {
505
561
  const rows = Object.entries(options).map(([name, option]) => {
506
562
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -515,9 +571,17 @@ function optionRows(options, colors = paint(process8.stdout)) {
515
571
  const width = Math.max(0, ...rows.map((row) => row.width));
516
572
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
517
573
  }
574
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
575
+ var init_help = __esm(() => {
576
+ init_mode();
577
+ init_style();
578
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
579
+ USAGE_PREFIX = /^usage:\s*/i;
580
+ FULL_STOP = /\.$/;
581
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
582
+ });
518
583
 
519
584
  // ../kit/src/text.ts
520
- var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
521
585
  function stripAnsi(text) {
522
586
  return text.replace(ANSI, "");
523
587
  }
@@ -546,10 +610,13 @@ function closest(name, names) {
546
610
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
547
611
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
548
612
  }
613
+ var ANSI;
614
+ var init_text2 = __esm(() => {
615
+ ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
616
+ });
617
+
549
618
  // ../kit/src/input.ts
550
619
  import process9 from "process";
551
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
552
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
553
620
  function duration(value, name, fallback, unit = "s") {
554
621
  if (value === undefined)
555
622
  return fallback;
@@ -570,40 +637,26 @@ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
570
637
  fail(`no file ${path}`);
571
638
  return file.text();
572
639
  }
640
+ var DURATION, UNIT_MS;
641
+ var init_input = __esm(() => {
642
+ init_args();
643
+ DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
644
+ UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
645
+ });
573
646
 
574
647
  // ../kit/src/args.ts
575
- var DASHES = /^-+/;
648
+ import process10 from "process";
649
+ import { parseArgs } from "util";
576
650
  function jsonOption(holds) {
577
651
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
578
652
  }
579
- class Exit extends Error {
580
- code;
581
- hint;
582
- constructor(message, code, hint) {
583
- super(message);
584
- this.code = code;
585
- this.hint = hint;
586
- }
587
- }
588
653
  function fail(message, code = 2, hint) {
589
654
  throw new Exit(message, code, hint);
590
655
  }
591
-
592
- class UsageError extends Exit {
593
- constructor(message, hint) {
594
- super(message, 2, hint);
595
- }
596
- }
597
656
  function badUsage(message) {
598
657
  throw new UsageError(message);
599
658
  }
600
659
 
601
- class HelpShown extends Exit {
602
- constructor() {
603
- super("help shown", 0);
604
- }
605
- }
606
-
607
660
  class Completing {
608
661
  options;
609
662
  positionals;
@@ -614,11 +667,6 @@ class Completing {
614
667
  this.candidates = candidates;
615
668
  }
616
669
  }
617
- var completion = { active: false };
618
- var OUTPUT_OPTIONS = {
619
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
620
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
621
- };
622
670
  function applyOutput(color, plain, env = process10.env) {
623
671
  const when = plain === true ? "never" : color ?? "auto";
624
672
  if (when === "auto")
@@ -772,7 +820,6 @@ function parseError(error) {
772
820
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
773
821
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
774
822
  }
775
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
776
823
  function nearestOption(message, options, allowNegative) {
777
824
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
778
825
  if (typed === undefined)
@@ -788,1008 +835,1488 @@ function nearestOption(message, options, allowNegative) {
788
835
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
789
836
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
790
837
  }
791
- // ../kit/src/argv.ts
792
- import { readFileSync as readFileSync3, realpathSync } from "fs";
793
- import { resolve as resolve3 } from "path";
794
- import process11 from "process";
795
- function commandLine() {
796
- try {
797
- return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
798
- } catch {
799
- return;
800
- }
801
- }
802
- function realPath(word) {
803
- try {
804
- return realpathSync(resolve3(word));
805
- } catch {
806
- return;
807
- }
808
- }
809
- function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
810
- const target = script === undefined ? undefined : realPath(script) ?? script;
811
- const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
812
- const after = at === -1 ? [] : cmdline.slice(at + 1);
813
- return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
814
- }
815
- // ../kit/src/process.ts
816
- import { constants } from "os";
817
- import process12 from "process";
818
- var KILL_GRACE_MS = 2000;
819
- var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
820
- function exitCodeOf(code, signal) {
821
- if (code !== null)
822
- return code;
823
- if (typeof signal === "number")
824
- return 128 + signal;
825
- return signal === null ? 129 : 128 + constants.signals[signal];
826
- }
827
- function holdSignals(cleanup) {
828
- let received;
829
- let child;
830
- const held = {
831
- get signal() {
832
- return received;
833
- },
834
- forward: (to) => {
835
- child = to;
836
- },
837
- release: () => {
838
- for (const signal of SIGNALS)
839
- process12.off(signal, onSignal);
838
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
839
+ var init_args = __esm(() => {
840
+ init_format();
841
+ init_help();
842
+ init_text2();
843
+ init_help();
844
+ init_input();
845
+ DASHES = /^-+/;
846
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
847
+ Exit = class Exit extends Error {
848
+ code;
849
+ hint;
850
+ [EXIT] = true;
851
+ constructor(message, code, hint) {
852
+ super(message);
853
+ this.code = code;
854
+ this.hint = hint;
840
855
  }
841
- };
842
- function onSignal(signal) {
843
- received = signal;
844
- if (child !== undefined) {
845
- child.kill(signal);
846
- return;
856
+ static [Symbol.hasInstance](value) {
857
+ if (this !== Exit)
858
+ return Function.prototype[Symbol.hasInstance].call(this, value);
859
+ return typeof value === "object" && value !== null && value[EXIT] === true;
847
860
  }
848
- if (cleanup === undefined)
849
- return;
850
- held.release();
851
- cleanup(signal);
852
- process12.kill(process12.pid, signal);
853
- }
854
- for (const signal of SIGNALS)
855
- process12.on(signal, onSignal);
856
- return held;
857
- }
858
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
859
- const chunks = [];
860
- const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
861
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
862
- const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
863
- const timers = [];
864
- const killGroup = (killing) => {
865
- if (state.done)
866
- return;
867
- try {
868
- if (grouped)
869
- process12.kill(-proc.pid, killing);
870
- else
871
- proc.kill(killing);
872
- } catch {}
873
- };
874
- const stop = () => {
875
- killGroup("SIGTERM");
876
- timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
877
861
  };
878
- const onAbort = () => stop();
879
- if (timeoutMs !== undefined) {
880
- timers.push(setTimeout(() => {
881
- state.timedOut = true;
882
- stop();
883
- }, timeoutMs));
884
- }
885
- if (signal?.aborted === true)
886
- onAbort();
887
- else
888
- signal?.addEventListener("abort", onAbort, { once: true });
889
- onStart?.({ kill: (killing) => killGroup(killing) });
890
- const drain = async (stream, name) => {
891
- for await (const data of stream) {
892
- if (state.failure !== undefined)
893
- continue;
894
- try {
895
- onChunk?.({ stream: name, data });
896
- } catch (error) {
897
- state.failure = error;
898
- stop();
899
- continue;
900
- }
901
- if (state.kept + data.length > maxBytes) {
902
- state.truncated = true;
903
- continue;
904
- }
905
- state.kept += data.length;
906
- chunks.push({ stream: name, data });
862
+ UsageError = class UsageError extends Exit {
863
+ constructor(message, hint) {
864
+ super(message, 2, hint);
907
865
  }
908
866
  };
909
- try {
910
- await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
911
- await proc.exited;
912
- } finally {
913
- state.done = true;
914
- for (const timer of timers)
915
- clearTimeout(timer);
916
- signal?.removeEventListener("abort", onAbort);
917
- }
918
- if (state.failure !== undefined)
919
- throw state.failure;
920
- const joined = () => Buffer.concat(chunks.map(({ data }) => data));
921
- let output;
922
- let text;
923
- return {
924
- code: exitCodeOf(proc.exitCode, proc.signalCode),
925
- chunks,
926
- timedOut: state.timedOut,
927
- truncated: state.truncated,
928
- get output() {
929
- return output ??= joined();
930
- },
931
- get text() {
932
- return text ??= (output ??= joined()).toString();
867
+ HelpShown = class HelpShown extends Exit {
868
+ constructor() {
869
+ super("help shown", 0);
933
870
  }
934
871
  };
935
- }
936
-
937
- // ../kit/src/progress.ts
938
- var ESC = String.fromCharCode(27);
939
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
940
- var RESET_STYLE = `${ESC}[0m`;
941
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
942
- // ../kit/src/cli.ts
943
- import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
944
- import { dirname as dirname3, join as join6 } from "path";
945
- import process16 from "process";
872
+ completion = { active: false };
873
+ OUTPUT_OPTIONS = {
874
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
875
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
876
+ };
877
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
878
+ });
946
879
 
947
- // ../kit/src/notify.ts
948
- import process13 from "process";
949
- var NOTIFY_AFTER_MS = 1e4;
950
- var CANCELLED = 130;
951
- function base64(text) {
952
- return Buffer.from(text).toString("base64");
953
- }
954
- function notification(title, body, env = process13.env) {
955
- const id = `kit${process13.pid}`;
956
- 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\\`];
957
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
880
+ // ../kit/src/folders.ts
881
+ import { homedir as homedir5 } from "os";
882
+ import { join as join7 } from "path";
883
+ import process18 from "process";
884
+ function ignoredFolders(extra = [], where = {}) {
885
+ const configured = readUserConfig("config", where).ignore;
886
+ const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
887
+ return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
958
888
  }
959
- function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
960
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
961
- return;
962
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
889
+ function cacheFolder({ home = homedir5(), env = process18.env } = {}) {
890
+ return xdgFolder(env.XDG_CACHE_HOME, join7(home, ".cache"));
963
891
  }
892
+ var SKIPPED_FOLDERS;
893
+ var init_folders = __esm(() => {
894
+ init_user_config();
895
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
896
+ });
964
897
 
965
- // ../kit/src/usage.ts
966
- import { appendFileSync, mkdirSync } from "fs";
967
- import { homedir as homedir4 } from "os";
968
- import { dirname as dirname2, isAbsolute, join as join5 } from "path";
969
- import process15 from "process";
970
-
971
- // ../kit/src/logs.ts
972
- import { lstatSync, openSync } from "fs";
973
- import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
974
- import { homedir as homedir3, tmpdir } from "os";
975
- import { join as join4 } from "path";
976
- import process14 from "process";
977
- var DAY_MS = 24 * 60 * 60 * 1000;
978
- var CLI_FOLDER = "kaynooo-cli";
979
- function isPrivateDirectory(path) {
980
- try {
981
- const info = lstatSync(path, { throwIfNoEntry: false });
982
- return info !== undefined && info.isDirectory() && info.uid === (process14.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
983
- } catch {
984
- return false;
985
- }
898
+ // ../kit/src/picker/line.ts
899
+ function isEditKey(key) {
900
+ return EDIT_KEYS.has(key);
986
901
  }
987
- async function privateLogDirectory(name, env = process14.env) {
988
- const runtime = env.XDG_RUNTIME_DIR;
989
- const base = runtime === undefined || runtime === "" ? join4(homedir3(), ".cache", CLI_FOLDER) : join4(runtime, CLI_FOLDER);
990
- const path = join4(base, name);
991
- try {
992
- await mkdir(path, { recursive: true, mode: 448 });
993
- if (isPrivateDirectory(path))
994
- return path;
995
- } catch {}
996
- return mkdtemp(join4(tmpdir(), `${name.replaceAll("/", "-")}-`));
902
+ function endsKills(key) {
903
+ return typeof key !== "object" && !isEditKey(key);
997
904
  }
998
- async function sweepLogs(dir, maxAgeMs = DAY_MS, now = Date.now()) {
999
- let names;
1000
- try {
1001
- names = await readdir(dir);
1002
- } catch {
1003
- return;
1004
- }
1005
- for (const name of names) {
1006
- const path = join4(dir, name);
1007
- try {
1008
- const info = await stat(path);
1009
- if (info.isDirectory())
1010
- await sweepLogs(path, maxAgeMs, now);
1011
- if (now - info.mtimeMs > maxAgeMs)
1012
- await rm(path, { force: true, recursive: info.isDirectory() });
1013
- } catch {
1014
- continue;
1015
- }
1016
- }
905
+ function isWord(char) {
906
+ return char !== undefined && WORD_CHARACTER.test(char);
1017
907
  }
1018
-
1019
- // ../kit/src/usage.ts
1020
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1021
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1022
- var LONGEST_NAME = 40;
1023
- var usageError;
1024
- function noteUsageError(message) {
1025
- usageError = message;
908
+ function wordStart(chars, from) {
909
+ let at = from;
910
+ while (at > 0 && !isWord(chars[at - 1]))
911
+ at--;
912
+ while (at > 0 && isWord(chars[at - 1]))
913
+ at--;
914
+ return at;
1026
915
  }
1027
- function stateHome(env = process15.env) {
1028
- const dir = env.XDG_STATE_HOME;
1029
- return dir !== undefined && isAbsolute(dir) ? dir : join5(homedir4(), ".local", "state");
916
+ function wordEnd(chars, from) {
917
+ let at = from;
918
+ while (at < chars.length && !isWord(chars[at]))
919
+ at++;
920
+ while (at < chars.length && isWord(chars[at]))
921
+ at++;
922
+ return at;
1030
923
  }
1031
- function usagePath(env = process15.env) {
1032
- return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
924
+ function spacedStart(chars, from) {
925
+ let at = from;
926
+ while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
927
+ at--;
928
+ while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
929
+ at--;
930
+ return at;
1033
931
  }
1034
- function usageRecorded(env = process15.env) {
1035
- const off = env.KAYNOOO_CLI_NO_USAGE;
1036
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
932
+ function cut2(chars, from, to) {
933
+ return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
1037
934
  }
1038
- function flagNames(argv) {
1039
- const end = argv.indexOf("--");
1040
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1041
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
935
+ function insert(chars, at, text) {
936
+ const typed = [...text];
937
+ return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
1042
938
  }
1043
- function usageEntry(bin, command, argv, code, now = new Date) {
1044
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1045
- usageError = undefined;
1046
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
939
+ function editLine(line, key) {
940
+ const { killed = "", chained = false } = line;
941
+ const chars = [...line.text];
942
+ const at = Math.min(Math.max(line.caret, 0), chars.length);
943
+ const edited = edit(chars, at, key, killed);
944
+ if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
945
+ return line.killed === undefined ? edited : { ...edited, killed };
946
+ const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
947
+ if (taken === "")
948
+ return { ...edited, killed, chained };
949
+ if (!chained)
950
+ return { ...edited, killed: taken, chained: true };
951
+ return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
1047
952
  }
1048
- function recordUsage(entry, env = process15.env) {
1049
- if (!usageRecorded(env))
1050
- return;
1051
- try {
1052
- const path = usagePath(env);
1053
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1054
- appendFileSync(path, `${JSON.stringify(entry)}
1055
- `, { mode: 384 });
1056
- } catch {}
953
+ function edit(chars, at, key, killed) {
954
+ const text = chars.join("");
955
+ if (typeof key === "object")
956
+ return insert(chars, at, key.text);
957
+ switch (key) {
958
+ case "left":
959
+ return { text, caret: Math.max(at - 1, 0) };
960
+ case "right":
961
+ return { text, caret: Math.min(at + 1, chars.length) };
962
+ case "wordleft":
963
+ return { text, caret: wordStart(chars, at) };
964
+ case "wordright":
965
+ return { text, caret: wordEnd(chars, at) };
966
+ case "linestart":
967
+ return { text, caret: 0 };
968
+ case "lineend":
969
+ return { text, caret: chars.length };
970
+ case "erase":
971
+ return cut2(chars, Math.max(at - 1, 0), at);
972
+ case "delete":
973
+ return cut2(chars, at, Math.min(at + 1, chars.length));
974
+ case "word":
975
+ return cut2(chars, spacedStart(chars, at), at);
976
+ case "killword":
977
+ return cut2(chars, wordStart(chars, at), at);
978
+ case "killnext":
979
+ return cut2(chars, at, wordEnd(chars, at));
980
+ case "clear":
981
+ return cut2(chars, 0, at);
982
+ case "killend":
983
+ return cut2(chars, at, chars.length);
984
+ case "yank":
985
+ return insert(chars, at, killed);
986
+ }
987
+ }
988
+ function visible({ text, caret }, room) {
989
+ const chars = [...text];
990
+ const at = Math.min(Math.max(caret, 0), chars.length);
991
+ const cells = at === chars.length ? [...chars, " "] : chars;
992
+ const widths = cells.map((char) => Bun.stringWidth(char));
993
+ const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
994
+ const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
995
+ let start = at;
996
+ let end = at + 1;
997
+ while (start > 0 && fits(start - 1, end))
998
+ start--;
999
+ while (end < cells.length && fits(start, end + 1))
1000
+ end++;
1001
+ const left = start > 0 ? "\u2026" : "";
1002
+ const right = end < cells.length ? "\u2026" : "";
1003
+ 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) };
1057
1004
  }
1005
+ var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS, WORD_CHARACTER, SPACE;
1006
+ var init_line = __esm(() => {
1007
+ EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
1008
+ BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
1009
+ FORWARD_KILLS = new Set(["killnext", "killend"]);
1010
+ WORD_CHARACTER = /[\p{L}\p{N}_]/u;
1011
+ SPACE = /\s/;
1012
+ });
1058
1013
 
1059
- // ../kit/src/cli.ts
1060
- var LEVEL_OPTIONS = {
1061
- ...OUTPUT_OPTIONS,
1062
- help: { type: "boolean", short: "h", description: "show this help" }
1063
- };
1064
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1065
- function printError(prefix, message, hint, cause) {
1066
- const colors = paint(process16.stderr);
1067
- const styled = takesControlCodes(process16.stderr);
1068
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1069
- const under = (label, text, tint) => text === undefined ? "" : `
1070
- ${styled ? tint(label) : `${label}:`} ${text}`;
1071
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1014
+ // ../kit/src/picker/score.ts
1015
+ function startsWord(text, index) {
1016
+ if (index === 0)
1017
+ return true;
1018
+ const before = text[index - 1];
1019
+ return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
1072
1020
  }
1073
- function printJsonError(message, hint, cause) {
1074
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1021
+ function fuzzy(query, text) {
1022
+ if (query === "")
1023
+ return { score: 0, positions: [] };
1024
+ const exact = query !== query.toLowerCase();
1025
+ const needle = exact ? query : query.toLowerCase();
1026
+ const haystack = exact ? text : text.toLowerCase();
1027
+ if (haystack.length !== text.length || needle.length > haystack.length)
1028
+ return;
1029
+ const width = haystack.length;
1030
+ const best = Array.from({ length: needle.length }, () => new Array(width).fill(NONE));
1031
+ const from = Array.from({ length: needle.length }, () => new Array(width).fill(-1));
1032
+ for (let j = 0;j < needle.length; j++) {
1033
+ let run = NONE;
1034
+ let runAt = -1;
1035
+ for (let i = j;i < width; i++) {
1036
+ if (j > 0 && i - 2 >= j - 1) {
1037
+ const candidate = best[j - 1][i - 2] + (i - 2) * GAP;
1038
+ if (candidate > run) {
1039
+ run = candidate;
1040
+ runAt = i - 2;
1041
+ }
1042
+ }
1043
+ if (haystack[i] !== needle[j])
1044
+ continue;
1045
+ const here = MATCH + (startsWord(text, i) ? BOUNDARY2 : 0) + (i === 0 ? PREFIX : 0);
1046
+ if (j === 0) {
1047
+ best[0][i] = here - i * GAP;
1048
+ continue;
1049
+ }
1050
+ const joined = best[j - 1][i - 1] + CONSECUTIVE;
1051
+ const skipped = run - (i - 1) * GAP;
1052
+ if (joined > NONE && joined >= skipped) {
1053
+ best[j][i] = joined + here;
1054
+ from[j][i] = i - 1;
1055
+ } else if (skipped > NONE) {
1056
+ best[j][i] = skipped + here;
1057
+ from[j][i] = runAt;
1058
+ }
1059
+ }
1060
+ }
1061
+ const last = best[needle.length - 1];
1062
+ let end = -1;
1063
+ for (let i = 0;i < width; i++) {
1064
+ if (last[i] > NONE && (end === -1 || last[i] > last[end]))
1065
+ end = i;
1066
+ }
1067
+ if (end === -1)
1068
+ return;
1069
+ const positions = [];
1070
+ for (let j = needle.length - 1, i = end;j >= 0; j--) {
1071
+ positions.unshift(i);
1072
+ i = from[j][i];
1073
+ }
1074
+ return { score: last[end], positions };
1075
1075
  }
1076
- function wantsJson(argv) {
1077
- const end = argv.indexOf("--");
1078
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1076
+ function rank(query, lines) {
1077
+ if (query === "")
1078
+ return lines.map((_, index) => ({ index, positions: [] }));
1079
+ const found = [];
1080
+ for (const [index, line] of lines.entries()) {
1081
+ const match = fuzzy(query, line);
1082
+ if (match !== undefined)
1083
+ found.push({ index, positions: match.positions, score: match.score });
1084
+ }
1085
+ return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
1079
1086
  }
1080
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
1081
- if (error instanceof HelpShown)
1082
- return 0;
1083
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1084
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1085
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1086
- if (error instanceof Exit && error.code === 2)
1087
- noteUsageError(error.message);
1088
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1089
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1090
- return error instanceof Exit ? error.code : 1;
1087
+ var MATCH = 16, CONSECUTIVE = 12, BOUNDARY2 = 10, PREFIX = 8, GAP = 1, BOUNDARY_AFTER, UPPER, LOWER, NONE;
1088
+ var init_score = __esm(() => {
1089
+ BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1090
+ UPPER = /\p{Lu}/u;
1091
+ LOWER = /\p{Ll}/u;
1092
+ NONE = Number.NEGATIVE_INFINITY;
1093
+ });
1094
+
1095
+ // ../kit/src/picker/state.ts
1096
+ function repeat(value, count) {
1097
+ return Array.from({ length: count }).fill(value);
1091
1098
  }
1092
- var COMPLETE = "__complete";
1093
- var FILES = "__files__";
1094
- async function completingOf(run) {
1095
- completion.active = true;
1096
- try {
1097
- await run([]);
1098
- } catch (error) {
1099
- if (error instanceof Completing)
1100
- return error;
1101
- } finally {
1102
- completion.active = false;
1099
+ function styled(line) {
1100
+ let text = "";
1101
+ const styles = [];
1102
+ let active = "";
1103
+ let colored = false;
1104
+ let last = 0;
1105
+ function add(chunk) {
1106
+ const flat = chunk.replace(CONTROL2, " ");
1107
+ text += flat;
1108
+ colored ||= active !== "" && flat !== "";
1109
+ styles.push(...repeat(active, flat.length));
1103
1110
  }
1104
- return new Completing({});
1105
- }
1106
- function candidateLine(candidate) {
1107
- return typeof candidate === "string" ? candidate : candidate.join("\t");
1111
+ for (const found of line.matchAll(ANSI)) {
1112
+ add(line.slice(last, found.index));
1113
+ last = found.index + found[0].length;
1114
+ if (SGR.test(found[0]))
1115
+ active = RESET.test(found[0]) ? "" : active + found[0];
1116
+ }
1117
+ add(line.slice(last));
1118
+ return { text, styles: colored ? styles : undefined };
1108
1119
  }
1109
- function positionalBeingTyped(before, { options, positionals }) {
1110
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1111
- const typed = [];
1112
- let at = 0;
1113
- while (at < before.length) {
1114
- const word = before[at];
1115
- if (word === "--") {
1116
- typed.push(...before.slice(at + 1));
1117
- break;
1120
+ function lay(rows, searched) {
1121
+ const parsed = rows.map((row) => row.cells.map(styled));
1122
+ const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
1123
+ return parsed.map((cells, at) => {
1124
+ let text = "";
1125
+ const styles = [];
1126
+ let colored = false;
1127
+ let searchEnd = 0;
1128
+ for (const [column, cell] of cells.entries()) {
1129
+ const last = column === cells.length - 1;
1130
+ const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
1131
+ text += shown;
1132
+ colored ||= cell.styles !== undefined;
1133
+ styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
1134
+ if (column < searched)
1135
+ searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
1136
+ if (!last) {
1137
+ const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
1138
+ text += " ".repeat(pad);
1139
+ styles.push(...repeat("", pad));
1140
+ }
1118
1141
  }
1119
- if (!word.startsWith("-"))
1120
- typed.push(word);
1121
- else if (takesValue(word))
1122
- at++;
1123
- at++;
1124
- }
1125
- const last = positionals.at(-1);
1126
- if (typed.length < positionals.length)
1127
- return { name: positionals[typed.length], typed };
1128
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1142
+ return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
1143
+ });
1129
1144
  }
1130
- async function leafCandidates(run, words) {
1131
- const completing = await completingOf(run);
1132
- if ((words.at(-1) ?? "").startsWith("-"))
1133
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1134
- const flag = words.at(-2);
1135
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1136
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1137
- if (option?.type === "string") {
1138
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1139
- return values === undefined ? [FILES] : values.map(candidateLine);
1140
- }
1141
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1142
- return values === undefined ? [FILES] : values.map(candidateLine);
1145
+ function parseKeys(input, paste = { active: false }, ctrls = []) {
1146
+ const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1147
+ return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1148
+ const wheel = MOUSE.exec(sequence)?.[1];
1149
+ if (wheel !== undefined)
1150
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1151
+ const named = codes.get(sequence);
1152
+ const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1153
+ if (sequence === PASTE_START || sequence === PASTE_END) {
1154
+ paste.active = sequence === PASTE_START;
1155
+ return [];
1156
+ }
1157
+ if (paste.active && (sequence === "\r" || sequence === `
1158
+ `))
1159
+ return [];
1160
+ if (key !== undefined)
1161
+ return [key];
1162
+ return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1163
+ });
1143
1164
  }
1144
- async function printCandidates(found) {
1145
- for (const line of await found)
1146
- console.log(line);
1147
- return 0;
1165
+ function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1166
+ 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 };
1167
+ return withRows(state, rows);
1148
1168
  }
1149
- function packageVersion(entry = Bun.main) {
1150
- let resolved = entry;
1151
- try {
1152
- resolved = realpathSync2(entry);
1153
- } catch {}
1154
- for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1155
- try {
1156
- const { version } = JSON.parse(readFileSync4(join6(dir, "package.json"), "utf8"));
1157
- if (typeof version === "string")
1158
- return version;
1159
- } catch {}
1160
- if (dirname3(dir) === dir)
1161
- return "0.0.0";
1162
- }
1169
+ function withRows(state, rows, header = state.header) {
1170
+ const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1171
+ const laid = lay(cells, state.searched);
1172
+ const searchable = laid.map((row) => row.searchable);
1173
+ const matches = rank(state.query, searchable);
1174
+ 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 };
1163
1175
  }
1164
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1165
- if (argv[0] === COMPLETE)
1166
- return printCandidates(leafCandidates(run, argv.slice(1)));
1167
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1168
- console.log(version ?? packageVersion());
1169
- return 0;
1170
- }
1171
- let code;
1172
- const started = performance.now();
1173
- try {
1174
- code = await run(argv);
1175
- } catch (error) {
1176
- code = reportThrown(name, error, redact, wantsJson(argv));
1176
+ function withQuery(state, key) {
1177
+ const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1178
+ return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1179
+ }
1180
+ function move(state, by) {
1181
+ return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
1182
+ }
1183
+ function highlighted(state) {
1184
+ return state.matches[state.cursor]?.index;
1185
+ }
1186
+ function press(state, key) {
1187
+ if (state.done !== undefined)
1188
+ return state;
1189
+ if (state.chained && endsKills(key))
1190
+ state = { ...state, chained: false };
1191
+ if (state.help)
1192
+ return { ...state, help: false };
1193
+ if (typeof key === "object") {
1194
+ if ("text" in key)
1195
+ return withQuery(state, key);
1196
+ return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1177
1197
  }
1178
- notifyEnd(name, code, performance.now() - started);
1179
- if (usage !== false) {
1180
- try {
1181
- recordUsage(usageEntry(name, undefined, argv, code));
1182
- } catch {}
1198
+ if (isEditKey(key))
1199
+ return withQuery(state, key);
1200
+ switch (key) {
1201
+ case "up":
1202
+ return move(state, -1);
1203
+ case "down":
1204
+ return move(state, 1);
1205
+ case "pageup":
1206
+ return move(state, -state.page);
1207
+ case "pagedown":
1208
+ return move(state, state.page);
1209
+ case "home":
1210
+ return move(state, -state.matches.length);
1211
+ case "end":
1212
+ return move(state, state.matches.length);
1213
+ case "cancel":
1214
+ return { ...state, done: "cancel" };
1215
+ case "help":
1216
+ return { ...state, help: true };
1217
+ case "suspend":
1218
+ return state;
1219
+ case "enter":
1220
+ return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1221
+ case "tab": {
1222
+ const at = highlighted(state);
1223
+ if (!state.multi || at === undefined)
1224
+ return state;
1225
+ const marked = new Set(state.marked);
1226
+ if (!marked.delete(at))
1227
+ marked.add(at);
1228
+ return move({ ...state, marked }, 1);
1229
+ }
1183
1230
  }
1184
- return code;
1185
1231
  }
1186
- // ../kit/src/excerpt.ts
1187
- var BASH_ECHO = /^\$ /;
1188
- var DURATION2 = / \[[\d.]+m?s\]$/;
1189
- var BOUNDARY = /^(?:\((?:pass|fail|skip|todo)\) |\S+\.test\.[jt]sx?:$)/;
1190
- var BUN_TEST_SUMMARY = /^\s*\d+ (?:pass|fail|skip|todo)$|^Ran \d+ tests?/;
1191
- var BUN_CHECK_BLOCK = /<error file=[\s\S]*?<\/error>/g;
1192
- var BUN_CHECK_SOURCE = /<source>[\s\S]*?<\/source>\n?/g;
1193
- var BUN_CHECK_ATTRIBUTE = /(\w+)="([^"]*)"/g;
1194
- var BUN_CHECK_SUMMARY = /^Found \d+ errors?/;
1195
- var TSC_ERROR = /\berror TS\d+/;
1196
- var TSC_CONTINUATION = /^\s{2,}\S/;
1197
- var TSC_FRAME = /^\s*[~^|]/;
1198
- var TSC_SUMMARY = /^Found \d+ errors?/;
1199
- var ESLINT_PROBLEM = /^\s+\d+:\d+\s+(?:error|warning)\s/;
1200
- var ESLINT_SUMMARY = /^(?:\u2716 )?\d+ problems? \(/;
1201
- var PHPSTAN_TABLE = /^\s*-{3,} -{3,}/;
1202
- var PHPSTAN_NOISE = /^\s*\[OK\]/;
1203
- var PHP_FAILURES = /^(?:There w(?:as|ere) \d+ (?:failure|error|risky|warning)|\s+(?:FAIL|FAILED)\s+\S|In \S+\.php line \d+:$)/;
1204
- var VITEST_FAIL_LINE = /^ FAIL {2}\S/;
1205
- var PLAYWRIGHT_FAIL_LINE = /^ {2}1\) .+:\d+:\d+ \u203A .+ \u2500+$/;
1206
- var CS_FIXER_LINE = /^\s+\d+\) \S.*\.php(?: \(.+\))?$/;
1207
- var CS_FIXER_TOTAL = /^Found \d+ of \d+ files/;
1208
- var MAX_TESTS = 10;
1209
- var MAX_LINES = 100;
1210
- var TAIL = 30;
1211
- var bunTest = (lines) => {
1212
- const seen = new Set;
1213
- const blocks = [];
1214
- for (const [index, line] of lines.entries()) {
1215
- const name = line.replace(DURATION2, "");
1216
- if (!line.startsWith("(fail) ") || seen.has(name))
1217
- continue;
1218
- seen.add(name);
1219
- if (blocks.length < MAX_TESTS)
1220
- blocks.push(lines.slice(lines.findLastIndex((text, at) => at < index && BOUNDARY.test(text)) + 1, index + 1).join(`
1221
- `).trim());
1222
- }
1223
- if (blocks.length === 0)
1224
- return;
1225
- if (seen.size > MAX_TESTS)
1226
- blocks.push(`and ${seen.size - MAX_TESTS} more failed tests`);
1227
- return [...blocks.join(`
1232
+ function chosen(state) {
1233
+ if (state.marked.size > 0)
1234
+ return state.rows.filter((_, index) => state.marked.has(index));
1235
+ const at = highlighted(state);
1236
+ return at === undefined ? [] : [state.rows[at]];
1237
+ }
1238
+ 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;
1239
+ var init_state = __esm(() => {
1240
+ init_text2();
1241
+ init_line();
1242
+ init_score();
1243
+ CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1244
+ IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1245
+ SGR = /^\x1B\[[0-9;]*m$/;
1246
+ RESET = /^\x1B\[0?m$/;
1247
+ KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1248
+ MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1249
+ KEYS = {
1250
+ "\x1B[A": "up",
1251
+ "\x1BOA": "up",
1252
+ "\x10": "up",
1253
+ "\x1B[B": "down",
1254
+ "\x1BOB": "down",
1255
+ "\x0E": "down",
1256
+ "\x1B[5~": "pageup",
1257
+ "\x1B[6~": "pagedown",
1258
+ "\x1B[H": "home",
1259
+ "\x1B[1~": "home",
1260
+ "\x1BOH": "home",
1261
+ "\x1B[F": "end",
1262
+ "\x1B[4~": "end",
1263
+ "\x1BOF": "end",
1264
+ "\r": "enter",
1265
+ "\n": "enter",
1266
+ "\x03": "cancel",
1267
+ "\x1B": "cancel",
1268
+ "\x1B[D": "left",
1269
+ "\x1BOD": "left",
1270
+ "\x1B[C": "right",
1271
+ "\x1BOC": "right",
1272
+ "\x1B[1;5D": "wordleft",
1273
+ "\x1B[1;3D": "wordleft",
1274
+ "\x1Bb": "wordleft",
1275
+ "\x1B[1;5C": "wordright",
1276
+ "\x1B[1;3C": "wordright",
1277
+ "\x1Bf": "wordright",
1278
+ "\x01": "linestart",
1279
+ "\x05": "lineend",
1280
+ "\x7F": "erase",
1281
+ "\x1B[3~": "delete",
1282
+ "\b": "killword",
1283
+ "\x1B\x7F": "killword",
1284
+ "\x1B[3;5~": "killnext",
1285
+ "\x1Bd": "killnext",
1286
+ "\x15": "clear",
1287
+ "\v": "killend",
1288
+ "\x17": "word",
1289
+ "\x19": "yank",
1290
+ "\x1A": "suspend",
1291
+ "\t": "tab",
1292
+ "\x1F": "help",
1293
+ "\x1BOP": "help",
1294
+ "\x1B[11~": "help"
1295
+ };
1296
+ CTRL_KEY = /^ctrl-[abd-gkln-z]$/;
1297
+ });
1228
1298
 
1229
- `).split(`
1230
- `), "", ...lines.filter((line) => BUN_TEST_SUMMARY.test(line)).map((line) => line.trim())];
1231
- };
1232
- var bunCheck = (lines) => {
1233
- const text = lines.join(`
1299
+ // ../kit/src/job.ts
1300
+ import process20 from "process";
1301
+ function stopJob() {
1302
+ process20.kill(0, "SIGTSTP");
1303
+ }
1304
+ var init_job = () => {};
1305
+
1306
+ // ../kit/src/redraw.ts
1307
+ function overwrite(lines, columns) {
1308
+ return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1234
1309
  `);
1235
- const blocks = text.match(BUN_CHECK_BLOCK);
1236
- if (blocks === null)
1237
- return;
1238
- const errors = blocks.map((block) => {
1239
- const { file, line, column, code, message } = bunCheckFields(block);
1240
- return `${file}:${line}:${column} ${code}: ${message}`;
1241
- });
1242
- return [...errors, ...lines.filter((line) => BUN_CHECK_SUMMARY.test(line))];
1243
- };
1244
- function bunCheckFields(block) {
1245
- const attributes = Object.fromEntries([...block.slice(0, block.indexOf(`
1246
- `)).matchAll(BUN_CHECK_ATTRIBUTE)].map((match) => [match[1] ?? "", match[2] ?? ""]));
1247
- return {
1248
- file: attributes.file ?? "",
1249
- line: attributes.line ?? "",
1250
- column: attributes.column ?? "",
1251
- code: attributes.code ?? "",
1252
- message: block.replace(BUN_CHECK_SOURCE, "").split(`
1253
- `).slice(1, -1).join(`
1254
- `).trim()
1255
- };
1256
1310
  }
1257
- var tsc = (lines) => {
1258
- const kept = [];
1259
- let inError = false;
1260
- for (const line of lines) {
1261
- if (TSC_ERROR.test(line)) {
1262
- inError = true;
1263
- kept.push(line);
1264
- } else if (TSC_SUMMARY.test(line)) {
1265
- inError = false;
1266
- kept.push(line);
1267
- } else if (inError && TSC_CONTINUATION.test(line) && !TSC_FRAME.test(line)) {
1268
- kept.push(line);
1269
- } else {
1270
- inError = false;
1271
- }
1272
- }
1273
- return kept.some((line) => TSC_ERROR.test(line)) ? kept : undefined;
1274
- };
1275
- var eslint = (lines) => {
1276
- const kept = [];
1277
- let file = "";
1278
- let shown = "";
1279
- for (const line of lines) {
1280
- if (ESLINT_PROBLEM.test(line)) {
1281
- if (file !== shown) {
1282
- kept.push(file);
1283
- shown = file;
1284
- }
1285
- kept.push(line);
1286
- } else if (ESLINT_SUMMARY.test(line)) {
1287
- kept.push(line);
1288
- } else if (line.trim() !== "") {
1289
- file = line;
1290
- }
1291
- }
1292
- return kept.some((line) => ESLINT_PROBLEM.test(line)) ? kept : undefined;
1293
- };
1294
- var phpstan = (lines) => {
1295
- const start = lines.findIndex((line) => PHPSTAN_TABLE.test(line));
1296
- return start === -1 ? undefined : lines.slice(start).filter((line) => !PHPSTAN_NOISE.test(line));
1297
- };
1298
- var php = (lines) => {
1299
- const start = lines.findIndex((line) => PHP_FAILURES.test(line));
1300
- return start === -1 ? undefined : lines.slice(start);
1301
- };
1302
- var vitest = (lines) => {
1303
- const start = lines.findIndex((line) => VITEST_FAIL_LINE.test(line));
1304
- return start === -1 ? undefined : lines.slice(start);
1305
- };
1306
- var playwright = (lines) => {
1307
- const start = lines.findIndex((line) => PLAYWRIGHT_FAIL_LINE.test(line));
1308
- return start === -1 ? undefined : lines.slice(start);
1309
- };
1310
- var phpCsFixer = (lines) => {
1311
- const files = lines.filter((line) => CS_FIXER_LINE.test(line) || CS_FIXER_TOTAL.test(line));
1312
- return files.some((line) => CS_FIXER_LINE.test(line)) ? files : undefined;
1313
- };
1314
- var PARSERS = [bunTest, bunCheck, tsc, eslint, vitest, playwright, phpCsFixer, phpstan, php];
1315
- function squeeze(lines) {
1316
- const out = [];
1317
- for (const line of lines.map((text) => text.trimEnd())) {
1318
- if (line !== "" || out.at(-1) !== "")
1319
- out.push(line);
1320
- }
1321
- while (out.at(-1) === "")
1322
- out.pop();
1323
- return out;
1324
- }
1325
- function cut(shown) {
1326
- return shown.length > MAX_LINES ? [...shown.slice(0, MAX_LINES), `... ${shown.length - MAX_LINES} more lines`].join(`
1327
- `) : shown.join(`
1328
- `);
1311
+ function rowsTaken(lines, columns) {
1312
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1329
1313
  }
1330
- function recognised(lines, parsers) {
1331
- return parsers.map((parser) => parser(lines)).find((result) => result !== undefined && result.some((line) => line.trim() !== ""));
1314
+ var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
1315
+ var init_redraw = __esm(() => {
1316
+ init_format();
1317
+ });
1318
+
1319
+ // ../kit/src/answers.ts
1320
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync2 } from "fs";
1321
+ import { dirname as dirname5, join as join9 } from "path";
1322
+ function answersFile() {
1323
+ return join9(cacheFolder(), "kaynooo-cli", "answers.json");
1332
1324
  }
1333
- function failureExcerpt(output) {
1334
- const lines = stripAnsi(output).split(`
1335
- `);
1336
- if (BASH_ECHO.test(lines[0] ?? ""))
1337
- lines.shift();
1338
- return cut(squeeze(recognised(lines, PARSERS) ?? lines.slice(-TAIL)));
1325
+ function stored() {
1326
+ try {
1327
+ const parsed = JSON.parse(readFileSync7(answersFile(), "utf-8"));
1328
+ if (typeof parsed !== "object" || parsed === null)
1329
+ return {};
1330
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
1331
+ } catch {
1332
+ return {};
1333
+ }
1339
1334
  }
1340
- var LOG_PATTERNS = { BASH_ECHO, DURATION: DURATION2, BOUNDARY, BUN_TEST_SUMMARY, BUN_CHECK_SUMMARY, TSC_CONTINUATION, TSC_FRAME, TSC_SUMMARY, ESLINT_PROBLEM, ESLINT_SUMMARY };
1341
- // ../kit/src/folders.ts
1342
- import { homedir as homedir5 } from "os";
1343
- import { join as join7 } from "path";
1344
- import process17 from "process";
1345
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1346
- function ignoredFolders(extra = [], where = {}) {
1347
- const configured = readUserConfig("config", where).ignore;
1348
- const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
1349
- return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
1335
+ function earlierAnswers(key) {
1336
+ return stored()[key] ?? [];
1350
1337
  }
1351
- function cacheFolder({ home = homedir5(), env = process17.env } = {}) {
1352
- return env.XDG_CACHE_HOME ?? join7(home, ".cache");
1338
+ function rememberAnswer(key, answer) {
1339
+ const all = stored();
1340
+ const file = answersFile();
1341
+ all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
1342
+ try {
1343
+ mkdirSync3(dirname5(file), { recursive: true });
1344
+ writeFileSync2(file, JSON.stringify(all));
1345
+ } catch {}
1353
1346
  }
1354
- // ../kit/src/secrets.ts
1355
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1356
- // ../kit/src/sessions.ts
1357
- var {Glob } = globalThis.Bun;
1358
- var SESSION_FILES = new Glob("*.json");
1359
- var ACCOUNT_DIRS = new Glob("*/sessions");
1360
- // package.json
1361
- var version = "0.20.0";
1362
-
1363
- // src/j.ts
1364
- import process25 from "process";
1365
-
1366
- // ../kit/src/picker.ts
1367
- import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync } from "fs";
1368
- import { dirname as dirname4, join as join8 } from "path";
1369
- import process22 from "process";
1347
+ var KEPT = 50;
1348
+ var init_answers = __esm(() => {
1349
+ init_folders();
1350
+ });
1370
1351
 
1371
- // ../kit/src/picker/line.ts
1372
- var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
1373
- var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
1374
- var FORWARD_KILLS = new Set(["killnext", "killend"]);
1375
- function isEditKey(key) {
1376
- return EDIT_KEYS.has(key);
1377
- }
1378
- function endsKills(key) {
1379
- return typeof key !== "object" && !isEditKey(key);
1352
+ // ../kit/src/prompt.ts
1353
+ import process24 from "process";
1354
+ function readKeys(input, paste = { active: false }) {
1355
+ return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
1380
1356
  }
1381
- var WORD_CHARACTER = /[\p{L}\p{N}_]/u;
1382
- var SPACE = /\s/;
1383
- function isWord(char) {
1384
- return char !== undefined && WORD_CHARACTER.test(char);
1357
+ function roomAfter(question, columns) {
1358
+ return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
1385
1359
  }
1386
- function wordStart(chars, from) {
1387
- let at = from;
1388
- while (at > 0 && !isWord(chars[at - 1]))
1389
- at--;
1390
- while (at > 0 && isWord(chars[at - 1]))
1391
- at--;
1392
- return at;
1360
+ function withCaret(colors, line, room, dim = false) {
1361
+ const { before, at, after } = visible(line, room);
1362
+ const tone = dim ? colors.dim : (text) => text;
1363
+ return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
1393
1364
  }
1394
- function wordEnd(chars, from) {
1395
- let at = from;
1396
- while (at < chars.length && !isWord(chars[at]))
1397
- at++;
1398
- while (at < chars.length && isWord(chars[at]))
1399
- at++;
1400
- return at;
1365
+ function sharedStart(texts) {
1366
+ const [first = [], ...rest] = texts.map((text) => [...text]);
1367
+ let length = first.length;
1368
+ for (const chars of rest) {
1369
+ const differs = chars.findIndex((char, index) => char !== first[index]);
1370
+ length = Math.min(length, differs === -1 ? chars.length : differs);
1371
+ }
1372
+ return first.slice(0, length).join("");
1401
1373
  }
1402
- function spacedStart(chars, from) {
1403
- let at = from;
1404
- while (at > 0 && SPACE.test(chars[at - 1] ?? ""))
1405
- at--;
1406
- while (at > 0 && !SPACE.test(chars[at - 1] ?? ""))
1407
- at--;
1408
- return at;
1374
+ function listed2(colors, found, columns) {
1375
+ const shared = sharedStart(found);
1376
+ const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
1377
+ const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
1378
+ const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
1379
+ return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
1409
1380
  }
1410
- function cut2(chars, from, to) {
1411
- return { text: [...chars.slice(0, from), ...chars.slice(to)].join(""), caret: from };
1381
+ async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
1382
+ let line = { text: "", caret: 0 };
1383
+ let invalid;
1384
+ let completions = [];
1385
+ const remembered = history === undefined || mask ? undefined : history;
1386
+ const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
1387
+ let recalled = -1;
1388
+ let draft = line;
1389
+ const taken = () => line.text === "" ? fallback ?? "" : line.text;
1390
+ const shown = () => mask ? "*".repeat([...taken()].length) : taken();
1391
+ const accepted = await ask(question, settings, (colors, state, { columns }) => {
1392
+ if (state !== "asking")
1393
+ return [answer(colors, question, state, shown())];
1394
+ const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
1395
+ return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
1396
+ }, (key) => {
1397
+ if (key === "cancel")
1398
+ return "cancel";
1399
+ invalid = undefined;
1400
+ completions = [];
1401
+ if (line.chained === true && endsKills(key))
1402
+ line = { ...line, chained: false };
1403
+ if (key === "tab") {
1404
+ const chars = [...line.text];
1405
+ const before = chars.slice(0, line.caret).join("");
1406
+ const found = complete?.(before) ?? [];
1407
+ const filled = sharedStart(found);
1408
+ if ([...filled].length > [...before].length)
1409
+ line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
1410
+ else
1411
+ completions = found;
1412
+ return;
1413
+ }
1414
+ if (key === "enter") {
1415
+ invalid = validate?.(taken());
1416
+ return invalid === undefined ? "enter" : undefined;
1417
+ }
1418
+ if (key === "up" || key === "down") {
1419
+ const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
1420
+ if (recalled === -1)
1421
+ draft = line;
1422
+ recalled = to;
1423
+ const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
1424
+ line = { ...shown, killed: line.killed ?? "" };
1425
+ return;
1426
+ }
1427
+ const edit = { home: "linestart", end: "lineend" }[key] ?? key;
1428
+ if (typeof edit === "object" || isEditKey(edit))
1429
+ line = editLine(line, edit);
1430
+ return;
1431
+ });
1432
+ if (!accepted)
1433
+ return;
1434
+ if (remembered !== undefined && taken() !== "")
1435
+ rememberAnswer(remembered, taken());
1436
+ return taken();
1412
1437
  }
1413
- function insert(chars, at, text) {
1414
- const typed = [...text];
1415
- return { text: [...chars.slice(0, at), ...typed, ...chars.slice(at)].join(""), caret: at + typed.length };
1438
+ function answer(colors, question, state, picked) {
1439
+ return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
1416
1440
  }
1417
- function editLine(line, key) {
1418
- const { killed = "", chained = false } = line;
1419
- const chars = [...line.text];
1420
- const at = Math.min(Math.max(line.caret, 0), chars.length);
1421
- const edited = edit(chars, at, key, killed);
1422
- if (typeof key === "object" || !BACKWARD_KILLS.has(key) && !FORWARD_KILLS.has(key))
1423
- return line.killed === undefined ? edited : { ...edited, killed };
1424
- const taken = chars.slice(edited.caret, edited.caret + chars.length - [...edited.text].length).join("");
1425
- if (taken === "")
1426
- return { ...edited, killed, chained };
1427
- if (!chained)
1428
- return { ...edited, killed: taken, chained: true };
1429
- return { ...edited, killed: BACKWARD_KILLS.has(key) ? taken + killed : killed + taken, chained: true };
1430
- }
1431
- function edit(chars, at, key, killed) {
1432
- const text = chars.join("");
1433
- if (typeof key === "object")
1434
- return insert(chars, at, key.text);
1435
- switch (key) {
1436
- case "left":
1437
- return { text, caret: Math.max(at - 1, 0) };
1438
- case "right":
1439
- return { text, caret: Math.min(at + 1, chars.length) };
1440
- case "wordleft":
1441
- return { text, caret: wordStart(chars, at) };
1442
- case "wordright":
1443
- return { text, caret: wordEnd(chars, at) };
1444
- case "linestart":
1445
- return { text, caret: 0 };
1446
- case "lineend":
1447
- return { text, caret: chars.length };
1448
- case "erase":
1449
- return cut2(chars, Math.max(at - 1, 0), at);
1450
- case "delete":
1451
- return cut2(chars, at, Math.min(at + 1, chars.length));
1452
- case "word":
1453
- return cut2(chars, spacedStart(chars, at), at);
1454
- case "killword":
1455
- return cut2(chars, wordStart(chars, at), at);
1456
- case "killnext":
1457
- return cut2(chars, at, wordEnd(chars, at));
1458
- case "clear":
1459
- return cut2(chars, 0, at);
1460
- case "killend":
1461
- return cut2(chars, at, chars.length);
1462
- case "yank":
1463
- return insert(chars, at, killed);
1464
- }
1465
- }
1466
- function visible({ text, caret }, room) {
1467
- const chars = [...text];
1468
- const at = Math.min(Math.max(caret, 0), chars.length);
1469
- const cells = at === chars.length ? [...chars, " "] : chars;
1470
- const widths = cells.map((char) => Bun.stringWidth(char));
1471
- const width = (from, to) => widths.slice(from, to).reduce((sum, size) => sum + size, 0);
1472
- const fits = (from, to) => (from > 0 ? 1 : 0) + width(from, to) + (to < cells.length ? 1 : 0) <= room;
1473
- let start = at;
1474
- let end = at + 1;
1475
- while (start > 0 && fits(start - 1, end))
1476
- start--;
1477
- while (end < cells.length && fits(start, end + 1))
1478
- end++;
1479
- const left = start > 0 ? "\u2026" : "";
1480
- const right = end < cells.length ? "\u2026" : "";
1481
- 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) };
1482
- }
1483
-
1484
- // ../kit/src/picker/score.ts
1485
- var MATCH = 16;
1486
- var CONSECUTIVE = 12;
1487
- var BOUNDARY2 = 10;
1488
- var PREFIX = 8;
1489
- var GAP = 1;
1490
- var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
1491
- var UPPER = /\p{Lu}/u;
1492
- var LOWER = /\p{Ll}/u;
1493
- var NONE = Number.NEGATIVE_INFINITY;
1494
- function startsWord(text, index) {
1495
- if (index === 0)
1496
- return true;
1497
- const before = text[index - 1];
1498
- return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
1499
- }
1500
- function fuzzy(query, text) {
1501
- if (query === "")
1502
- return { score: 0, positions: [] };
1503
- const exact = query !== query.toLowerCase();
1504
- const needle = exact ? query : query.toLowerCase();
1505
- const haystack = exact ? text : text.toLowerCase();
1506
- if (haystack.length !== text.length || needle.length > haystack.length)
1507
- return;
1508
- const width = haystack.length;
1509
- const best = Array.from({ length: needle.length }, () => new Array(width).fill(NONE));
1510
- const from = Array.from({ length: needle.length }, () => new Array(width).fill(-1));
1511
- for (let j = 0;j < needle.length; j++) {
1512
- let run = NONE;
1513
- let runAt = -1;
1514
- for (let i = j;i < width; i++) {
1515
- if (j > 0 && i - 2 >= j - 1) {
1516
- const candidate = best[j - 1][i - 2] + (i - 2) * GAP;
1517
- if (candidate > run) {
1518
- run = candidate;
1519
- runAt = i - 2;
1441
+ async function ask(question, { hint, terminal = process24 }, render, press) {
1442
+ const { stdin, stderr } = terminal;
1443
+ if (!isInteractive(terminal))
1444
+ fail(`cannot ask "${question}" off a terminal`, 2, hint);
1445
+ const colors = paint(stderr);
1446
+ let current = "asking";
1447
+ let outcome;
1448
+ const columns = () => stderr.columns || 80;
1449
+ const draw = (state, last = false) => {
1450
+ const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
1451
+ const rows = rowsTaken(frame, columns());
1452
+ stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
1453
+ current = state;
1454
+ };
1455
+ const redraw = () => draw(current);
1456
+ const paste = { active: false };
1457
+ const stop = terminal.stop ?? (terminal === process24 ? stopJob : undefined);
1458
+ const suspend = () => {
1459
+ if (stop === undefined)
1460
+ return;
1461
+ stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
1462
+ stdin.setRawMode(false);
1463
+ stop();
1464
+ stdin.setRawMode(true);
1465
+ stderr.write("\x1B[?25l\x1B[?2004h");
1466
+ };
1467
+ try {
1468
+ stderr.on?.("resize", redraw);
1469
+ stdin.setRawMode(true);
1470
+ stdin.resume();
1471
+ stderr.write("\x1B[?25l\x1B[?2004h");
1472
+ draw("asking");
1473
+ return await new Promise((resolve) => {
1474
+ function onData(data) {
1475
+ for (const key of readKeys(data.toString(), paste)) {
1476
+ if (key === "suspend") {
1477
+ suspend();
1478
+ continue;
1479
+ }
1480
+ const pressed = press(key);
1481
+ if (pressed !== undefined) {
1482
+ settle(pressed);
1483
+ return;
1484
+ }
1520
1485
  }
1486
+ draw("asking");
1521
1487
  }
1522
- if (haystack[i] !== needle[j])
1523
- continue;
1524
- const here = MATCH + (startsWord(text, i) ? BOUNDARY2 : 0) + (i === 0 ? PREFIX : 0);
1525
- if (j === 0) {
1526
- best[0][i] = here - i * GAP;
1527
- continue;
1488
+ function onEnd() {
1489
+ settle("cancel");
1528
1490
  }
1529
- const joined = best[j - 1][i - 1] + CONSECUTIVE;
1530
- const skipped = run - (i - 1) * GAP;
1531
- if (joined > NONE && joined >= skipped) {
1532
- best[j][i] = joined + here;
1533
- from[j][i] = i - 1;
1534
- } else if (skipped > NONE) {
1535
- best[j][i] = skipped + here;
1536
- from[j][i] = runAt;
1491
+ function settle(settled) {
1492
+ outcome = settled;
1493
+ stdin.off("data", onData);
1494
+ stdin.off("end", onEnd);
1495
+ resolve(settled === "enter");
1537
1496
  }
1538
- }
1539
- }
1540
- const last = best[needle.length - 1];
1541
- let end = -1;
1542
- for (let i = 0;i < width; i++) {
1543
- if (last[i] > NONE && (end === -1 || last[i] > last[end]))
1544
- end = i;
1497
+ stdin.on("data", onData);
1498
+ stdin.on("end", onEnd);
1499
+ });
1500
+ } finally {
1501
+ stderr.off?.("resize", redraw);
1502
+ draw(outcome ?? "cancel", true);
1503
+ stderr.write(`
1504
+ \x1B[?25h\x1B[?2004l`);
1505
+ stdin.setRawMode(false);
1506
+ stdin.pause();
1545
1507
  }
1546
- if (end === -1)
1508
+ }
1509
+ var PROMPT_KEYS, MAX_LISTED = 12;
1510
+ var init_prompt = __esm(() => {
1511
+ init_answers();
1512
+ init_args();
1513
+ init_format();
1514
+ init_job();
1515
+ init_mode();
1516
+ init_line();
1517
+ init_state();
1518
+ init_redraw();
1519
+ init_style();
1520
+ PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
1521
+ });
1522
+
1523
+ // src/j-cli.ts
1524
+ import process27 from "process";
1525
+
1526
+ // ../kit/src/index.ts
1527
+ init_args();
1528
+
1529
+ // ../kit/src/argv.ts
1530
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
1531
+ import { resolve as resolve3 } from "path";
1532
+ import process11 from "process";
1533
+ function commandLine() {
1534
+ try {
1535
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
1536
+ } catch {
1547
1537
  return;
1548
- const positions = [];
1549
- for (let j = needle.length - 1, i = end;j >= 0; j--) {
1550
- positions.unshift(i);
1551
- i = from[j][i];
1552
1538
  }
1553
- return { score: last[end], positions };
1554
1539
  }
1555
- function rank(query, lines) {
1556
- if (query === "")
1557
- return lines.map((_, index) => ({ index, positions: [] }));
1558
- const found = [];
1559
- for (const [index, line] of lines.entries()) {
1560
- const match = fuzzy(query, line);
1561
- if (match !== undefined)
1562
- found.push({ index, positions: match.positions, score: match.score });
1540
+ function realPath(word) {
1541
+ try {
1542
+ return realpathSync(resolve3(word));
1543
+ } catch {
1544
+ return;
1563
1545
  }
1564
- return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
1565
1546
  }
1547
+ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
1548
+ const target = script === undefined ? undefined : realPath(script) ?? script;
1549
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
1550
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
1551
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
1552
+ }
1553
+ // ../kit/src/chart.ts
1554
+ init_format();
1555
+ init_mode();
1556
+ init_style();
1557
+ init_theme();
1558
+ // ../kit/src/ci.ts
1559
+ init_args();
1560
+ init_format();
1566
1561
 
1567
- // ../kit/src/picker/state.ts
1568
- var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
1569
- var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
1570
- var SGR = /^\x1B\[[0-9;]*m$/;
1571
- var RESET = /^\x1B\[0?m$/;
1572
- var COLUMN_GAP = 2;
1573
- var PASTE_START = "\x1B[200~";
1574
- var PASTE_END = "\x1B[201~";
1575
- var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
1576
- var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
1577
- var WHEEL_LINES = 3;
1578
- var KEYS = {
1579
- "\x1B[A": "up",
1580
- "\x1BOA": "up",
1581
- "\x10": "up",
1582
- "\x1B[B": "down",
1583
- "\x1BOB": "down",
1584
- "\x0E": "down",
1585
- "\x1B[5~": "pageup",
1586
- "\x1B[6~": "pagedown",
1587
- "\x1B[H": "home",
1588
- "\x1B[1~": "home",
1589
- "\x1BOH": "home",
1590
- "\x1B[F": "end",
1591
- "\x1B[4~": "end",
1592
- "\x1BOF": "end",
1593
- "\r": "enter",
1594
- "\n": "enter",
1595
- "\x03": "cancel",
1596
- "\x1B": "cancel",
1597
- "\x1B[D": "left",
1598
- "\x1BOD": "left",
1599
- "\x1B[C": "right",
1600
- "\x1BOC": "right",
1601
- "\x1B[1;5D": "wordleft",
1602
- "\x1B[1;3D": "wordleft",
1603
- "\x1Bb": "wordleft",
1604
- "\x1B[1;5C": "wordright",
1605
- "\x1B[1;3C": "wordright",
1606
- "\x1Bf": "wordright",
1607
- "\x01": "linestart",
1608
- "\x05": "lineend",
1609
- "\x7F": "erase",
1610
- "\x1B[3~": "delete",
1611
- "\b": "killword",
1612
- "\x1B\x7F": "killword",
1613
- "\x1B[3;5~": "killnext",
1614
- "\x1Bd": "killnext",
1615
- "\x15": "clear",
1616
- "\v": "killend",
1617
- "\x17": "word",
1618
- "\x19": "yank",
1619
- "\x1A": "suspend",
1620
- "\t": "tab",
1621
- "\x1F": "help",
1622
- "\x1BOP": "help",
1623
- "\x1B[11~": "help"
1624
- };
1625
- var CTRL_KEY = /^ctrl-[abd-gkln-z]$/;
1626
- function repeat(value, count) {
1627
- return Array.from({ length: count }).fill(value);
1562
+ // ../kit/src/progress.ts
1563
+ init_format();
1564
+
1565
+ // ../kit/src/process.ts
1566
+ import { readFileSync as readFileSync4 } from "fs";
1567
+ import { constants } from "os";
1568
+ import process12 from "process";
1569
+ var KILL_GRACE_MS = 2000;
1570
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1571
+ var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
1572
+ function exitCodeOf(code, signal) {
1573
+ if (code !== null)
1574
+ return code;
1575
+ if (typeof signal === "number")
1576
+ return 128 + signal;
1577
+ return signal === null ? 129 : 128 + constants.signals[signal];
1628
1578
  }
1629
- function styled(line) {
1630
- let text = "";
1631
- const styles = [];
1632
- let active = "";
1633
- let colored = false;
1634
- let last = 0;
1635
- function add(chunk) {
1636
- const flat = chunk.replace(CONTROL2, " ");
1637
- text += flat;
1638
- colored ||= active !== "" && flat !== "";
1639
- styles.push(...repeat(active, flat.length));
1640
- }
1641
- for (const found of line.matchAll(ANSI)) {
1642
- add(line.slice(last, found.index));
1643
- last = found.index + found[0].length;
1644
- if (SGR.test(found[0]))
1645
- active = RESET.test(found[0]) ? "" : active + found[0];
1579
+ function groupsOf(pid) {
1580
+ try {
1581
+ const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
1582
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
1583
+ return { group: Number(fields[2]), foreground: Number(fields[5]) };
1584
+ } catch {
1585
+ return;
1646
1586
  }
1647
- add(line.slice(last));
1648
- return { text, styles: colored ? styles : undefined };
1649
1587
  }
1650
- function lay(rows, searched) {
1651
- const parsed = rows.map((row) => row.cells.map(styled));
1652
- const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
1653
- return parsed.map((cells, at) => {
1654
- let text = "";
1655
- const styles = [];
1656
- let colored = false;
1657
- let searchEnd = 0;
1658
- for (const [column, cell] of cells.entries()) {
1659
- const last = column === cells.length - 1;
1660
- const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
1661
- text += shown;
1662
- colored ||= cell.styles !== undefined;
1663
- styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
1664
- if (column < searched)
1665
- searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
1666
- if (!last) {
1667
- const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
1668
- text += " ".repeat(pad);
1669
- styles.push(...repeat("", pad));
1670
- }
1588
+ function heardTheTerminal(child) {
1589
+ if (child.pid === undefined)
1590
+ return false;
1591
+ const own = groupsOf("self");
1592
+ return own !== undefined && own.group === own.foreground && groupsOf(child.pid)?.group === own.group;
1593
+ }
1594
+ function holdSignals(cleanup) {
1595
+ let received;
1596
+ let child;
1597
+ const held = {
1598
+ get signal() {
1599
+ return received;
1600
+ },
1601
+ forward: (to) => {
1602
+ child = to;
1603
+ },
1604
+ release: () => {
1605
+ for (const signal of SIGNALS)
1606
+ process12.off(signal, onSignal);
1671
1607
  }
1672
- return { text, styles: colored ? styles : undefined, searchable: rows[at].search ?? text.slice(0, searchEnd) };
1673
- });
1608
+ };
1609
+ function onSignal(signal) {
1610
+ received = signal;
1611
+ if (child !== undefined) {
1612
+ if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
1613
+ child.kill(signal);
1614
+ return;
1615
+ }
1616
+ if (cleanup === undefined)
1617
+ return;
1618
+ held.release();
1619
+ cleanup(signal);
1620
+ process12.kill(process12.pid, signal);
1621
+ }
1622
+ for (const signal of SIGNALS)
1623
+ process12.on(signal, onSignal);
1624
+ return held;
1674
1625
  }
1675
- function parseKeys(input, paste = { active: false }, ctrls = []) {
1676
- const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
1677
- return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1678
- const wheel = MOUSE.exec(sequence)?.[1];
1679
- if (wheel !== undefined)
1680
- return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
1681
- const named = codes.get(sequence);
1682
- const key = named === undefined ? KEYS[sequence] : { ctrl: named };
1683
- if (sequence === PASTE_START || sequence === PASTE_END) {
1684
- paste.active = sequence === PASTE_START;
1685
- return [];
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;
1635
+ try {
1636
+ if (grouped)
1637
+ process12.kill(-proc.pid, killing);
1638
+ else
1639
+ proc.kill(killing);
1640
+ } catch {}
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));
1652
+ }
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.truncated)
1670
+ continue;
1671
+ let kept = data;
1672
+ if (state.kept + data.length > maxBytes) {
1673
+ let cut = maxBytes - state.kept;
1674
+ while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
1675
+ cut--;
1676
+ kept = data.subarray(0, cut);
1677
+ state.truncated = true;
1678
+ }
1679
+ state.kept += kept.length;
1680
+ if (kept.length > 0)
1681
+ chunks.push({ stream: name, data: kept });
1686
1682
  }
1687
- if (paste.active && (sequence === "\r" || sequence === `
1688
- `))
1689
- return [];
1690
- if (key !== undefined)
1691
- return [key];
1692
- return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
1693
- });
1683
+ };
1684
+ try {
1685
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
1686
+ await proc.exited;
1687
+ } finally {
1688
+ state.done = true;
1689
+ for (const timer of timers)
1690
+ clearTimeout(timer);
1691
+ signal?.removeEventListener("abort", onAbort);
1692
+ }
1693
+ if (state.failure !== undefined)
1694
+ throw state.failure;
1695
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
1696
+ let output;
1697
+ let text;
1698
+ let stdout;
1699
+ return {
1700
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
1701
+ chunks,
1702
+ timedOut: state.timedOut,
1703
+ truncated: state.truncated,
1704
+ get output() {
1705
+ return output ??= joined();
1706
+ },
1707
+ get text() {
1708
+ return text ??= (output ??= joined()).toString();
1709
+ },
1710
+ get stdout() {
1711
+ return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
1712
+ }
1713
+ };
1694
1714
  }
1695
- function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1696
- 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 };
1697
- return withRows(state, rows);
1715
+
1716
+ // ../kit/src/progress.ts
1717
+ init_style();
1718
+ init_theme();
1719
+ var ESC = String.fromCharCode(27);
1720
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
1721
+ var RESET_STYLE = `${ESC}[0m`;
1722
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1723
+
1724
+ // ../kit/src/ci.ts
1725
+ init_style();
1726
+
1727
+ // ../kit/src/tool.ts
1728
+ init_format();
1729
+ // ../kit/src/cli.ts
1730
+ init_args();
1731
+ import { readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
1732
+ import { dirname as dirname3, join as join6 } from "path";
1733
+ import process17 from "process";
1734
+
1735
+ // ../kit/src/askpass.ts
1736
+ import process13 from "process";
1737
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1738
+ async function askpassClient(argv) {
1739
+ const socketPath = process13.env[SOCKET_VARIABLE];
1740
+ if (socketPath === undefined)
1741
+ return;
1742
+ const request = { prompt: argv[0] ?? "", ...process13.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1743
+ const { promise, resolve } = Promise.withResolvers();
1744
+ let received = "";
1745
+ try {
1746
+ await Bun.connect({
1747
+ unix: socketPath,
1748
+ socket: {
1749
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
1750
+ `),
1751
+ data: (_, chunk) => {
1752
+ received += chunk.toString();
1753
+ },
1754
+ close: () => resolve(received),
1755
+ error: () => resolve("")
1756
+ }
1757
+ });
1758
+ } catch {
1759
+ return 1;
1760
+ }
1761
+ const reply = await promise;
1762
+ if (reply === "")
1763
+ return 1;
1764
+ const { answer } = JSON.parse(reply);
1765
+ if (request.notice === true)
1766
+ return 0;
1767
+ if (answer === undefined)
1768
+ return 1;
1769
+ process13.stdout.write(`${answer}
1770
+ `);
1771
+ return 0;
1698
1772
  }
1699
- function withRows(state, rows, header = state.header) {
1700
- const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
1701
- const laid = lay(cells, state.searched);
1702
- const searchable = laid.map((row) => row.searchable);
1703
- const matches = rank(state.query, searchable);
1704
- 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 };
1773
+
1774
+ // ../kit/src/completions.ts
1775
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1776
+ 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'
1777
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1778
+ set -l current (commandline -ct)
1779
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1780
+ if test "$line" = __files__
1781
+ __fish_complete_path $current
1782
+ else
1783
+ echo $line
1784
+ end
1785
+ end
1786
+ end`;
1787
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1788
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1789
+ local -a lines
1790
+ COMPREPLY=()
1791
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1792
+ for line in "\${lines[@]}"; do
1793
+ if [[ $line == __files__ ]]; then
1794
+ COMPREPLY+=($(compgen -f -- "$cur"))
1795
+ else
1796
+ words+="\${line%%$'\\t'*}"$'\\n'
1797
+ fi
1798
+ done
1799
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1800
+ }`;
1801
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1802
+ local line
1803
+ local -a described plain
1804
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1805
+ if [[ $line == __files__ ]]; then
1806
+ _files
1807
+ elif [[ $line == *$'\\t'* ]]; then
1808
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1809
+ else
1810
+ plain+=("$line")
1811
+ fi
1812
+ done
1813
+ (( \${#described} )) && _describe -V value described
1814
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1815
+ return 0
1816
+ }`;
1817
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1818
+ if (shell === "fish")
1819
+ return `${header}
1820
+ ${FISH_FUNCTION}
1821
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1822
+ `).join("")}`;
1823
+ if (shell === "bash")
1824
+ return `${header}
1825
+ ${BASH_FUNCTION}
1826
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1827
+ `;
1828
+ return `${header}
1829
+ ${ZSH_FUNCTION}
1830
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1831
+ `;
1705
1832
  }
1706
- function withQuery(state, key) {
1707
- const { text, caret, killed = "", chained = false } = editLine({ text: state.query, caret: state.caret, killed: state.killed, chained: state.chained }, key);
1708
- return text === state.query ? { ...state, caret, killed, chained } : { ...state, query: text, caret, killed, chained, matches: rank(text, state.searchable), cursor: 0 };
1833
+
1834
+ // ../kit/src/notify.ts
1835
+ init_format();
1836
+ init_mode();
1837
+ import process14 from "process";
1838
+ var NOTIFY_AFTER_MS = 1e4;
1839
+ var CANCELLED = 130;
1840
+ function base64(text) {
1841
+ return Buffer.from(text).toString("base64");
1709
1842
  }
1710
- function move(state, by) {
1711
- return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
1843
+ function notification(title, body, env = process14.env) {
1844
+ const id = `kit${process14.pid}`;
1845
+ 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\\`];
1846
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1712
1847
  }
1713
- function highlighted(state) {
1714
- return state.matches[state.cursor]?.index;
1848
+ function notifyEnd(command, code, ms, { stream = process14.stderr, env = process14.env } = {}) {
1849
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1850
+ return;
1851
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1715
1852
  }
1716
- function press(state, key) {
1717
- if (state.done !== undefined)
1718
- return state;
1719
- if (state.chained && endsKills(key))
1720
- state = { ...state, chained: false };
1721
- if (state.help)
1722
- return { ...state, help: false };
1723
- if (typeof key === "object") {
1724
- if ("text" in key)
1725
- return withQuery(state, key);
1726
- return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
1853
+
1854
+ // ../kit/src/cli.ts
1855
+ init_style();
1856
+ init_text2();
1857
+
1858
+ // ../kit/src/usage.ts
1859
+ import { appendFileSync, mkdirSync } from "fs";
1860
+ import { homedir as homedir4 } from "os";
1861
+ import { dirname as dirname2, join as join5 } from "path";
1862
+ import process16 from "process";
1863
+
1864
+ // ../kit/src/logs.ts
1865
+ init_user_config();
1866
+ import { lstatSync, openSync } from "fs";
1867
+ import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
1868
+ import { homedir as homedir3, tmpdir } from "os";
1869
+ import { join as join4 } from "path";
1870
+ import process15 from "process";
1871
+ var DAY_MS = 24 * 60 * 60 * 1000;
1872
+ var CLI_FOLDER = "kaynooo-cli";
1873
+ function isPrivateDirectory(path) {
1874
+ try {
1875
+ const info = lstatSync(path, { throwIfNoEntry: false });
1876
+ return info !== undefined && info.isDirectory() && info.uid === (process15.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
1877
+ } catch {
1878
+ return false;
1727
1879
  }
1728
- if (isEditKey(key))
1729
- return withQuery(state, key);
1730
- switch (key) {
1731
- case "up":
1732
- return move(state, -1);
1733
- case "down":
1734
- return move(state, 1);
1735
- case "pageup":
1736
- return move(state, -state.page);
1737
- case "pagedown":
1738
- return move(state, state.page);
1739
- case "home":
1740
- return move(state, -state.matches.length);
1741
- case "end":
1742
- return move(state, state.matches.length);
1743
- case "cancel":
1744
- return { ...state, done: "cancel" };
1745
- case "help":
1746
- return { ...state, help: true };
1747
- case "suspend":
1748
- return state;
1749
- case "enter":
1750
- return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
1751
- case "tab": {
1752
- const at = highlighted(state);
1753
- if (!state.multi || at === undefined)
1754
- return state;
1755
- const marked = new Set(state.marked);
1756
- if (!marked.delete(at))
1757
- marked.add(at);
1758
- return move({ ...state, marked }, 1);
1759
- }
1880
+ }
1881
+ async function privateLogDirectory(name, env = process15.env) {
1882
+ const path = join4(xdgFolder(env.XDG_RUNTIME_DIR, join4(homedir3(), ".cache")), CLI_FOLDER, name);
1883
+ try {
1884
+ await mkdir(path, { recursive: true, mode: 448 });
1885
+ if (isPrivateDirectory(path))
1886
+ return path;
1887
+ } catch {}
1888
+ return mkdtemp(join4(tmpdir(), `${name.replaceAll("/", "-")}-`));
1889
+ }
1890
+ async function sweepLogs(dir, maxAgeMs = DAY_MS, now = Date.now()) {
1891
+ let names;
1892
+ try {
1893
+ names = await readdir(dir);
1894
+ } catch {
1895
+ return;
1896
+ }
1897
+ for (const name of names) {
1898
+ const path = join4(dir, name);
1899
+ try {
1900
+ const info = await stat(path);
1901
+ if (info.isDirectory())
1902
+ await sweepLogs(path, maxAgeMs, now);
1903
+ if (now - info.mtimeMs > maxAgeMs)
1904
+ await rm(path, { force: true, recursive: info.isDirectory() });
1905
+ } catch {
1906
+ continue;
1907
+ }
1908
+ }
1909
+ }
1910
+
1911
+ // ../kit/src/usage.ts
1912
+ init_user_config();
1913
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1914
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1915
+ var LONGEST_NAME = 40;
1916
+ var usageError;
1917
+ function noteUsageError(message) {
1918
+ usageError = message;
1919
+ }
1920
+ function stateHome(env = process16.env) {
1921
+ return xdgFolder(env.XDG_STATE_HOME, join5(homedir4(), ".local", "state"));
1922
+ }
1923
+ function usagePath(env = process16.env) {
1924
+ return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
1925
+ }
1926
+ function usageRecorded(env = process16.env) {
1927
+ const off = env.KAYNOOO_CLI_NO_USAGE;
1928
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1929
+ }
1930
+ function flagNames(argv) {
1931
+ const end = argv.indexOf("--");
1932
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1933
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1934
+ }
1935
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1936
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1937
+ usageError = undefined;
1938
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1939
+ }
1940
+ function recordUsage(entry, env = process16.env) {
1941
+ if (!usageRecorded(env))
1942
+ return;
1943
+ try {
1944
+ const path = usagePath(env);
1945
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1946
+ appendFileSync(path, `${JSON.stringify(entry)}
1947
+ `, { mode: 384 });
1948
+ } catch {}
1949
+ }
1950
+
1951
+ // ../kit/src/cli.ts
1952
+ var LEVEL_OPTIONS = {
1953
+ ...OUTPUT_OPTIONS,
1954
+ help: { type: "boolean", short: "h", description: "show this help" }
1955
+ };
1956
+ var TOP_OPTIONS = {
1957
+ ...LEVEL_OPTIONS,
1958
+ version: { type: "boolean", short: "v", description: "print the version" },
1959
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1960
+ };
1961
+ function printError(prefix, message, hint, cause) {
1962
+ const colors = paint(process17.stderr);
1963
+ const styled = takesControlCodes(process17.stderr);
1964
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1965
+ const under = (label, text, tint) => text === undefined ? "" : `
1966
+ ${styled ? tint(label) : `${label}:`} ${text}`;
1967
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1968
+ }
1969
+ function printJsonError(message, hint, cause) {
1970
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1971
+ }
1972
+ function wantsJson(argv) {
1973
+ const end = argv.indexOf("--");
1974
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1975
+ }
1976
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
1977
+ if (error instanceof HelpShown)
1978
+ return 0;
1979
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1980
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1981
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1982
+ if (error instanceof Exit && error.code === 2)
1983
+ noteUsageError(error.message);
1984
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1985
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1986
+ return error instanceof Exit ? error.code : 1;
1987
+ }
1988
+ var COMPLETE = "__complete";
1989
+ var FILES = "__files__";
1990
+ async function completingOf(run) {
1991
+ completion.active = true;
1992
+ try {
1993
+ await run([]);
1994
+ } catch (error) {
1995
+ if (error instanceof Completing)
1996
+ return error;
1997
+ } finally {
1998
+ completion.active = false;
1999
+ }
2000
+ return new Completing({});
2001
+ }
2002
+ function candidateLine(candidate) {
2003
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
2004
+ }
2005
+ function positionalBeingTyped(before, { options, positionals }) {
2006
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
2007
+ const typed = [];
2008
+ let at = 0;
2009
+ while (at < before.length) {
2010
+ const word = before[at];
2011
+ if (word === "--") {
2012
+ typed.push(...before.slice(at + 1));
2013
+ break;
2014
+ }
2015
+ if (!word.startsWith("-"))
2016
+ typed.push(word);
2017
+ else if (takesValue(word))
2018
+ at++;
2019
+ at++;
2020
+ }
2021
+ const last = positionals.at(-1);
2022
+ if (typed.length < positionals.length)
2023
+ return { name: positionals[typed.length], typed };
2024
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
2025
+ }
2026
+ async function leafCandidates(run, words) {
2027
+ const completing = await completingOf(run);
2028
+ if ((words.at(-1) ?? "").startsWith("-"))
2029
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
2030
+ const flag = words.at(-2);
2031
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
2032
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
2033
+ if (option?.type === "string") {
2034
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
2035
+ return values === undefined ? [FILES] : values.map(candidateLine);
2036
+ }
2037
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
2038
+ return values === undefined ? [FILES] : values.map(candidateLine);
2039
+ }
2040
+ var COMPLETIONS = "--completions";
2041
+ function flagValue([flag = "", ...rest]) {
2042
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
2043
+ }
2044
+ function printCompletionScript(name, args) {
2045
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
2046
+ if (shell === undefined || args.length !== 1) {
2047
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
2048
+ return 2;
2049
+ }
2050
+ console.log(completionScript(shell, [name]).trimEnd());
2051
+ return 0;
2052
+ }
2053
+ async function printCandidates(found) {
2054
+ for (const line of await found)
2055
+ console.log(line);
2056
+ return 0;
2057
+ }
2058
+ function packageVersion(entry = Bun.main) {
2059
+ let resolved = entry;
2060
+ try {
2061
+ resolved = realpathSync2(entry);
2062
+ } catch {}
2063
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
2064
+ try {
2065
+ const { version } = JSON.parse(readFileSync5(join6(dir, "package.json"), "utf8"));
2066
+ if (typeof version === "string")
2067
+ return version;
2068
+ } catch {}
2069
+ if (dirname3(dir) === dir)
2070
+ return "0.0.0";
2071
+ }
2072
+ }
2073
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
2074
+ const answered = await askpassClient(argv);
2075
+ if (answered !== undefined)
2076
+ return answered;
2077
+ if (argv[0] === COMPLETE)
2078
+ return printCandidates(leafCandidates(run, argv.slice(1)));
2079
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
2080
+ return printCompletionScript(name, flagValue(argv));
2081
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
2082
+ console.log(version ?? packageVersion());
2083
+ return 0;
2084
+ }
2085
+ let code;
2086
+ const started = performance.now();
2087
+ try {
2088
+ code = await run(argv);
2089
+ } catch (error) {
2090
+ code = reportThrown(name, error, redact, wantsJson(argv));
2091
+ }
2092
+ notifyEnd(name, code, performance.now() - started);
2093
+ if (usage !== false) {
2094
+ try {
2095
+ recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
2096
+ } catch {}
2097
+ }
2098
+ return code;
2099
+ }
2100
+
2101
+ // ../kit/src/index.ts
2102
+ init_config();
2103
+
2104
+ // ../kit/src/excerpt.ts
2105
+ init_text2();
2106
+ var BASH_ECHO = /^\$ /;
2107
+ var DURATION2 = / \[[\d.]+m?s\]$/;
2108
+ var BOUNDARY = /^(?:\((?:pass|fail|skip|todo)\) |\S+\.test\.[jt]sx?:$)/;
2109
+ var BUN_TEST_SUMMARY = /^\s*\d+ (?:pass|fail|skip|todo)$|^Ran \d+ tests?/;
2110
+ var BUN_CHECK_BLOCK = /<error file=[\s\S]*?<\/error>/g;
2111
+ var BUN_CHECK_SOURCE = /<source>[\s\S]*?<\/source>\n?/g;
2112
+ var BUN_CHECK_ATTRIBUTE = /(\w+)="([^"]*)"/g;
2113
+ var BUN_CHECK_SUMMARY = /^Found \d+ errors?/;
2114
+ var TSC_ERROR = /\berror TS\d+/;
2115
+ var TSC_CONTINUATION = /^\s{2,}\S/;
2116
+ var TSC_FRAME = /^\s*[~^|]/;
2117
+ var TSC_SUMMARY = /^Found \d+ errors?/;
2118
+ var ESLINT_PROBLEM = /^\s+\d+:\d+\s+(?:error|warning)\s/;
2119
+ var ESLINT_SUMMARY = /^(?:\u2716 )?\d+ problems? \(/;
2120
+ var PHPSTAN_TABLE = /^\s*-{3,} -{3,}/;
2121
+ var PHPSTAN_NOISE = /^\s*\[OK\]/;
2122
+ var PHP_FAILURES = /^(?:There w(?:as|ere) \d+ (?:failure|error|risky|warning)|\s+(?:FAIL|FAILED)\s+\S|In \S+\.php line \d+:$)/;
2123
+ var VITEST_FAIL_LINE = /^ FAIL {2}\S/;
2124
+ var PLAYWRIGHT_FAIL_LINE = /^ {2}1\) .+:\d+:\d+ \u203A .+ \u2500+$/;
2125
+ var CS_FIXER_LINE = /^\s+\d+\) \S.*\.php(?: \(.+\))?$/;
2126
+ var CS_FIXER_TOTAL = /^Found \d+ of \d+ files/;
2127
+ var MAX_TESTS = 10;
2128
+ var MAX_LINES = 100;
2129
+ var TAIL = 30;
2130
+ var bunTest = (lines) => {
2131
+ const seen = new Set;
2132
+ const blocks = [];
2133
+ for (const [index, line] of lines.entries()) {
2134
+ const name = line.replace(DURATION2, "");
2135
+ if (!line.startsWith("(fail) ") || seen.has(name))
2136
+ continue;
2137
+ seen.add(name);
2138
+ if (blocks.length < MAX_TESTS)
2139
+ blocks.push(lines.slice(lines.findLastIndex((text, at) => at < index && BOUNDARY.test(text)) + 1, index + 1).join(`
2140
+ `).trim());
2141
+ }
2142
+ if (blocks.length === 0)
2143
+ return;
2144
+ if (seen.size > MAX_TESTS)
2145
+ blocks.push(`and ${seen.size - MAX_TESTS} more failed tests`);
2146
+ return [...blocks.join(`
2147
+
2148
+ `).split(`
2149
+ `), "", ...lines.filter((line) => BUN_TEST_SUMMARY.test(line)).map((line) => line.trim())];
2150
+ };
2151
+ var bunCheck = (lines) => {
2152
+ const text = lines.join(`
2153
+ `);
2154
+ const blocks = text.match(BUN_CHECK_BLOCK);
2155
+ if (blocks === null)
2156
+ return;
2157
+ const errors = blocks.map((block) => {
2158
+ const { file, line, column, code, message } = bunCheckFields(block);
2159
+ return `${file}:${line}:${column} ${code}: ${message}`;
2160
+ });
2161
+ return [...errors, ...lines.filter((line) => BUN_CHECK_SUMMARY.test(line))];
2162
+ };
2163
+ function bunCheckFields(block) {
2164
+ const attributes = Object.fromEntries([...block.slice(0, block.indexOf(`
2165
+ `)).matchAll(BUN_CHECK_ATTRIBUTE)].map((match) => [match[1] ?? "", match[2] ?? ""]));
2166
+ return {
2167
+ file: attributes.file ?? "",
2168
+ line: attributes.line ?? "",
2169
+ column: attributes.column ?? "",
2170
+ code: attributes.code ?? "",
2171
+ message: block.replace(BUN_CHECK_SOURCE, "").split(`
2172
+ `).slice(1, -1).join(`
2173
+ `).trim()
2174
+ };
2175
+ }
2176
+ var tsc = (lines) => {
2177
+ const kept = [];
2178
+ let inError = false;
2179
+ for (const line of lines) {
2180
+ if (TSC_ERROR.test(line)) {
2181
+ inError = true;
2182
+ kept.push(line);
2183
+ } else if (TSC_SUMMARY.test(line)) {
2184
+ inError = false;
2185
+ kept.push(line);
2186
+ } else if (inError && TSC_CONTINUATION.test(line) && !TSC_FRAME.test(line)) {
2187
+ kept.push(line);
2188
+ } else {
2189
+ inError = false;
2190
+ }
2191
+ }
2192
+ return kept.some((line) => TSC_ERROR.test(line)) ? kept : undefined;
2193
+ };
2194
+ var eslint = (lines) => {
2195
+ const kept = [];
2196
+ let file = "";
2197
+ let shown = "";
2198
+ for (const line of lines) {
2199
+ if (ESLINT_PROBLEM.test(line)) {
2200
+ if (file !== shown) {
2201
+ kept.push(file);
2202
+ shown = file;
2203
+ }
2204
+ kept.push(line);
2205
+ } else if (ESLINT_SUMMARY.test(line)) {
2206
+ kept.push(line);
2207
+ } else if (line.trim() !== "") {
2208
+ file = line;
2209
+ }
2210
+ }
2211
+ return kept.some((line) => ESLINT_PROBLEM.test(line)) ? kept : undefined;
2212
+ };
2213
+ var phpstan = (lines) => {
2214
+ const start = lines.findIndex((line) => PHPSTAN_TABLE.test(line));
2215
+ return start === -1 ? undefined : lines.slice(start).filter((line) => !PHPSTAN_NOISE.test(line));
2216
+ };
2217
+ var php = (lines) => {
2218
+ const start = lines.findIndex((line) => PHP_FAILURES.test(line));
2219
+ return start === -1 ? undefined : lines.slice(start);
2220
+ };
2221
+ var vitest = (lines) => {
2222
+ const start = lines.findIndex((line) => VITEST_FAIL_LINE.test(line));
2223
+ return start === -1 ? undefined : lines.slice(start);
2224
+ };
2225
+ var playwright = (lines) => {
2226
+ const start = lines.findIndex((line) => PLAYWRIGHT_FAIL_LINE.test(line));
2227
+ return start === -1 ? undefined : lines.slice(start);
2228
+ };
2229
+ var phpCsFixer = (lines) => {
2230
+ const files = lines.filter((line) => CS_FIXER_LINE.test(line) || CS_FIXER_TOTAL.test(line));
2231
+ return files.some((line) => CS_FIXER_LINE.test(line)) ? files : undefined;
2232
+ };
2233
+ var PARSERS = [bunTest, bunCheck, tsc, eslint, vitest, playwright, phpCsFixer, phpstan, php];
2234
+ function squeeze(lines) {
2235
+ const out = [];
2236
+ for (const line of lines.map((text) => text.trimEnd())) {
2237
+ if (line !== "" || out.at(-1) !== "")
2238
+ out.push(line);
1760
2239
  }
2240
+ while (out.at(-1) === "")
2241
+ out.pop();
2242
+ return out;
1761
2243
  }
1762
- function chosen(state) {
1763
- if (state.marked.size > 0)
1764
- return state.rows.filter((_, index) => state.marked.has(index));
1765
- const at = highlighted(state);
1766
- return at === undefined ? [] : [state.rows[at]];
2244
+ function cut(shown) {
2245
+ return shown.length > MAX_LINES ? [...shown.slice(0, MAX_LINES), `... ${shown.length - MAX_LINES} more lines`].join(`
2246
+ `) : shown.join(`
2247
+ `);
2248
+ }
2249
+ function recognised(lines, parsers) {
2250
+ return parsers.map((parser) => parser(lines)).find((result) => result !== undefined && result.some((line) => line.trim() !== ""));
2251
+ }
2252
+ function failureExcerpt(output) {
2253
+ const lines = stripAnsi(output).split(`
2254
+ `);
2255
+ if (BASH_ECHO.test(lines[0] ?? ""))
2256
+ lines.shift();
2257
+ return cut(squeeze(recognised(lines, PARSERS) ?? lines.slice(-TAIL)));
1767
2258
  }
2259
+ var LOG_PATTERNS = { BASH_ECHO, DURATION: DURATION2, BOUNDARY, BUN_TEST_SUMMARY, BUN_CHECK_SUMMARY, TSC_CONTINUATION, TSC_FRAME, TSC_SUMMARY, ESLINT_PROBLEM, ESLINT_SUMMARY };
2260
+
2261
+ // ../kit/src/index.ts
2262
+ init_folders();
2263
+ init_format();
2264
+
2265
+ // ../kit/src/git.ts
2266
+ init_args();
2267
+ // ../kit/src/limit.ts
2268
+ init_args();
2269
+
2270
+ // ../kit/src/index.ts
2271
+ init_mode();
2272
+
2273
+ // ../kit/src/report.ts
2274
+ init_style();
2275
+ init_text2();
2276
+ // ../kit/src/secrets.ts
2277
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
2278
+ var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
2279
+ // ../kit/src/sessions.ts
2280
+ var {Glob } = globalThis.Bun;
2281
+ var SESSION_FILES = new Glob("*.json");
2282
+ var ACCOUNT_DIRS = new Glob("*/sessions");
2283
+
2284
+ // ../kit/src/index.ts
2285
+ init_style();
2286
+ init_text2();
2287
+ init_theme();
2288
+ init_user_config();
2289
+
2290
+ // ../kit/src/watch.ts
2291
+ init_args();
2292
+ init_input();
2293
+ init_style();
2294
+ // ../kit/src/workspace-root.ts
2295
+ init_user_config();
2296
+ // package.json
2297
+ var version = "0.21.2";
2298
+
2299
+ // src/j.ts
2300
+ import process26 from "process";
2301
+
2302
+ // ../kit/src/picker.ts
2303
+ init_folders();
2304
+ init_state();
2305
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync6, writeFileSync } from "fs";
2306
+ import { dirname as dirname4, join as join8 } from "path";
2307
+ import process23 from "process";
1768
2308
 
1769
2309
  // ../kit/src/picker/terminal.ts
2310
+ init_args();
2311
+ init_job();
2312
+ init_redraw();
2313
+ init_style();
1770
2314
  import { openSync as openSync2 } from "fs";
1771
- import process21 from "process";
2315
+ import process22 from "process";
1772
2316
  import tty from "tty";
1773
2317
 
1774
- // ../kit/src/job.ts
1775
- import process19 from "process";
1776
- function stopJob() {
1777
- process19.kill(0, "SIGTSTP");
1778
- }
1779
-
1780
- // ../kit/src/redraw.ts
1781
- var SYNC_START = "\x1B[?2026h";
1782
- var SYNC_END = "\x1B[?2026l";
1783
- function overwrite(lines, columns) {
1784
- return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
1785
- `);
1786
- }
1787
- function rowsTaken(lines, columns) {
1788
- return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
1789
- }
1790
-
1791
2318
  // ../kit/src/picker/preview.ts
1792
- import process20 from "process";
2319
+ import process21 from "process";
1793
2320
 
1794
2321
  // ../kit/src/shell.ts
1795
2322
  var SEPARATORS = new Set([`
@@ -1800,6 +2327,7 @@ var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
1800
2327
  var SAFE_WORD = /^[\w@%+=:,./-]+$/;
1801
2328
  var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
1802
2329
  var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
2330
+ var FISH_COMBINERS = new Set(["and", "or", "not"]);
1803
2331
  var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
1804
2332
  var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
1805
2333
  var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
@@ -1811,6 +2339,7 @@ var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
1811
2339
  function wrapper(short = "", long = [], operands = 0, runsString = false) {
1812
2340
  return { short, long, operands, runsString };
1813
2341
  }
2342
+ var RUNNER = { ...wrapper(), afterDashes: true };
1814
2343
  var WRAPPERS = new Map([
1815
2344
  ["command", wrapper()],
1816
2345
  ["builtin", wrapper()],
@@ -1832,7 +2361,23 @@ var WRAPPERS = new Map([
1832
2361
  ["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
1833
2362
  ["unbuffer", wrapper()],
1834
2363
  ["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
1835
- ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
2364
+ ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])],
2365
+ ["strace", wrapper("abeEIoOpPsSuUX", ["--trace", "--output", "--attach", "--string-limit", "--user", "--env", "--columns", "--trace-path", "--signal", "--status", "--summary-sort-by", "--summary-columns", "--const-print-style", "--interruptible", "--detach-on"])],
2366
+ ["ltrace", wrapper("aeFlnopsuxX", ["--output", "--user", "--library", "--config", "--align", "--indent"])],
2367
+ ["taskset", wrapper("", [], 1)],
2368
+ ["fakeroot", wrapper("lsib", ["--lib", "--faked"])],
2369
+ ["sshpass", wrapper("pfdP")],
2370
+ ["coproc", wrapper()],
2371
+ ["proxychains", wrapper("f")],
2372
+ ["proxychains4", wrapper("f")],
2373
+ ["torsocks", wrapper("upaP", ["--user", "--pass", "--address", "--port"])],
2374
+ ["chrt", wrapper("TPD", ["--sched-runtime", "--sched-period", "--sched-deadline"], 1)],
2375
+ ["unshare", wrapper("SGRw", ["--setuid", "--setgid", "--root", "--wd", "--map-user", "--map-group", "--map-users", "--map-groups", "--propagation", "--setgroups"])],
2376
+ ["nsenter", wrapper("tSG", ["--target", "--setuid", "--setgid"])],
2377
+ ["out", RUNNER],
2378
+ ["slot", RUNNER],
2379
+ ["waitfor", RUNNER],
2380
+ ["base", RUNNER]
1836
2381
  ]);
1837
2382
  function shellQuote(word) {
1838
2383
  return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
@@ -1858,7 +2403,7 @@ async function runPreview(template, line, signal, hidden = []) {
1858
2403
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1859
2404
  const stop = () => {
1860
2405
  try {
1861
- process20.kill(-proc.pid, "SIGKILL");
2406
+ process21.kill(-proc.pid, "SIGKILL");
1862
2407
  } catch {
1863
2408
  proc.kill();
1864
2409
  }
@@ -1883,7 +2428,12 @@ ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe",
1883
2428
  return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
1884
2429
  }
1885
2430
 
2431
+ // ../kit/src/picker/terminal.ts
2432
+ init_state();
2433
+
1886
2434
  // ../kit/src/picker/view.ts
2435
+ init_line();
2436
+ init_state();
1887
2437
  var MIN_HEIGHT = 4;
1888
2438
  var PREVIEW_MIN_COLUMNS = 80;
1889
2439
  var PREVIEW_MIN_ROWS = 10;
@@ -2016,7 +2566,7 @@ function openTerminal() {
2016
2566
  return fail("no terminal to read keys from (/dev/tty)");
2017
2567
  }
2018
2568
  const keys = Bun.file("/dev/tty").stream().getReader();
2019
- const out = process21.stderr;
2569
+ const out = process22.stderr;
2020
2570
  let resize;
2021
2571
  async function read(onChunk) {
2022
2572
  const decoder = new TextDecoder;
@@ -2205,9 +2755,9 @@ async function select(rows, settings, terminal = openTerminal()) {
2205
2755
  const ended = new Promise((resolve) => {
2206
2756
  finish = resolve;
2207
2757
  });
2208
- process21.once("exit", restore);
2758
+ process22.once("exit", restore);
2209
2759
  for (const signal of SIGNALS2)
2210
- process21.once(signal, stop);
2760
+ process22.once(signal, stop);
2211
2761
  try {
2212
2762
  terminal.write(`${PASTE_ON}${MOUSE_ON}`);
2213
2763
  terminal.listen(onChunk, () => draw(true));
@@ -2220,8 +2770,8 @@ async function select(rows, settings, terminal = openTerminal()) {
2220
2770
  await ended;
2221
2771
  } finally {
2222
2772
  for (const signal of SIGNALS2)
2223
- process21.off(signal, stop);
2224
- process21.off("exit", restore);
2773
+ process22.off(signal, stop);
2774
+ process22.off("exit", restore);
2225
2775
  restore();
2226
2776
  }
2227
2777
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -2235,6 +2785,7 @@ async function previewOf(preview, hidden, signal) {
2235
2785
  }
2236
2786
 
2237
2787
  // ../kit/src/picker.ts
2788
+ init_score();
2238
2789
  var REMEMBERED = 20;
2239
2790
  async function pick(rows, options) {
2240
2791
  const height = parseHeight(options.height ?? "100%");
@@ -2257,18 +2808,18 @@ function historyFile(name) {
2257
2808
  function history(name) {
2258
2809
  try {
2259
2810
  const file = historyFile(name);
2260
- return existsSync4(file) ? JSON.parse(readFileSync5(file, "utf-8")) : {};
2811
+ return existsSync4(file) ? JSON.parse(readFileSync6(file, "utf-8")) : {};
2261
2812
  } catch {
2262
2813
  return {};
2263
2814
  }
2264
2815
  }
2265
2816
  function runs(name) {
2266
- return history(name)[process22.cwd()] ?? [];
2817
+ return history(name)[process23.cwd()] ?? [];
2267
2818
  }
2268
2819
  function record(name, run) {
2269
2820
  const all = history(name);
2270
2821
  const file = historyFile(name);
2271
- all[process22.cwd()] = [run, ...(all[process22.cwd()] ?? []).filter((earlier) => earlier.id !== run.id)].slice(0, REMEMBERED);
2822
+ all[process23.cwd()] = [run, ...(all[process23.cwd()] ?? []).filter((earlier) => earlier.id !== run.id)].slice(0, REMEMBERED);
2272
2823
  mkdirSync2(dirname4(file), { recursive: true });
2273
2824
  writeFileSync(file, JSON.stringify(all));
2274
2825
  }
@@ -2291,203 +2842,14 @@ function list(rows) {
2291
2842
  console.log(JSON.stringify(rows));
2292
2843
  }
2293
2844
 
2294
- // ../kit/src/prompt.ts
2295
- import process23 from "process";
2296
-
2297
- // ../kit/src/answers.ts
2298
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync2 } from "fs";
2299
- import { dirname as dirname5, join as join9 } from "path";
2300
- var KEPT = 50;
2301
- function answersFile() {
2302
- return join9(cacheFolder(), "kaynooo-cli", "answers.json");
2303
- }
2304
- function stored() {
2305
- try {
2306
- const parsed = JSON.parse(readFileSync6(answersFile(), "utf-8"));
2307
- if (typeof parsed !== "object" || parsed === null)
2308
- return {};
2309
- return Object.fromEntries(Object.entries(parsed).filter((entry) => Array.isArray(entry[1]) && entry[1].every((answer) => typeof answer === "string")));
2310
- } catch {
2311
- return {};
2312
- }
2313
- }
2314
- function earlierAnswers(key) {
2315
- return stored()[key] ?? [];
2316
- }
2317
- function rememberAnswer(key, answer) {
2318
- const all = stored();
2319
- const file = answersFile();
2320
- all[key] = [answer, ...(all[key] ?? []).filter((earlier) => earlier !== answer)].slice(0, KEPT);
2321
- try {
2322
- mkdirSync3(dirname5(file), { recursive: true });
2323
- writeFileSync2(file, JSON.stringify(all));
2324
- } catch {}
2325
- }
2326
-
2327
- // ../kit/src/prompt.ts
2328
- var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
2329
- var MAX_LISTED = 12;
2330
- function readKeys(input, paste = { active: false }) {
2331
- return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
2332
- }
2333
- function roomAfter(question, columns) {
2334
- return Math.max(columns - textWidth(`? ${question} `) % columns - 1, 1);
2335
- }
2336
- function withCaret(colors, line, room, dim = false) {
2337
- const { before, at, after } = visible(line, room);
2338
- const tone = dim ? colors.dim : (text) => text;
2339
- return `${tone(before)}${at === undefined ? colors.dim("\u2588") : colors.inverse(at)}${tone(after)}`;
2340
- }
2341
- function sharedStart(texts) {
2342
- const [first = [], ...rest] = texts.map((text) => [...text]);
2343
- let length = first.length;
2344
- for (const chars of rest) {
2345
- const differs = chars.findIndex((char, index) => char !== first[index]);
2346
- length = Math.min(length, differs === -1 ? chars.length : differs);
2347
- }
2348
- return first.slice(0, length).join("");
2349
- }
2350
- function listed2(colors, found, columns) {
2351
- const shared = sharedStart(found);
2352
- const cut = Math.max(shared.lastIndexOf("/"), shared.lastIndexOf(" ")) + 1;
2353
- const names = found.slice(0, MAX_LISTED).map((each) => each.slice(cut));
2354
- const more = found.length > MAX_LISTED ? ` \u2026 ${found.length - MAX_LISTED} more` : "";
2355
- return ` ${colors.dim(truncate(names.join(" ") + more, Math.max(columns - 3, 1)))}`;
2356
- }
2357
- async function input2(question, { default: fallback, mask = false, validate, history, complete, ...settings } = {}) {
2358
- let line = { text: "", caret: 0 };
2359
- let invalid;
2360
- let completions = [];
2361
- const remembered = history === undefined || mask ? undefined : history;
2362
- const earlier = remembered === undefined ? [] : earlierAnswers(remembered);
2363
- let recalled = -1;
2364
- let draft = line;
2365
- const taken = () => line.text === "" ? fallback ?? "" : line.text;
2366
- const shown = () => mask ? "*".repeat([...taken()].length) : taken();
2367
- const accepted = await ask(question, settings, (colors, state, { columns }) => {
2368
- if (state !== "asking")
2369
- return [answer(colors, question, state, shown())];
2370
- const typed = line.text === "" ? { text: shown(), caret: [...shown()].length } : { text: shown(), caret: line.caret };
2371
- return [`${colors.cyan("?")} ${question} ${withCaret(colors, typed, roomAfter(question, columns), line.text === "")}`, ...invalid === undefined ? [] : [` ${colors.red(invalid)}`], ...completions.length > 1 ? [listed2(colors, completions, columns)] : []];
2372
- }, (key) => {
2373
- if (key === "cancel")
2374
- return "cancel";
2375
- invalid = undefined;
2376
- completions = [];
2377
- if (line.chained === true && endsKills(key))
2378
- line = { ...line, chained: false };
2379
- if (key === "tab") {
2380
- const chars = [...line.text];
2381
- const before = chars.slice(0, line.caret).join("");
2382
- const found = complete?.(before) ?? [];
2383
- const filled = sharedStart(found);
2384
- if ([...filled].length > [...before].length)
2385
- line = { ...line, text: filled + chars.slice(line.caret).join(""), caret: [...filled].length };
2386
- else
2387
- completions = found;
2388
- return;
2389
- }
2390
- if (key === "enter") {
2391
- invalid = validate?.(taken());
2392
- return invalid === undefined ? "enter" : undefined;
2393
- }
2394
- if (key === "up" || key === "down") {
2395
- const to = Math.min(Math.max(recalled + (key === "up" ? 1 : -1), -1), earlier.length - 1);
2396
- if (recalled === -1)
2397
- draft = line;
2398
- recalled = to;
2399
- const shown = to === -1 ? draft : { text: earlier[to], caret: [...earlier[to]].length };
2400
- line = { ...shown, killed: line.killed ?? "" };
2401
- return;
2402
- }
2403
- const edit = { home: "linestart", end: "lineend" }[key] ?? key;
2404
- if (typeof edit === "object" || isEditKey(edit))
2405
- line = editLine(line, edit);
2406
- return;
2407
- });
2408
- if (!accepted)
2409
- return;
2410
- if (remembered !== undefined && taken() !== "")
2411
- rememberAnswer(remembered, taken());
2412
- return taken();
2413
- }
2414
- function answer(colors, question, state, picked) {
2415
- return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
2416
- }
2417
- async function ask(question, { hint, terminal = process23 }, render, press) {
2418
- const { stdin, stderr } = terminal;
2419
- if (!isInteractive(terminal))
2420
- fail(`cannot ask "${question}" off a terminal`, 2, hint);
2421
- const colors = paint(stderr);
2422
- let current = "asking";
2423
- let outcome;
2424
- const columns = () => stderr.columns || 80;
2425
- const draw = (state, last = false) => {
2426
- const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
2427
- const rows = rowsTaken(frame, columns());
2428
- stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
2429
- current = state;
2430
- };
2431
- const redraw = () => draw(current);
2432
- const paste = { active: false };
2433
- const stop = terminal.stop ?? (terminal === process23 ? stopJob : undefined);
2434
- const suspend = () => {
2435
- if (stop === undefined)
2436
- return;
2437
- stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
2438
- stdin.setRawMode(false);
2439
- stop();
2440
- stdin.setRawMode(true);
2441
- stderr.write("\x1B[?25l\x1B[?2004h");
2442
- };
2443
- try {
2444
- stderr.on?.("resize", redraw);
2445
- stdin.setRawMode(true);
2446
- stdin.resume();
2447
- stderr.write("\x1B[?25l\x1B[?2004h");
2448
- draw("asking");
2449
- return await new Promise((resolve) => {
2450
- function onData(data) {
2451
- for (const key of readKeys(data.toString(), paste)) {
2452
- if (key === "suspend") {
2453
- suspend();
2454
- continue;
2455
- }
2456
- const pressed = press(key);
2457
- if (pressed !== undefined) {
2458
- settle(pressed);
2459
- return;
2460
- }
2461
- }
2462
- draw("asking");
2463
- }
2464
- function onEnd() {
2465
- settle("cancel");
2466
- }
2467
- function settle(settled) {
2468
- outcome = settled;
2469
- stdin.off("data", onData);
2470
- stdin.off("end", onEnd);
2471
- resolve(settled === "enter");
2472
- }
2473
- stdin.on("data", onData);
2474
- stdin.on("end", onEnd);
2475
- });
2476
- } finally {
2477
- stderr.off?.("resize", redraw);
2478
- draw(outcome ?? "cancel", true);
2479
- stderr.write(`
2480
- \x1B[?25h\x1B[?2004l`);
2481
- stdin.setRawMode(false);
2482
- stdin.pause();
2483
- }
2484
- }
2845
+ // src/j.ts
2846
+ init_prompt();
2485
2847
 
2486
2848
  // src/job-picker.ts
2487
- import process24 from "process";
2849
+ import process25 from "process";
2488
2850
 
2489
2851
  // src/jobs.ts
2490
- import { existsSync as existsSync5, readdirSync, readFileSync as readFileSync7 } from "fs";
2852
+ import { existsSync as existsSync5, readdirSync, readFileSync as readFileSync8 } from "fs";
2491
2853
  import { dirname as dirname6, join as join11, resolve as resolvePath } from "path";
2492
2854
 
2493
2855
  // src/steps.ts
@@ -2743,7 +3105,7 @@ function make(dir) {
2743
3105
  const file = MAKEFILES.find((name) => existsSync5(join11(dir, name)));
2744
3106
  if (file === undefined)
2745
3107
  return [];
2746
- const source = readFileSync7(join11(dir, file), "utf-8");
3108
+ const source = readFileSync8(join11(dir, file), "utf-8");
2747
3109
  return build({ kind: "make", tag: "make", runner: ["make"], separated: false, dir }, targets2(source).map((target) => ({ ...target, body: show(source, target.name) })));
2748
3110
  }
2749
3111
  function manager(dir, manifest) {
@@ -2766,7 +3128,7 @@ function packageScripts(dir, here) {
2766
3128
  const file = locate(dir, here, ["package.json"]);
2767
3129
  if (file === undefined)
2768
3130
  return [];
2769
- const manifest = JSON.parse(readFileSync7(file, "utf-8"));
3131
+ const manifest = JSON.parse(readFileSync8(file, "utf-8"));
2770
3132
  const tool = manager(dirname6(file), manifest);
2771
3133
  const items = Object.entries(table2(manifest.scripts)).map(([name, command]) => ({ name, body: text2(command) }));
2772
3134
  return build({ kind: "package", tag: tool, runner: [tool, "run"], separated: tool === "npm", dir: dirname6(file) }, items);
@@ -2775,7 +3137,7 @@ function composer(dir, here) {
2775
3137
  const file = locate(dir, here, ["composer.json"]);
2776
3138
  if (file === undefined)
2777
3139
  return [];
2778
- const manifest = JSON.parse(readFileSync7(file, "utf-8"));
3140
+ const manifest = JSON.parse(readFileSync8(file, "utf-8"));
2779
3141
  const descriptions = table2(manifest["scripts-descriptions"]);
2780
3142
  const items = Object.entries(table2(manifest.scripts)).map(([name, command]) => ({ name, doc: field(descriptions, name), body: text2(command) }));
2781
3143
  return build({ kind: "composer", tag: "composer", runner: ["composer", "run"], separated: true, dir: dirname6(file) }, items);
@@ -2784,7 +3146,7 @@ function deno(dir, here) {
2784
3146
  const file = locate(dir, here, ["deno.json", "deno.jsonc"]);
2785
3147
  if (file === undefined)
2786
3148
  return [];
2787
- const manifest = Bun.JSONC.parse(readFileSync7(file, "utf-8"));
3149
+ const manifest = Bun.JSONC.parse(readFileSync8(file, "utf-8"));
2788
3150
  const items = Object.entries(table2(manifest.tasks)).map(([name, task]) => ({ name, doc: field(task, "description"), body: field(task, "command") ?? text2(task) }));
2789
3151
  return build({ kind: "deno", tag: "deno", runner: ["deno", "task"], separated: false, dir: dirname6(file) }, items);
2790
3152
  }
@@ -2792,7 +3154,7 @@ function taskfile(dir, here) {
2792
3154
  const file = locate(dir, here, TASKFILES);
2793
3155
  if (file === undefined)
2794
3156
  return [];
2795
- const tasks = table2(Bun.YAML.parse(readFileSync7(file, "utf-8"))?.tasks);
3157
+ const tasks = table2(Bun.YAML.parse(readFileSync8(file, "utf-8"))?.tasks);
2796
3158
  const items = Object.entries(tasks).filter(([, task]) => !(task !== null && typeof task === "object" && task.internal === true)).map(([name, task]) => ({ name, doc: field(task, "desc") ?? field(task, "summary"), body: text2(task) }));
2797
3159
  return build({ kind: "task", tag: "task", runner: ["task"], separated: true, dir: dirname6(file) }, items);
2798
3160
  }
@@ -2811,7 +3173,7 @@ function pyproject(dir, here) {
2811
3173
  const file = locate(dir, here, ["pyproject.toml"]);
2812
3174
  if (file === undefined)
2813
3175
  return [];
2814
- const manifest = Bun.TOML.parse(readFileSync7(file, "utf-8"));
3176
+ const manifest = Bun.TOML.parse(readFileSync8(file, "utf-8"));
2815
3177
  const tool = table2(manifest.tool);
2816
3178
  const project = table2(manifest.project);
2817
3179
  const uv = locate(dirname6(file), true, ["uv.lock"]) !== undefined;
@@ -2843,9 +3205,9 @@ function readOr(read, fallback) {
2843
3205
  }
2844
3206
  }
2845
3207
  function workspaces() {
2846
- const manifest = readOr(() => JSON.parse(readFileSync7("package.json", "utf-8")), {});
3208
+ const manifest = readOr(() => JSON.parse(readFileSync8("package.json", "utf-8")), {});
2847
3209
  const declared = Array.isArray(manifest.workspaces) ? manifest.workspaces : table2(manifest.workspaces).packages;
2848
- const pnpm = readOr(() => table2(Bun.YAML.parse(readFileSync7("pnpm-workspace.yaml", "utf-8"))).packages, undefined);
3210
+ const pnpm = readOr(() => table2(Bun.YAML.parse(readFileSync8("pnpm-workspace.yaml", "utf-8"))).packages, undefined);
2849
3211
  const patterns = [declared, pnpm].flatMap((value) => Array.isArray(value) ? value.filter((pattern) => typeof pattern === "string") : []);
2850
3212
  const excluded = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => new Bun.Glob(pattern.slice(1)));
2851
3213
  return patterns.filter((pattern) => !pattern.startsWith("!")).flatMap((pattern) => [...new Bun.Glob(`${pattern.replace(TRAILING_SLASHES, "")}/package.json`).scanSync({ cwd: "." })].map((file) => dirname6(file))).filter((dir) => !dir.split("/").includes("node_modules") && !excluded.some((glob) => glob.match(dir)));
@@ -2904,7 +3266,7 @@ function labelled(entries) {
2904
3266
  return new Set(entries.map((entry) => entry.tag)).size > 1;
2905
3267
  }
2906
3268
  function row(entry, labels, signed) {
2907
- const colors = paint(process24.stderr);
3269
+ const colors = paint(process25.stderr);
2908
3270
  const keyed = entry.dir === "." ? entry.name : `${colors.dim(`${entry.dir}/`)}${entry.name}`;
2909
3271
  return {
2910
3272
  hidden: [entry.kind, entry.dir, entry.name, id(entry)],
@@ -2918,7 +3280,7 @@ async function pickJob(entries, narrowed = false) {
2918
3280
  prompt: `${[...new Set(entries.map((entry) => entry.tag))].join("/")}> `,
2919
3281
  searched: labels ? 2 : 1,
2920
3282
  ...narrowed ? { height: heightFor(entries.length) } : {},
2921
- preview: `${process24.execPath} ${process24.argv[1]} --show {1} {2} {3}`
3283
+ preview: `${process25.execPath} ${process25.argv[1]} --show {1} {2} {3}`
2922
3284
  });
2923
3285
  return entries.find((candidate) => id(candidate) === picked?.hidden[3]);
2924
3286
  }
@@ -2927,10 +3289,9 @@ async function pickJob(entries, narrowed = false) {
2927
3289
  var usage2 = `j [name] [args...]
2928
3290
  j -
2929
3291
 
2930
- Without a name, picks a recipe, target, script or task of this folder, its parents and its child folders when a terminal is attached, and runs it. The ones run last come first, per folder. Without a terminal it lists them instead.
2931
- \`j -\` runs the last one again with the same arguments, \`j <name> [args...]\` runs without the picker, the words after the name filling the parameters in order and the required ones left being asked for.
2932
- The sources are a Justfile, a Makefile, the scripts of a package.json (through its package manager), composer.json scripts, deno tasks, a Taskfile, mise tasks and a pyproject (poe tasks and entry points).
2933
- A name is the key behind the folder it runs from, \`api/test\`, bare for this folder. A name several entries share offers them, unless it comes qualified by its runner: \`just:check\`, \`bun:api/test\`.`;
3292
+ Without a name, picks a recipe, script or task of this folder, its parents and its child folders and runs it, the ones run last first; without a terminal it lists them instead.
3293
+ \`j -\` runs the last one again with the same arguments, \`j <name> [args...]\` runs without the picker, the words after the name filling the parameters in order.
3294
+ The sources are a Justfile, a Makefile, package.json and composer.json scripts, deno tasks, a Taskfile, mise tasks and a pyproject; a name several share offers them, unless qualified by its runner (\`just:check\`).`;
2934
3295
  var EXITS = [["its own", "the code of the command it ran"], [1, "there is nothing to run here or nothing by that name"]];
2935
3296
  var options = {
2936
3297
  json: jsonOption("[{ id, key, runner, dir, name, doc, parameters }]")
@@ -2939,7 +3300,7 @@ function preview(kind, dir, name) {
2939
3300
  const entry = readKind(kind, dir).find((candidate) => candidate.name === name);
2940
3301
  if (entry === undefined)
2941
3302
  return;
2942
- const colors = paint(process25.stdout);
3303
+ const colors = paint(process26.stdout);
2943
3304
  console.log(`${colors.dim(`$ ${dir === "." ? "" : `env -C ${dir} `}`)}${colors.bold([...entry.runner, entry.name].join(" "))}
2944
3305
  `);
2945
3306
  if (entry.body !== undefined)
@@ -2954,7 +3315,7 @@ function names(found) {
2954
3315
  return same.length === 1 ? [[name, described(same[0])]] : [[name, same.map((entry) => entry.tag).join(", ")], ...same.map((entry) => [id(entry), described(entry)])];
2955
3316
  });
2956
3317
  }
2957
- function completions() {
3318
+ function completions2() {
2958
3319
  try {
2959
3320
  return [...names(everything()), ["-", "the last one again, with its arguments"]];
2960
3321
  } catch {
@@ -2972,7 +3333,7 @@ function listed3(found) {
2972
3333
  }));
2973
3334
  }
2974
3335
  function listing(found) {
2975
- const colors = paint(process25.stdout);
3336
+ const colors = paint(process26.stdout);
2976
3337
  const labels = labelled(found);
2977
3338
  return table(found.map((entry) => [...labels ? [entry.tag] : [], key(entry), signature(entry), colors.dim(entry.doc ?? "")]));
2978
3339
  }
@@ -3011,7 +3372,7 @@ async function j2(argv) {
3011
3372
  const parsed = last ? { values: {}, positionals: ["-"], rest: args.slice(1) } : parse(args, usage2, options, {
3012
3373
  exits: EXITS,
3013
3374
  positionals: ["[name]"],
3014
- candidates: { "[name]": completions },
3375
+ candidates: { "[name]": completions2 },
3015
3376
  trailing: true,
3016
3377
  replaces: "reading the Justfile, Makefile, package.json scripts or composer scripts to find what to run, then retyping it",
3017
3378
  examples: ["j", ["j test", "run the test recipe, script or task"], ["j api/test --watch", "a child folder's, with an argument"], ["j just:check", "the one of a runner, when several share the name"], ["j -", "the last one again"]]
@@ -3073,4 +3434,4 @@ async function j2(argv) {
3073
3434
  }
3074
3435
 
3075
3436
  // src/j-cli.ts
3076
- process26.exitCode = await runMain({ name: "j", version, run: j2 });
3437
+ process27.exitCode = await runMain({ name: "j", version, run: j2 });