@kaynooo/cli-code 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,16 +2,34 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process13 from "process";
5
+ import process17 from "process";
6
6
  // ../kit/src/args.ts
7
- import process5 from "process";
7
+ import process9 from "process";
8
8
  import { parseArgs } from "util";
9
9
 
10
10
  // ../kit/src/format.ts
11
- import process3 from "process";
11
+ import process7 from "process";
12
12
 
13
- // ../kit/src/style.ts
13
+ // ../kit/src/mode.ts
14
14
  import process2 from "process";
15
+ var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
16
+ var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
17
+ function isSet(value) {
18
+ return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
19
+ }
20
+ function outputMode(stream = process2.stdout, env = process2.env) {
21
+ const chosen = env.KIT_MODE;
22
+ if (chosen !== undefined && MODES.has(chosen))
23
+ return chosen;
24
+ if (AGENT_VARIABLES.some((name) => isSet(env[name])))
25
+ return "agent";
26
+ if (stream.isTTY === true)
27
+ return "terminal";
28
+ return isSet(env.CI) ? "ci" : "pipe";
29
+ }
30
+
31
+ // ../kit/src/style.ts
32
+ import process6 from "process";
15
33
 
16
34
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
17
35
  function x(s) {
@@ -274,36 +292,242 @@ function le(i = {}) {
274
292
  }
275
293
  var t = le();
276
294
 
277
- // ../kit/src/style.ts
278
- var MARKS = {
279
- ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
280
- warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
281
- problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
282
- note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
295
+ // ../kit/src/theme.ts
296
+ import { existsSync as existsSync2, readFileSync, statSync } from "fs";
297
+ import { homedir as homedir2 } from "os";
298
+ import { join as join3, resolve as resolve2 } from "path";
299
+ import process5 from "process";
300
+
301
+ // ../kit/src/config.ts
302
+ import { existsSync } from "fs";
303
+ import { dirname, join, resolve } from "path";
304
+ import process3 from "process";
305
+ function findUp(names, from = process3.cwd(), stop = () => false) {
306
+ const wanted = typeof names === "string" ? [names] : names;
307
+ for (let dir = resolve(from);; dir = dirname(dir)) {
308
+ const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
309
+ if (found !== undefined)
310
+ return found;
311
+ if (stop(dir) || dirname(dir) === dir)
312
+ return;
313
+ }
314
+ }
315
+
316
+ // ../kit/src/user-config.ts
317
+ import { homedir } from "os";
318
+ import { join as join2 } from "path";
319
+ import process4 from "process";
320
+ function configBase(where = {}) {
321
+ const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
322
+ return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
323
+ }
324
+ function userConfigPath(bin, where = {}) {
325
+ return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
326
+ }
327
+
328
+ // ../kit/src/theme.ts
329
+ var DEFAULT = {
330
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
331
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501" },
332
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
333
+ bins: {}
283
334
  };
284
- function takesControlCodes(stream, env = process2.env) {
285
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
335
+ var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
336
+ var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
337
+ var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#" };
338
+ var PRESETS = {
339
+ default: {},
340
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"] },
341
+ mono: { colors: MONO, accents: ["bold"] },
342
+ ascii: { glyphs: ASCII }
343
+ };
344
+ 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"]);
345
+ var HEX = /^#[0-9a-f]{6}$/i;
346
+ var CONTROL = /\p{Cc}/u;
347
+ var MAX_FILE_BYTES = 64 * 1024;
348
+ var SPACES = /\s+/;
349
+ function isColorSpec(spec) {
350
+ if (typeof spec === "number")
351
+ return Number.isInteger(spec) && spec >= 0 && spec <= 255;
352
+ return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
353
+ }
354
+ var CUBE = [0, 95, 135, 175, 215, 255];
355
+ function cubeLevel(channel) {
356
+ return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
357
+ }
358
+ function nearest256(hex) {
359
+ const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
360
+ const levels = rgb.map(cubeLevel);
361
+ const cube = levels.map((level) => CUBE[level]);
362
+ const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
363
+ const greyValue = 8 + grey * 10;
364
+ const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
365
+ return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
366
+ }
367
+ function hasTrueColor(env) {
368
+ return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
369
+ }
370
+ function tinted(colors, spec, env = process5.env) {
371
+ if (typeof spec === "number")
372
+ return colors.ansi256(spec);
373
+ return spec.trim().split(SPACES).reduce((chain, token) => {
374
+ if (HEX.test(token))
375
+ return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
376
+ return chain[token] ?? chain;
377
+ }, colors);
378
+ }
379
+ function isRecord(value) {
380
+ return typeof value === "object" && value !== null && !Array.isArray(value);
381
+ }
382
+ function readThemeFile(path, warn) {
383
+ try {
384
+ const stat = statSync(path, { throwIfNoEntry: false });
385
+ if (stat === undefined)
386
+ return;
387
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
388
+ warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
389
+ return;
390
+ }
391
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
392
+ if (isRecord(parsed))
393
+ return parsed;
394
+ warn(`${path} is not a JSON object, theme ignored`);
395
+ } catch (error) {
396
+ warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
397
+ }
398
+ return;
399
+ }
400
+ function applyPreset(theme, name, warn, where) {
401
+ if (name === undefined)
402
+ return;
403
+ if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
404
+ warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
405
+ return;
406
+ }
407
+ const preset = PRESETS[name];
408
+ Object.assign(theme.colors, preset.colors);
409
+ Object.assign(theme.glyphs, preset.glyphs);
410
+ if (preset.accents !== undefined)
411
+ theme.accents = [...preset.accents];
412
+ return name;
413
+ }
414
+ function applyFile(theme, file, where, warn) {
415
+ if (isRecord(file.colors)) {
416
+ for (const [key, value] of Object.entries(file.colors)) {
417
+ if (!Object.hasOwn(DEFAULT.colors, key))
418
+ warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
419
+ else if (!isColorSpec(value))
420
+ warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
421
+ else
422
+ theme.colors[key] = value;
423
+ }
424
+ }
425
+ if (isRecord(file.glyphs)) {
426
+ for (const [key, value] of Object.entries(file.glyphs)) {
427
+ if (!Object.hasOwn(DEFAULT.glyphs, key))
428
+ warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
429
+ else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
430
+ warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
431
+ else
432
+ theme.glyphs[key] = value;
433
+ }
434
+ }
435
+ if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
436
+ theme.accents = [...file.accents];
437
+ else if (file.accents !== undefined)
438
+ warn(`${where}: accents must be a non-empty list of colours`);
439
+ if (isRecord(file.bins)) {
440
+ for (const [bin, value] of Object.entries(file.bins)) {
441
+ if (isColorSpec(value))
442
+ theme.bins[bin] = value;
443
+ else
444
+ warn(`${where}: bin ${bin} has no valid colour`);
445
+ }
446
+ }
447
+ }
448
+ function endsWalk(home) {
449
+ return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
450
+ }
451
+ var warned = new Set;
452
+ function warnOnce(message) {
453
+ if (warned.has(message))
454
+ return;
455
+ warned.add(message);
456
+ console.error(`warning: theme ${message}`);
457
+ }
458
+ function isPath(chosen) {
459
+ return chosen.includes("/") || chosen.endsWith(".json");
460
+ }
461
+ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
462
+ const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
463
+ const sources = [];
464
+ const chosen = env.KIT_THEME ?? "";
465
+ const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
466
+ if (isPath(chosen))
467
+ wanted.push(resolve2(from, chosen));
468
+ const files = [];
469
+ for (const path of wanted) {
470
+ const file = path === undefined ? undefined : readThemeFile(path, warn);
471
+ if (path !== undefined && file !== undefined)
472
+ files.push({ path, file });
473
+ }
474
+ let preset = "default";
475
+ if (chosen !== "" && !isPath(chosen)) {
476
+ preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
477
+ } else {
478
+ const named = files.findLast(({ file }) => file.preset !== undefined);
479
+ if (named !== undefined)
480
+ preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
481
+ }
482
+ for (const { path, file } of files) {
483
+ applyFile(theme, file, path, warn);
484
+ sources.push(path);
485
+ }
486
+ return { theme, sources, preset };
286
487
  }
