@kaynooo/cli-view 0.1.0 → 0.1.1

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 +149 -88
  2. package/package.json +2 -2
package/dist/view.js CHANGED
@@ -2,10 +2,10 @@
2
2
  // @bun
3
3
 
4
4
  // src/view.ts
5
- import process6 from "process";
5
+ import process9 from "process";
6
6
 
7
7
  // ../kit/src/args.ts
8
- import process2 from "process";
8
+ import process4 from "process";
9
9
  import { parseArgs } from "util";
10
10
 
11
11
  // ../kit/src/style.ts
@@ -313,6 +313,55 @@ function textWidth(text) {
313
313
  return Bun.stringWidth(text);
314
314
  }
315
315
 
316
+ // ../kit/src/help.ts
317
+ import process2 from "process";
318
+ var OPTIONAL = /\[[^\]]+\]/g;
319
+ var USAGE_PREFIX = /^usage:\s*/i;
320
+ var FULL_STOP = /\.$/;
321
+ function usageLine(usage, colors = paint(process2.stdout)) {
322
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
323
+ }
324
+ function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
325
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
326
+ `);
327
+ }
328
+ function replacesRows(replaces, colors = paint(process2.stdout)) {
329
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
330
+ }
331
+ function wantsHelpJson(env = process2.env) {
332
+ return env.KIT_HELP === "json";
333
+ }
334
+ function description(usage, { examples = [], replaces } = {}) {
335
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
336
+ `);
337
+ const first = lines[0];
338
+ const colon = first.indexOf(": ");
339
+ const prose = lines[lines.indexOf("") + 1] ?? "";
340
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
341
+ return {
342
+ synopsis: colon === -1 ? first : first.slice(0, colon),
343
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
344
+ ...replaces === undefined ? {} : { replaces },
345
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
346
+ };
347
+ }
348
+ function exampleRows(examples, colors = paint(process2.stdout)) {
349
+ if (examples.length === 0)
350
+ return [];
351
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
352
+ }
353
+ function optionRows(options, colors = paint(process2.stdout)) {
354
+ const rows = Object.entries(options).map(([name, option]) => {
355
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
356
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
357
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
358
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
359
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
360
+ });
361
+ const width = Math.max(0, ...rows.map((row) => row.width));
362
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
363
+ }
364
+
316
365
  // ../kit/src/text.ts
317
366
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
318
367
  function stripAnsi(text) {
@@ -335,8 +384,31 @@ function closest(name, names) {
335
384
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
336
385
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
337
386
  }
387
+ // ../kit/src/input.ts
388
+ import process3 from "process";
389
+ var WHOLE = /^\d+$/;
390
+ function wholeNumber(value, name, fallback, min = 1) {
391
+ if (value === undefined)
392
+ return fallback;
393
+ const number = Number(value);
394
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
395
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
396
+ return number;
397
+ }
398
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
399
+ if (path === "-") {
400
+ if (process3.stdin.isTTY)
401
+ fail(noStdin);
402
+ return Bun.stdin.text();
403
+ }
404
+ const file = Bun.file(path);
405
+ if (!await file.exists())
406
+ fail(`no file ${path}`);
407
+ return file.text();
408
+ }
338
409
 
339
410
  // ../kit/src/args.ts
411
+ var DASHES = /^-+/;
340
412
  class Exit extends Error {
341
413
  code;
342
414
  hint;
@@ -376,58 +448,11 @@ class Completing {
376
448
  }
377
449
  }
378
450
  var completion = { active: false };
