@kaynooo/cli-view 0.2.1 → 0.3.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.
Files changed (2) hide show
  1. package/dist/view.js +307 -74
  2. package/package.json +2 -2
package/dist/view.js CHANGED
@@ -2,13 +2,34 @@
2
2
  // @bun
3
3
 
4
4
  // src/view.ts
5
- import process10 from "process";
5
+ import process15 from "process";
6
6
  // ../kit/src/args.ts
7
- import process5 from "process";
7
+ import process10 from "process";
8
8
  import { parseArgs } from "util";
9
9
 
10
- // ../kit/src/style.ts
10
+ // ../kit/src/format.ts
11
+ import process7 from "process";
12
+
13
+ // ../kit/src/mode.ts
11
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";
12
33
 
13
34
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
14
35
  function x(s) {
@@ -271,32 +292,230 @@ function le(i = {}) {
271
292
  }
272
293
  var t = le();
273
294
 
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: {}
334
+ };
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 };
487
+ }
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
+
274
499
  // ../kit/src/style.ts
275
- function takesControlCodes(stream, env = process2.env) {
276
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
500
+ function takesControlCodes(stream, env = process6.env) {
501
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
277
502
  }
278
- function paint(stream, env = process2.env) {
503
+ function paint(stream, env = process6.env) {
279
504
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
280
505
  }
281
- var ROLES = {
282
- accent: (colors) => colors.cyan,
283
- id: (colors) => colors.yellow,
284
- path: (colors) => colors.blue,
285
- label: (colors) => colors.dim,
286
- value: (colors) => colors.bold
287
- };
288
- function role(name, stream, env = process2.env) {
289
- return ROLES[name](paint(stream, env));
290
- }
291
- var STATUSES = {
292
- passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
293
- failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
294
- running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
295
- queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
296
- skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
506
+ function role(name, stream, env = process6.env) {
507
+ const colors = paint(stream, env);
508
+ return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
509
+ }
510
+ var STATUS_WORDS = {
511
+ passed: ["passed", "success", "succeeded", "ok"],
512
+ failed: ["failed", "failure", "error", "errored"],
513
+ running: ["running", "in_progress", "started", "holding"],
514
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
515
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
297
516
  };
298
- var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
299
- function link(text, url, stream, env = process2.env) {
517
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
518
+ function link(text, url, stream, env = process6.env) {
300
519
  if (takesControlCodes(stream, env))
301
520
  return `\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`;
302
521
  return text === url ? text : `${text} (${url})`;
@@ -311,29 +530,35 @@ var ESCAPE = String.fromCharCode(27);
311
530
  function textWidth(text) {
312
531
  return Bun.stringWidth(text);
313
532
  }
533
+ function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
534
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
535
+ }
536
+ function printJson(value) {
537
+ console.log(jsonText(value));
538
+ }
314
539
 
315
540
  // ../kit/src/help.ts
316
- import process3 from "process";
541
+ import process8 from "process";
317
542
  var OPTIONAL = /\[[^\]]+\]/g;
318
543
  var USAGE_PREFIX = /^usage:\s*/i;
319
544
  var FULL_STOP = /\.$/;
320
- function usageLine(usage, colors = paint(process3.stdout)) {
545
+ function usageLine(usage, colors = paint(process8.stdout)) {
321
546
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
322
547
  }
323
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces, exits = [] } = {}) {
548
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
324
549
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
325
550
  `);
326
551
  }
327
- function exitRows(exits, colors = paint(process3.stdout)) {
552
+ function exitRows(exits, colors = paint(process8.stdout)) {
328
553
  if (exits.length === 0)
329
554
  return [];
330
555
  const width = Math.max(...exits.map(([code]) => String(code).length));
331
556
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
332
557
  }
333
- function replacesRows(replaces, colors = paint(process3.stdout)) {
334
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
558
+ function replacesRows(replaces, colors = paint(process8.stdout)) {
559
+ return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
335
560
  }
336
- function wantsHelpJson(env = process3.env) {
561
+ function wantsHelpJson(env = process8.env) {
337
562
  return env.KIT_HELP === "json";
338
563
  }
339
564
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -352,12 +577,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
352
577
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
353
578
  };
354
579
  }
355
- function exampleRows(examples, colors = paint(process3.stdout)) {
356
- if (examples.length === 0)
580
+ function exampleRows(examples, colors = paint(process8.stdout)) {
581
+ if (examples.length === 0 || outputMode() === "agent")
357
582
  return [];
358
583
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
359
584
  }
360
- function optionRows(options, colors = paint(process3.stdout)) {
585
+ function optionRows(options, colors = paint(process8.stdout)) {
361
586
  const rows = Object.entries(options).map(([name, option]) => {
362
587
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
363
588
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -392,7 +617,7 @@ function closest(name, names) {
392
617
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
393
618
  }
394
619
  // ../kit/src/input.ts
395
- import process4 from "process";
620
+ import process9 from "process";
396
621
  var WHOLE = /^\d+$/;
397
622
  function wholeNumber(value, name, fallback, min = 1) {
398
623
  if (value === undefined)
@@ -404,7 +629,7 @@ function wholeNumber(value, name, fallback, min = 1) {
404
629
  }
405
630
  async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
406
631
  if (path === "-") {
407
- if (process4.stdin.isTTY)
632
+ if (process9.stdin.isTTY)
408
633
  fail(noStdin);
409
634
  return Bun.stdin.text();
410
635
  }
@@ -416,6 +641,9 @@ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
416
641
 
417
642
  // ../kit/src/args.ts
418
643
  var DASHES = /^-+/;
644
+ function jsonOption(holds) {
645
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
646
+ }
419
647
  class Exit extends Error {
420
648
  code;
421
649
  hint;
@@ -459,7 +687,7 @@ var OUTPUT_OPTIONS = {
459
687
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
460
688
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
461
689
  };
462
- function applyOutput(color, plain, env = process5.env) {
690
+ function applyOutput(color, plain, env = process10.env) {
463
691
  const when = plain === true ? "never" : color ?? "auto";
464
692
  if (when === "auto")
465
693
  return;
@@ -634,15 +862,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
634
862
  var RESET_STYLE = `${ESC}[0m`;
635
863
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
636
864
  // ../kit/src/cli.ts
637
- import { readFileSync, realpathSync } from "fs";
638
- import { dirname as dirname2, join as join2 } from "path";
639
- import process7 from "process";
865
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
866
+ import { dirname as dirname3, join as join5 } from "path";
867
+ import process12 from "process";
640
868
 
641
869
  // ../kit/src/usage.ts
642
870
  import { appendFileSync, mkdirSync } from "fs";
643
- import { homedir } from "os";
644
- import { dirname, isAbsolute, join } from "path";
645
- import process6 from "process";
871
+ import { homedir as homedir3 } from "os";
872
+ import { dirname as dirname2, isAbsolute, join as join4 } from "path";
873
+ import process11 from "process";
646
874
 
647
875
  // ../kit/src/logs.ts
648
876
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -656,14 +884,14 @@ var usageError;
656
884
  function noteUsageError(message) {
657
885
  usageError = message;
658
886
  }
659
- function stateHome(env = process6.env) {
887
+ function stateHome(env = process11.env) {
660
888
  const dir = env.XDG_STATE_HOME;
661
- return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
889
+ return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
662
890
  }
663
- function usagePath(env = process6.env) {
664
- return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
891
+ function usagePath(env = process11.env) {
892
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
665
893
  }
666
- function usageRecorded(env = process6.env) {
894
+ function usageRecorded(env = process11.env) {
667
895
  const off = env.KAYNOOO_CLI_NO_USAGE;
668
896
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
669
897
  }
@@ -677,12 +905,12 @@ function usageEntry(bin, command, argv, code, now = new Date) {
677
905
  usageError = undefined;
678
906
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
679
907
  }
680
- function recordUsage(entry, env = process6.env) {
908
+ function recordUsage(entry, env = process11.env) {
681
909
  if (!usageRecorded(env))
682
910
  return;
683
911
  try {
684
912
  const path = usagePath(env);
685
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
913
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
686
914
  appendFileSync(path, `${JSON.stringify(entry)}
687
915
  `, { mode: 384 });
688
916
  } catch {}
@@ -695,8 +923,8 @@ var LEVEL_OPTIONS = {
695
923
  };
696
924
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
697
925
  function printError(prefix, message, hint, cause) {
698
- const colors = paint(process7.stderr);
699
- const styled = takesControlCodes(process7.stderr);
926
+ const colors = paint(process12.stderr);
927
+ const styled = takesControlCodes(process12.stderr);
700
928
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
701
929
  const under = (label, text, tint) => text === undefined ? "" : `
702
930
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -715,7 +943,7 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
715
943
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
716
944
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
717
945
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
718
- if (error instanceof UsageError)
946
+ if (error instanceof Exit && error.code === 2)
719
947
  noteUsageError(error.message);
720
948
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
721
949
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
@@ -779,17 +1007,17 @@ async function printCandidates(found) {
779
1007
  return 0;
780
1008
  }
781
1009
  function packageVersion(entry = Bun.main) {
782
- for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1010
+ for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
783
1011
  try {
784
- const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
1012
+ const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
785
1013
  if (typeof version === "string")
786
1014
  return version;
787
1015
  } catch {}
788
- if (dirname2(dir) === dir)
1016
+ if (dirname3(dir) === dir)
789
1017
  return "0.0.0";
790
1018
  }
791
1019
  }
792
- async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
1020
+ async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
793
1021
  if (argv[0] === COMPLETE)
794
1022
  return printCandidates(leafCandidates(run, argv.slice(1)));
795
1023
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1209,8 +1437,8 @@ function renderMarkdown(source, { theme, width }) {
1209
1437
  }
1210
1438
 
1211
1439
  // src/theme.ts
1212
- import process9 from "process";
1213
- function themeFor(stream = process9.stdout, env = process9.env) {
1440
+ import process14 from "process";
1441
+ function themeFor(stream = process14.stdout, env = process14.env) {
1214
1442
  const colors = paint(stream, env);
1215
1443
  const accent = role("accent", stream, env);
1216
1444
  const path = role("path", stream, env);
@@ -1249,7 +1477,8 @@ var OPTIONS = {
1249
1477
  lang: { type: "string", short: "l", description: "show the text as code in this language (ts, json, yaml, sh...)" },
1250
1478
  lines: { type: "boolean", description: "number the lines of code (--no-lines turns it off; on a terminal by default)" },
1251
1479
  width: { type: "string", short: "w", description: "columns to wrap to, instead of the terminal's" },
1252
- pager: { type: "boolean", description: "page a long output on a terminal (--no-pager turns it off)" }
1480
+ pager: { type: "boolean", description: "page a long output on a terminal (--no-pager turns it off)" },
1481
+ json: jsonOption("{kind: code, diff or markdown, language, text}, the text rendered without colour")
1253
1482
  };
1254
1483
  async function page(text) {
1255
1484
  try {
@@ -1260,7 +1489,7 @@ async function page(text) {
1260
1489
  } catch {}
1261
1490
  await pager.exited;
1262
1491
  } catch {
1263
- process10.stdout.write(text);
1492
+ process15.stdout.write(text);
1264
1493
  }
1265
1494
  }
1266
1495
  async function main(args) {
@@ -1273,26 +1502,30 @@ async function main(args) {
1273
1502
  const text = await readInput(path, { noStdin: "give a file, or pipe the text on stdin" });
1274
1503
  if (text.trim() === "")
1275
1504
  fail("nothing to show", 1);
1276
- const width = wholeNumber(values.width, "width", process10.stdout.isTTY === true ? process10.stdout.columns || DEFAULT_WIDTH : DEFAULT_WIDTH, 20);
1277
- const theme = themeFor(process10.stdout);
1505
+ const width = wholeNumber(values.width, "width", process15.stdout.isTTY === true ? process15.stdout.columns || DEFAULT_WIDTH : DEFAULT_WIDTH, 20);
1506
+ const theme = themeFor(process15.stdout);
1278
1507
  const language = values.lang === undefined ? languageOf(path) : languageOf(values.lang);
1279
1508
  if (values.lang !== undefined && language === undefined)
1280
1509
  badUsage(`unknown language ${values.lang}`);
1281
1510
  const forced = values.diff === true || values.markdown === true;
1282
1511
  const isCode = values.lang !== undefined || !forced && language !== undefined && !MARKDOWN_FILE.test(path) && !DIFF_FILE.test(path);
1283
1512
  const isDiff = !isCode && (values.diff === true || values.markdown !== true && !MARKDOWN_FILE.test(path) && (DIFF_FILE.test(path) || looksLikeDiff(text)));
1284
- let shown;
1285
- if (isCode)
1286
- shown = renderCode(text, language, theme, values.lines ?? process10.stdout.isTTY === true);
1287
- else if (isDiff)
1288
- shown = renderDiff(text, theme);
1289
- else
1290
- shown = renderMarkdown(text, { theme, width });
1291
- if (process10.stdout.isTTY === true && values.pager !== false && shown.split(`
1292
- `).length > (process10.stdout.rows || 24))
1513
+ const kind = isDiff ? "diff" : "markdown";
1514
+ function render(as, numbered) {
1515
+ if (isCode)
1516
+ return renderCode(text, language, as, numbered);
1517
+ return isDiff ? renderDiff(text, as) : renderMarkdown(text, { theme: as, width });
1518
+ }
1519
+ if (values.json === true) {
1520
+ printJson({ kind: isCode ? "code" : kind, language: isCode ? language ?? null : null, text: stripAnsi(render(themeFor({ isTTY: false }), values.lines ?? false)) });
1521
+ return 0;
1522
+ }
1523
+ const shown = render(theme, values.lines ?? process15.stdout.isTTY === true);
1524
+ if (process15.stdout.isTTY === true && values.pager !== false && shown.split(`
1525
+ `).length > (process15.stdout.rows || 24))
1293
1526
  await page(shown);
1294
1527
  else
1295
- process10.stdout.write(shown);
1528
+ process15.stdout.write(shown);
1296
1529
  return 0;
1297
1530
  }
1298
- process10.exitCode = await runMain({ name: "view", run: main });
1531
+ process15.exitCode = await runMain({ name: "view", run: main });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-view",
3
3
  "type": "module",
4
- "version": "0.2.1",
4
+ "version": "0.3.0",
5
5
  "description": "view: markdown files and git diffs shown in the colours of the other @kaynooo CLIs, paged when long.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -35,6 +35,6 @@
35
35
  "view": "$npm_execpath src/view.ts"
36
36
  },
37
37
  "devDependencies": {
38
- "@kaynooo/cli-kit": "0.21.0"
38
+ "@kaynooo/cli-kit": "0.25.0"
39
39
  }
40
40
  }