287
- function paint(stream, env = process2.env) {
488
+ var current;
489
+ var currentKey = "";
490
+ function activeTheme() {
491
+ const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
492
+ if (current === undefined || key !== currentKey) {
493
+ current = loadTheme();
494
+ currentKey = key;
495
+ }
496
+ return current;
497
+ }
498
+
499
+ // ../kit/src/style.ts
500
+ var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:" };
501
+ function takesControlCodes(stream, env = process6.env) {
502
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
503
+ }
504
+ function paint(stream, env = process6.env) {
288
505
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
289
506
  }
290
- function marked(mark, text, stream, detail, env = process2.env) {
507
+ function marked(mark, text, stream, detail, env = process6.env) {
291
508
  const colors = paint(stream, env);
292
- const { symbol, word, paint: tint } = MARKS[mark];
293
- const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
509
+ let head = MARK_WORDS[mark];
510
+ if (takesControlCodes(stream, env)) {
511
+ const { theme } = activeTheme();
512
+ head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
513
+ }
294
514
  return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
295
515
  }
296
516
  function warn(text, detail) {
297
- console.error(marked("warn", text, process2.stderr, detail));
298
- }
299
- var STATUSES = {
300
- passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
301
- failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
302
- running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
303
- queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
304
- skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
517
+ console.error(marked("warn", text, process6.stderr, detail));
518
+ }
519
+ function role(name, stream, env = process6.env) {
520
+ const colors = paint(stream, env);
521
+ return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
522
+ }
523
+ var STATUS_WORDS = {
524
+ passed: ["passed", "success", "succeeded", "ok"],
525
+ failed: ["failed", "failure", "error", "errored"],
526
+ running: ["running", "in_progress", "started", "holding"],
527
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
528
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
305
529
  };
306
- var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
530
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
307
531
 
308
532
  // ../kit/src/format.ts
309
533
  function upTo(text, separator) {
@@ -318,15 +542,18 @@ var ESCAPE = String.fromCharCode(27);
318
542
  function textWidth(text) {
319
543
  return Bun.stringWidth(text);
320
544
  }
321
- function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
545
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
322
546
  const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
547
+ if (outputMode(stream, env) === "agent")
548
+ return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
549
+ `);
323
550
  const widths = [];
324
551
  for (const row of cells) {
325
552
  for (const [index, cell] of row.entries())
326
553
  widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
327
554
  }
328
555
  const shown = fit === undefined ? cells : narrow(cells, widths, fit);
329
- const colors = paint(process3.stdout);
556
+ const colors = paint(stream);
330
557
  const lines = shown.map((row) => row.map((cell, index) => {
331
558
  const width = widths[index] ?? 0;
332
559
  const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
@@ -334,7 +561,8 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
334
561
  return `${gap}${cell}`;
335
562
  return index === row.length - 1 ? cell : `${cell}${gap}`;
336
563
  }).join(" ").trimEnd());
337
- return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
564
+ const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
565
+ return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
338
566
  `);
339
567
  }
340
568
  function narrow(rows, widths, limit) {
@@ -353,32 +581,35 @@ function narrow(rows, widths, limit) {
353
581
  }
354
582
  return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
355
583
  }
584
+ function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
585
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
586
+ }
356
587
  function printJson(value) {
357
- console.log(JSON.stringify(value, undefined, 2));
588
+ console.log(jsonText(value));
358
589
  }