379
- var OPTIONAL = /\[[^\]]+\]/g;
380
- var USAGE_PREFIX = /^usage:\s*/i;
381
- var FULL_STOP = /\.$/;
382
- var DASHES = /^-+/;
383
- function usageLine(usage, colors = paint(process2.stdout)) {
384
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
385
- }
386
- function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
387
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
388
- `);
389
- }
390
- function replacesRows(replaces, colors = paint(process2.stdout)) {
391
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
392
- }
393
- function wantsHelpJson(env = process2.env) {
394
- return env.KIT_HELP === "json";
395
- }
396
- function description(usage, { examples = [], replaces } = {}) {
397
- const lines = usage.replace(USAGE_PREFIX, "").split(`
398
- `);
399
- const first = lines[0];
400
- const colon = first.indexOf(": ");
401
- const prose = lines[lines.indexOf("") + 1] ?? "";
402
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
403
- return {
404
- synopsis: colon === -1 ? first : first.slice(0, colon),
405
- summary: colon === -1 ? fallback : first.slice(colon + 2),
406
- ...replaces === undefined ? {} : { replaces },
407
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
408
- };
409
- }
410
- function exampleRows(examples, colors = paint(process2.stdout)) {
411
- if (examples.length === 0)
412
- return [];
413
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
414
- }
415
- function optionRows(options, colors = paint(process2.stdout)) {
416
- const rows = Object.entries(options).map(([name, option]) => {
417
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
418
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
419
- const placeholder = option.optional === undefined ? named : `[${named}]`;
420
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
421
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
422
- });
423
- const width = Math.max(0, ...rows.map((row) => row.width));
424
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
425
- }
426
451
  var OUTPUT_OPTIONS = {
427
452
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
428
453
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
429
454
  };
430
- function applyOutput(color, plain, env = process2.env) {
455
+ function applyOutput(color, plain, env = process4.env) {
431
456
  const when = plain === true ? "never" : color ?? "auto";
432
457
  if (when === "auto")
433
458
  return;
@@ -584,41 +609,73 @@ function nearestOption(message, options, allowNegative) {
584
609
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
585
610
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
586
611
  }
587
- var WHOLE = /^\d+$/;
588
- function wholeNumber(value, name, fallback, min = 1) {
589
- if (value === undefined)
590
- return fallback;
591
- const number = Number(value);
592
- if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
593
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
594
- return number;
595
- }
596
- async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
597
- if (path === "-") {
598
- if (process2.stdin.isTTY)
599
- fail(noStdin);
600
- return Bun.stdin.text();
601
- }
602
- const file = Bun.file(path);
603
- if (!await file.exists())
604
- fail(`no file ${path}`);
605
- return file.text();
606
- }
607
612
  // ../kit/src/progress.ts
608
613
  var ESC = String.fromCharCode(27);
609
614
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
610
615
  var RESET_STYLE = `${ESC}[0m`;
611
616
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
612
617
  // ../kit/src/cli.ts
613
- import process3 from "process";
618
+ import process6 from "process";
619
+
620
+ // ../kit/src/usage.ts
621
+ import { appendFileSync, mkdirSync } from "fs";
622
+ import { homedir } from "os";
623
+ import { dirname, isAbsolute, join } from "path";
624
+ import process5 from "process";
625
+
626
+ // ../kit/src/logs.ts
627
+ var DAY_MS = 24 * 60 * 60 * 1000;
628
+ var CLI_FOLDER = "kaynooo-cli";
629
+
630
+ // ../kit/src/usage.ts
631
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
632
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
633
+ var LONGEST_NAME = 40;
634
+ var usageError;
635
+ function noteUsageError(message) {
636
+ usageError = message;
637
+ }
638
+ function stateHome(env = process5.env) {
639
+ const dir = env.XDG_STATE_HOME;
640
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
641
+ }
642
+ function usagePath(env = process5.env) {
643
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
644
+ }
645
+ function usageRecorded(env = process5.env) {
646
+ const off = env.KAYNOOO_CLI_NO_USAGE;
647
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
648
+ }
649
+ function flagNames(argv) {
650
+ const end = argv.indexOf("--");
651
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
652
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
653
+ }
654
+ function usageEntry(bin, command, argv, code, now = new Date) {
655
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
656
+ usageError = undefined;
657
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
658
+ }
659
+ function recordUsage(entry, env = process5.env) {
660
+ if (!usageRecorded(env))
661
+ return;
662
+ try {
663
+ const path = usagePath(env);
664
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
665
+ appendFileSync(path, `${JSON.stringify(entry)}
666
+ `, { mode: 384 });
667
+ } catch {}
668
+ }
669
+
670
+ // ../kit/src/cli.ts
614
671
  var LEVEL_OPTIONS = {
615
672
  ...OUTPUT_OPTIONS,
616
673
  help: { type: "boolean", short: "h", description: "show this help" }
617
674
  };
618
675
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
619
676
  function printError(prefix, message, hint, cause) {
620
- const colors = paint(process3.stderr);
621
- const styled = takesControlCodes(process3.stderr);
677
+ const colors = paint(process6.stderr);
678
+ const styled = takesControlCodes(process6.stderr);
622
679
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
623
680
  const under = (label, text, tint) => text === undefined ? "" : `
624
681
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -637,6 +694,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
637
694
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
638
695
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
639
696
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
697
+ if (error instanceof UsageError)
698
+ noteUsageError(error.message);
640
699
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
641
700
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
642
701
  return error instanceof Exit ? error.code : 1;
@@ -698,21 +757,23 @@ async function printCandidates(found) {
698
757
  console.log(line);
699
758
  return 0;
700
759
  }
701
- async function runMain({ name, version, run, redact }, argv = process3.argv.slice(2)) {
760
+ async function runMain({ name, version, run, redact, usage }, argv = process6.argv.slice(2)) {
702
761
  if (argv[0] === COMPLETE)
703
762
  return printCandidates(leafCandidates(run, argv.slice(1)));
704
763
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
705
764
  console.log(version);
706
765
  return 0;
707
766
  }
767
+ let code;
708
768
  try {
709
- return await run(argv);
769
+ code = await run(argv);
710
770
  } catch (error) {
711
- return reportThrown(name, error, redact, wantsJson(argv));
771
+ code = reportThrown(name, error, redact, wantsJson(argv));
712
772
  }
773
+ if (usage !== false)
774
+ recordUsage(usageEntry(name, undefined, argv, code));
775
+ return code;
713
776
  }
714
- // ../kit/src/logs.ts
715
- var DAY_MS = 24 * 60 * 60 * 1000;
716
777
  // ../kit/src/secrets.ts
717
778
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
718
779
  // ../kit/src/sessions.ts
@@ -720,7 +781,7 @@ var {Glob } = globalThis.Bun;
720
781
  var SESSION_FILES = new Glob("*.json");
721
782
  var ACCOUNT_DIRS = new Glob("*/sessions");
722
783
  // package.json
723
- var version = "0.1.0";
784
+ var version = "0.1.1";
724
785
 
725
786
  // src/diff.ts
726
787
  var TRAILING_NEWLINE = /\n$/;
@@ -936,8 +997,8 @@ function renderMarkdown(source, { theme, width }) {
936
997
  }
937
998
 
938
999
  // src/theme.ts
939
- import process5 from "process";
940
- function themeFor(stream = process5.stdout, env = process5.env) {
1000
+ import process8 from "process";
1001
+ function themeFor(stream = process8.stdout, env = process8.env) {
941
1002
  const colors = paint(stream, env);
942
1003
  const accent = role("accent", stream, env);
943
1004
  const path = role("path", stream, env);
@@ -982,7 +1043,7 @@ async function page(text) {
982
1043
  } catch {}
983
1044
  await pager.exited;
984
1045
  } catch {
985
- process6.stdout.write(text);
1046
+ process9.stdout.write(text);
986
1047
  }
987
1048
  }
988
1049
  async function main(args) {
@@ -995,15 +1056,15 @@ async function main(args) {
995
1056
  const text = await readInput(path, { noStdin: "give a file, or pipe the text on stdin" });
996
1057
  if (text.trim() === "")
997
1058
  fail("nothing to show", 1);
998
- const width = wholeNumber(values.width, "width", process6.stdout.isTTY === true ? process6.stdout.columns || DEFAULT_WIDTH : DEFAULT_WIDTH, 20);
999
- const theme = themeFor(process6.stdout);
1059
+ const width = wholeNumber(values.width, "width", process9.stdout.isTTY === true ? process9.stdout.columns || DEFAULT_WIDTH : DEFAULT_WIDTH, 20);
1060
+ const theme = themeFor(process9.stdout);
1000
1061
  const isDiff = values.diff === true || values.markdown !== true && !MARKDOWN_FILE.test(path) && (DIFF_FILE.test(path) || looksLikeDiff(text));
1001
1062
  const shown = isDiff ? renderDiff(text, theme) : renderMarkdown(text, { theme, width });
1002
- if (process6.stdout.isTTY === true && values.pager !== false && shown.split(`
1003
- `).length > (process6.stdout.rows || 24))
1063
+ if (process9.stdout.isTTY === true && values.pager !== false && shown.split(`
1064
+ `).length > (process9.stdout.rows || 24))
1004
1065
  await page(shown);
1005
1066
  else
1006
- process6.stdout.write(shown);
1067
+ process9.stdout.write(shown);
1007
1068
  return 0;
1008
1069
  }
1009
- process6.exitCode = await runMain({ name: "view", version, run: main });
1070
+ process9.exitCode = await runMain({ name: "view", version, 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.1.0",
4
+ "version": "0.1.1",
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.19.0"
38
+ "@kaynooo/cli-kit": "0.20.0"
39
39
  }
40
40
  }