359
590
 
360
591
  // ../kit/src/help.ts
361
- import process4 from "process";
592
+ import process8 from "process";
362
593
  var OPTIONAL = /\[[^\]]+\]/g;
363
594
  var USAGE_PREFIX = /^usage:\s*/i;
364
595
  var FULL_STOP = /\.$/;
365
- function usageLine(usage, colors = paint(process4.stdout)) {
596
+ function usageLine(usage, colors = paint(process8.stdout)) {
366
597
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
367
598
  }
368
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
599
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
369
600
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
370
601
  `);
371
602
  }
372
- function exitRows(exits, colors = paint(process4.stdout)) {
603
+ function exitRows(exits, colors = paint(process8.stdout)) {
373
604
  if (exits.length === 0)
374
605
  return [];
375
606
  const width = Math.max(...exits.map(([code]) => String(code).length));
376
607
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
377
608
  }
378
- function replacesRows(replaces, colors = paint(process4.stdout)) {
379
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
609
+ function replacesRows(replaces, colors = paint(process8.stdout)) {
610
+ return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
380
611
  }
381
- function wantsHelpJson(env = process4.env) {
612
+ function wantsHelpJson(env = process8.env) {
382
613
  return env.KIT_HELP === "json";
383
614
  }
384
615
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -397,12 +628,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
397
628
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
398
629
  };
399
630
  }
400
- function exampleRows(examples, colors = paint(process4.stdout)) {
401
- if (examples.length === 0)
631
+ function exampleRows(examples, colors = paint(process8.stdout)) {
632
+ if (examples.length === 0 || outputMode() === "agent")
402
633
  return [];
403
634
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
404
635
  }
405
- function optionRows(options, colors = paint(process4.stdout)) {
636
+ function optionRows(options, colors = paint(process8.stdout)) {
406
637
  const rows = Object.entries(options).map(([name, option]) => {
407
638
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
408
639
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -465,7 +696,6 @@ var DASHES = /^-+/;
465
696
  function jsonOption(holds) {
466
697
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
467
698
  }
468
-
469
699
  class Exit extends Error {
470
700
  code;
471
701
  hint;
@@ -509,7 +739,7 @@ var OUTPUT_OPTIONS = {
509
739
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
510
740
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
511
741
  };
512
- function applyOutput(color, plain, env = process5.env) {
742
+ function applyOutput(color, plain, env = process9.env) {
513
743
  const when = plain === true ? "never" : color ?? "auto";
514
744
  if (when === "auto")
515
745
  return;
@@ -680,7 +910,7 @@ function nearestOption(message, options, allowNegative) {
680
910
  }
681
911
  // ../kit/src/process.ts
682
912
  import { constants } from "os";
683
- import process6 from "process";
913
+ import process10 from "process";
684
914
  var KILL_GRACE_MS = 2000;
685
915
  function exitCodeOf(code, signal) {
686
916
  if (code !== null)
@@ -700,7 +930,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
700
930
  return;
701
931
  try {
702
932
  if (grouped)
703
- process6.kill(-proc.pid, killing);
933
+ process10.kill(-proc.pid, killing);
704
934
  else
705
935
  proc.kill(killing);
706
936
  } catch {}
@@ -774,15 +1004,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
774
1004
  var RESET_STYLE = `${ESC}[0m`;
775
1005
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
776
1006
  // ../kit/src/cli.ts
777
- import { readFileSync, realpathSync } from "fs";
778
- import { dirname as dirname2, join as join2 } from "path";
779
- import process8 from "process";
1007
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
1008
+ import { dirname as dirname3, join as join5 } from "path";
1009
+ import process12 from "process";
780
1010
 
781
1011
  // ../kit/src/usage.ts
782
1012
  import { appendFileSync, mkdirSync } from "fs";
783
- import { homedir } from "os";
784
- import { dirname, isAbsolute, join } from "path";
785
- import process7 from "process";
1013
+ import { homedir as homedir3 } from "os";
1014
+ import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1015
+ import process11 from "process";
786
1016
 
787
1017
  // ../kit/src/logs.ts
788
1018
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -796,14 +1026,14 @@ var usageError;
796
1026
  function noteUsageError(message) {
797
1027
  usageError = message;
798
1028
  }
799
- function stateHome(env = process7.env) {
1029
+ function stateHome(env = process11.env) {
800
1030
  const dir = env.XDG_STATE_HOME;
801
- return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
1031
+ return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
802
1032
  }
803
- function usagePath(env = process7.env) {
804
- return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
1033
+ function usagePath(env = process11.env) {
1034
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
805
1035
  }
806
- function usageRecorded(env = process7.env) {
1036
+ function usageRecorded(env = process11.env) {
807
1037
  const off = env.KAYNOOO_CLI_NO_USAGE;
808
1038
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
809
1039
  }
@@ -817,12 +1047,12 @@ function usageEntry(bin, command, argv, code, now = new Date) {
817
1047
  usageError = undefined;
818
1048
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
819
1049
  }
820
- function recordUsage(entry, env = process7.env) {
1050
+ function recordUsage(entry, env = process11.env) {
821
1051
  if (!usageRecorded(env))
822
1052
  return;
823
1053
  try {
824
1054
  const path = usagePath(env);
825
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
1055
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
826
1056
  appendFileSync(path, `${JSON.stringify(entry)}
827
1057
  `, { mode: 384 });
828
1058
  } catch {}
@@ -908,8 +1138,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
908
1138
  `);
909
1139
  }
910
1140
  function printError(prefix, message, hint, cause) {
911
- const colors = paint(process8.stderr);
912
- const styled = takesControlCodes(process8.stderr);
1141
+ const colors = paint(process12.stderr);
1142
+ const styled = takesControlCodes(process12.stderr);
913
1143
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
914
1144
  const under = (label, text, tint) => text === undefined ? "" : `
915
1145
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -952,11 +1182,11 @@ async function dispatch(level, typed, { version, redact }) {
952
1182
  }
953
1183
  }
954
1184
  if (name === undefined && level.path.length > 1) {
955
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
1185
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stderr));
956
1186
  return 2;
957
1187
  }
958
1188
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
959
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
1189
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stdout));
960
1190
  return 0;
961
1191
  }
962
1192
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1073,17 +1303,17 @@ async function printCandidates(found) {
1073
1303
  return 0;
1074
1304
  }
1075
1305
  function packageVersion(entry = Bun.main) {
1076
- for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1306
+ for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1077
1307
  try {
1078
- const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
1308
+ const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
1079
1309
  if (typeof version === "string")
1080
1310
  return version;
1081
1311
  } catch {}
1082
- if (dirname2(dir) === dir)
1312
+ if (dirname3(dir) === dir)
1083
1313
  return "0.0.0";
1084
1314
  }
1085
1315
  }
1086
- async function runCli(cli, argv = process8.argv.slice(2)) {
1316
+ async function runCli(cli, argv = process12.argv.slice(2)) {
1087
1317
  const version = cli.version ?? packageVersion();
1088
1318
  if (argv[0] === COMPLETE)
1089
1319
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -1110,7 +1340,7 @@ function commandPath(scope, argv) {
1110
1340
  }
1111
1341
  return path.length === 0 ? undefined : path.join(" ");
1112
1342
  }
1113
- async function runMain({ name, version, run, redact, usage }, argv = process8.argv.slice(2)) {
1343
+ async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1114
1344
  if (argv[0] === COMPLETE)
1115
1345
  return printCandidates(leafCandidates(run, argv.slice(1)));
1116
1346
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1130,6 +1360,8 @@ async function runMain({ name, version, run, redact, usage }, argv = process8.ar
1130
1360
  }
1131
1361
  return code;
1132
1362
  }
1363
+ // ../kit/src/folders.ts
1364
+ var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1133
1365
  // ../kit/src/limit.ts
1134
1366
  function limitOptions(fallback) {
1135
1367
  return {
@@ -1158,8 +1390,8 @@ var {Glob } = globalThis.Bun;
1158
1390
  var SESSION_FILES = new Glob("*.json");
1159
1391
  var ACCOUNT_DIRS = new Glob("*/sessions");
1160
1392
  // src/hotspots.ts
1161
- import { join as join4 } from "path";
1162
- import process10 from "process";
1393
+ import { join as join7 } from "path";
1394
+ import process14 from "process";
1163
1395
 
1164
1396
  // src/churn.ts
1165
1397
  var SOURCE = /\.(?:[cm]?[jt]sx?|vue|svelte|astro|kay|py|go|rs|rb|php|java|kt|swift|cs|c|cc|cpp|h|hpp|scala|dart|lua|sh|zsh|fish)$/;
@@ -1200,11 +1432,10 @@ async function churnSince(cwd, since, { bulk, halfLifeMs, now = Date.now() }) {
1200
1432
  }
1201
1433
 
1202
1434
  // src/files.ts
1203
- import { existsSync, readdirSync, statSync } from "fs";
1204
- import { join as join3, relative } from "path";
1435
+ import { existsSync as existsSync3, readdirSync, statSync as statSync2 } from "fs";
1436
+ import { join as join6, relative } from "path";
1205
1437
  var MAX_BYTES = 2000000;
1206
1438
  var SNIFF_BYTES = 8000;
1207
- var SKIPPED = new Set(["node_modules", "dist", "build", "vendor", "target", "coverage"]);
1208
1439
  function walk(dir, found) {
1209
1440
  let entries;
1210
1441
  try {
@@ -1213,21 +1444,21 @@ function walk(dir, found) {
1213
1444
  return found;
1214
1445
  }
1215
1446
  for (const entry of entries) {
1216
- if (entry.name.startsWith(".") || SKIPPED.has(entry.name))
1447
+ if (entry.name.startsWith(".") || SKIPPED_FOLDERS.has(entry.name))
1217
1448
  continue;
1218
1449
  if (entry.isDirectory())
1219
- walk(join3(dir, entry.name), found);
1450
+ walk(join6(dir, entry.name), found);
1220
1451
  else if (entry.isFile())
1221
- found.push(join3(dir, entry.name));
1452
+ found.push(join6(dir, entry.name));
1222
1453
  }
1223
1454
  return found;
1224
1455
  }
1225
1456
  async function listFiles(paths, cwd) {
1226
1457
  const listed = await runCommand(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...paths], { cwd });
1227
1458
  if (listed.code === 0)
1228
- return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync(join3(cwd, path))).sort();
1229
- const roots = paths.length === 0 ? [cwd] : paths.map((path) => join3(cwd, path));
1230
- return roots.flatMap((root) => statSync(root, { throwIfNoEntry: false })?.isFile() === true ? [root] : walk(root, [])).map((path) => relative(cwd, path)).sort();
1459
+ return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync3(join6(cwd, path))).sort();
1460
+ const roots = paths.length === 0 ? [cwd] : paths.map((path) => join6(cwd, path));
1461
+ return roots.flatMap((root) => statSync2(root, { throwIfNoEntry: false })?.isFile() === true ? [root] : walk(root, [])).map((path) => relative(cwd, path)).sort();
1231
1462
  }
1232
1463
  async function readText(path) {
1233
1464
  const file = Bun.file(path);
@@ -1310,12 +1541,14 @@ var OPTIONS = {
1310
1541
  all: { type: "boolean", short: "a", description: "keep test files and generated files" },
1311
1542
  json: jsonOption("[{rank, path, score, churn, recent, complexity, worst, lines}], never cut unless --limit is given")
1312
1543
  };
1544
+ var HOT = 0.66;
1545
+ var WARM = 0.33;
1313
1546
  async function hotspots(args) {
1314
1547
  const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["[dir]"], replaces: "guessing which files are worth splitting first", examples: ["hotspots", 'hotspots src --since "3 months ago" --limit 10'] });
1315
1548
  if (positionals.length > 1)
1316
1549
  badUsage("give one folder");
1317
1550
  const count = limitOf(values, DEFAULT_COUNT);
1318
- const cwd = process10.cwd();
1551
+ const cwd = process14.cwd();
1319
1552
  const bulk = Number(values.bulk ?? DEFAULT_BULK);
1320
1553
  if (!Number.isInteger(bulk) || bulk < 1)
1321
1554
  badUsage(`--bulk takes a number of files, not ${values.bulk}`);
@@ -1328,7 +1561,7 @@ async function hotspots(args) {
1328
1561
  const touched = churn.get(path);
1329
1562
  if (touched === undefined || values.all !== true && !isCandidate(path))
1330
1563
  continue;
1331
- const text = await readText(join4(cwd, path));
1564
+ const text = await readText(join7(cwd, path));
1332
1565
  if (text === undefined || values.all !== true && isGenerated(text))
1333
1566
  continue;
1334
1567
  const complexity = complexityOf(text);
@@ -1346,7 +1579,15 @@ async function hotspots(args) {
1346
1579
  printJson(shown);
1347
1580
  return 0;
1348
1581
  }
1349
- console.log(table([["rank", "score", "churn", "recent", "complexity", "lines", "file", "most complex declaration"], ...shown.map((row) => [row.rank, row.score, row.churn, row.recent, row.complexity, row.lines, row.path, row.worst === undefined ? "" : `${row.worst.name} (${row.worst.complexity}, line ${row.worst.line})`].map(String))], { header: true, align: ["right", "right", "right", "right", "right", "right", "left", "left"] }));
1582
+ const colors = paint(process14.stdout);
1583
+ const path = role("path", process14.stdout);
1584
+ const top = shown.reduce((highest, row) => Math.max(highest, row.score), 0);
1585
+ const heat = (score, text) => {
1586
+ if (top > 0 && score >= top * HOT)
1587
+ return colors.red(text);
1588
+ return top > 0 && score >= top * WARM ? colors.yellow(text) : text;
1589
+ };
1590
+ console.log(table([["rank", "score", "churn", "recent", "complexity", "lines", "file", "most complex declaration"], ...shown.map((row) => [colors.dim(String(row.rank)), heat(row.score, String(row.score)), ...[row.churn, row.recent, row.complexity, row.lines].map(String), path(row.path), row.worst === undefined ? "" : `${row.worst.name} (${row.worst.complexity}, line ${row.worst.line})`])], { header: true, align: ["right", "right", "right", "right", "right", "right", "left", "left"] }));
1350
1591
  if (footer !== undefined)
1351
1592
  console.log(footer);
1352
1593
  return 0;
@@ -1354,8 +1595,8 @@ async function hotspots(args) {
1354
1595
 
1355
1596
  // src/peek.ts
1356
1597
  import { realpathSync as realpathSync2 } from "fs";
1357
- import { isAbsolute as isAbsolute2, join as join5, relative as relative2, resolve, sep } from "path";
1358
- import process11 from "process";
1598
+ import { isAbsolute as isAbsolute2, join as join8, relative as relative2, resolve as resolve3, sep } from "path";
1599
+ import process15 from "process";
1359
1600
 
1360
1601
  // src/source.ts
1361
1602
  var LOCATION = /^(?:\.\/)?([^\s:()]+)(?::(\d+)(?::\d+)?|\((\d+),\d+\))(?=[:\s)]|$)/;
@@ -1563,13 +1804,13 @@ function cut(text) {
1563
1804
  return text.length > LONGEST_LINE ? `${text.slice(0, LONGEST_LINE - 1)}\u2026` : text;
1564
1805
  }
1565
1806
  async function readableRoot() {
1566
- const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process11.cwd() });
1567
- return realpathSync2(ran.code === 0 ? ran.text.trim() : process11.cwd());
1807
+ const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process15.cwd() });
1808
+ return realpathSync2(ran.code === 0 ? ran.text.trim() : process15.cwd());
1568
1809
  }
1569
1810
  async function isOutside(path) {
1570
1811
  let real;
1571
1812
  try {
1572
- real = realpathSync2(resolve(process11.cwd(), path));
1813
+ real = realpathSync2(resolve3(process15.cwd(), path));
1573
1814
  } catch {
1574
1815
  return false;
1575
1816
  }
@@ -1583,7 +1824,7 @@ async function checkInside(path) {
1583
1824
  async function pipedSpans(text, context) {
1584
1825
  const spans = [];
1585
1826
  for (const [path, numbers] of locations(text)) {
1586
- const source = await isOutside(path) ? undefined : await readText(resolve(process11.cwd(), path));
1827
+ const source = await isOutside(path) ? undefined : await readText(resolve3(process15.cwd(), path));
1587
1828
  if (source !== undefined)
1588
1829
  spans.push(...spansAround(path, source.replace(TRAILING_NEWLINE2, "").split(`
1589
1830
  `).length, numbers, context));
@@ -1592,7 +1833,7 @@ async function pipedSpans(text, context) {
1592
1833
  }
1593
1834
  async function textOf(path) {
1594
1835
  await checkInside(path);
1595
- const text = await readText(resolve(process11.cwd(), path));
1836
+ const text = await readText(resolve3(process15.cwd(), path));
1596
1837
  if (text === undefined)
1597
1838
  fail(`cannot read ${path} (missing, binary or too large)`, 1);
1598
1839
  return text;
@@ -1650,8 +1891,8 @@ async function spanOf(target) {
1650
1891
  async function* sources(paths) {
1651
1892
  for (const path of paths)
1652
1893
  await checkInside(path);
1653
- for (const path of await listFiles(paths, process11.cwd())) {
1654
- const text = await readText(join5(process11.cwd(), path));
1894
+ for (const path of await listFiles(paths, process15.cwd())) {
1895
+ const text = await readText(join8(process15.cwd(), path));
1655
1896
  if (text !== undefined)
1656
1897
  yield { path, text };
1657
1898
  }
@@ -1751,8 +1992,8 @@ async function peek(args) {
1751
1992
  }
1752
1993
 
1753
1994
  // src/todo-scan.ts
1754
- import { join as join6 } from "path";
1755
- import process12 from "process";
1995
+ import { join as join9 } from "path";
1996
+ import process16 from "process";
1756
1997
 
1757
1998
  // src/todo.ts
1758
1999
  var COMMENT2 = /(?<![:\w/])\/\/|\/\*|<!--|(?:^|\s)(?:#|--)(?=\s)|^\s*\*(?=\s|$)/;
@@ -1844,11 +2085,11 @@ function printLines(lines, footer) {
1844
2085
  }
1845
2086
  async function todoScan(args) {
1846
2087
  const { values, positionals } = parse(args, USAGE3, OPTIONS3, { positionals: ["[path...]"], replaces: "grep -rn TODO, then opening each issue it names", examples: ["todo-scan src", ["todo-scan --stale", "only the comments naming a closed issue"]] });
1847
- const cwd = process12.cwd();
2088
+ const cwd = process16.cwd();
1848
2089
  const limit = limitOf(values, LIST_LIMIT);
1849
2090
  const marks = [];
1850
2091
  for (const path of await listFiles(positionals, cwd)) {
1851
- const text = await readText(join6(cwd, path));
2092
+ const text = await readText(join9(cwd, path));
1852
2093
  if (text !== undefined)
1853
2094
  marks.push(...marksIn(text, path));
1854
2095
  }
@@ -1875,7 +2116,7 @@ async function todoScan(args) {
1875
2116
  }
1876
2117
 
1877
2118
  // src/cli.ts
1878
- process13.exitCode = await runCli({
2119
+ process17.exitCode = await runCli({
1879
2120
  name: "src",
1880
2121
  about: "reads and ranks the source of a folder: line spans, TODO comments and the files worth splitting",
1881
2122
  replaces: "sed -n N,Mp, grep -n chains and grep -rn TODO",