@kaynooo/cli-probe 0.4.0 → 0.4.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/probe.js +95 -47
  2. package/package.json +2 -2
package/dist/probe.js CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
  // src/probe.ts
5
5
  import { isIP as isIP2 } from "net";
6
- import process14 from "process";
6
+ import process15 from "process";
7
7
  // ../kit/src/args.ts
8
8
  import process9 from "process";
9
9
  import { parseArgs } from "util";
@@ -350,6 +350,23 @@ var STATUS_WORDS = {
350
350
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
351
351
 
352
352
  // ../kit/src/format.ts
353
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
354
+ function formatSeconds(total) {
355
+ let rest = Math.max(0, Math.round(total));
356
+ const amounts = UNITS.map(([unit, size]) => {
357
+ const amount = Math.floor(rest / size);
358
+ rest -= amount * size;
359
+ return `${amount}${unit}`;
360
+ });
361
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
362
+ if (first === -1)
363
+ return "0s";
364
+ const next = amounts[first + 1];
365
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
366
+ }
367
+ function formatDuration(ms) {
368
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
369
+ }
353
370
  function upTo(text, separator) {
354
371
  const end = text.indexOf(separator);
355
372
  return end === -1 ? text : text.slice(0, end);
@@ -410,24 +427,20 @@ function printJson(value) {
410
427
 
411
428
  // ../kit/src/help.ts
412
429
  import process8 from "process";
413
- var OPTIONAL = /\[[^\]]+\]/g;
430
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
414
431
  var USAGE_PREFIX = /^usage:\s*/i;
415
432
  var FULL_STOP = /\.$/;
416
433
  function usageLine(usage, colors = paint(process8.stdout)) {
417
434
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
418
435
  }
419
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
420
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
436
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
437
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
421
438
  `);
422
439
  }
423
440
  function exitRows(exits, colors = paint(process8.stdout)) {
424
441
  if (exits.length === 0)
425
442
  return [];
426
- const width = Math.max(...exits.map(([code]) => String(code).length));
427
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
428
- }
429
- function replacesRows(replaces, colors = paint(process8.stdout)) {
430
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
443
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
431
444
  }
432
445
  function wantsHelpJson(env = process8.env) {
433
446
  return env.KIT_HELP === "json";
@@ -453,29 +466,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
453
466
  return [];
454
467
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
455
468
  }
469
+ var MAX_INLINE_CHOICES = 24;
456
470
  function optionRows(options, colors = paint(process8.stdout)) {
457
471
  const rows = Object.entries(options).map(([name, option]) => {
458
472
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
459
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
473
+ const choices = option.choices?.join("|");
474
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
475
+ const named = inline ? `<${choices}>` : "<value>";
460
476
  const placeholder = option.optional === undefined ? named : `[${named}]`;
461
477
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
462
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
478
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
479
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
463
480
  });
464
481
  const width = Math.max(0, ...rows.map((row) => row.width));
465
482
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
466
483
  }
467
484
 
468
485
  // ../kit/src/text.ts
469
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
470
486
  function distance(a, b) {
471
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
472
- for (const [i, left] of [...a].entries()) {
487
+ const left = [...a];
488
+ const right = [...b];
489
+ let before = [];
490
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
491
+ for (const [i, x] of left.entries()) {
473
492
  const current = [i + 1];
474
- for (const [j, right] of [...b].entries())
475
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
493
+ for (const [j, y] of right.entries()) {
494
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
495
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
496
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
497
+ current.push(cost);
498
+ }
499
+ before = previous;
476
500
  previous = current;
477
501
  }
478
- return previous[b.length] ?? 0;
502
+ return previous[right.length] ?? 0;
479
503
  }
480
504
  function closest(name, names) {
481
505
  const started = names.find((known) => known.startsWith(name));
@@ -746,13 +770,31 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
746
770
  // ../kit/src/cli.ts
747
771
  import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
748
772
  import { dirname as dirname3, join as join5 } from "path";
749
- import process12 from "process";
773
+ import process13 from "process";
774
+
775
+ // ../kit/src/notify.ts
776
+ import process11 from "process";
777
+ var NOTIFY_AFTER_MS = 1e4;
778
+ var CANCELLED = 130;
779
+ function base64(text) {
780
+ return Buffer.from(text).toString("base64");
781
+ }
782
+ function notification(title, body, env = process11.env) {
783
+ const id = `kit${process11.pid}`;
784
+ 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\\`];
785
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
786
+ }
787
+ function notifyEnd(command, code, ms, { stream = process11.stderr, env = process11.env } = {}) {
788
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
789
+ return;
790
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
791
+ }
750
792
 
751
793
  // ../kit/src/usage.ts
752
794
  import { appendFileSync, mkdirSync } from "fs";
753
795
  import { homedir as homedir3 } from "os";
754
796
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
755
- import process11 from "process";
797
+ import process12 from "process";
756
798
 
757
799
  // ../kit/src/logs.ts
758
800
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -766,14 +808,14 @@ var usageError;
766
808
  function noteUsageError(message) {
767
809
  usageError = message;
768
810
  }
769
- function stateHome(env = process11.env) {
811
+ function stateHome(env = process12.env) {
770
812
  const dir = env.XDG_STATE_HOME;
771
813
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
772
814
  }
773
- function usagePath(env = process11.env) {
815
+ function usagePath(env = process12.env) {
774
816
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
775
817
  }
776
- function usageRecorded(env = process11.env) {
818
+ function usageRecorded(env = process12.env) {
777
819
  const off = env.KAYNOOO_CLI_NO_USAGE;
778
820
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
779
821
  }
@@ -787,7 +829,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
787
829
  usageError = undefined;
788
830
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
789
831
  }
790
- function recordUsage(entry, env = process11.env) {
832
+ function recordUsage(entry, env = process12.env) {
791
833
  if (!usageRecorded(env))
792
834
  return;
793
835
  try {
@@ -805,8 +847,8 @@ var LEVEL_OPTIONS = {
805
847
  };
806
848
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
807
849
  function printError(prefix, message, hint, cause) {
808
- const colors = paint(process12.stderr);
809
- const styled = takesControlCodes(process12.stderr);
850
+ const colors = paint(process13.stderr);
851
+ const styled = takesControlCodes(process13.stderr);
810
852
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
811
853
  const under = (label, text, tint) => text === undefined ? "" : `
812
854
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -889,7 +931,11 @@ async function printCandidates(found) {
889
931
  return 0;
890
932
  }
891
933
  function packageVersion(entry = Bun.main) {
892
- for (let dir = dirname3(realpathSync2(entry));; dir = dirname3(dir)) {
934
+ let resolved = entry;
935
+ try {
936
+ resolved = realpathSync2(entry);
937
+ } catch {}
938
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
893
939
  try {
894
940
  const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
895
941
  if (typeof version === "string")
@@ -907,11 +953,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
907
953
  return 0;
908
954
  }
909
955
  let code;
956
+ const started = performance.now();
910
957
  try {
911
958
  code = await run(argv);
912
959
  } catch (error) {
913
960
  code = reportThrown(name, error, redact, wantsJson(argv));
914
961
  }
962
+ notifyEnd(name, code, performance.now() - started);
915
963
  if (usage !== false) {
916
964
  try {
917
965
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1386,7 +1434,7 @@ async function curlHop(url, options) {
1386
1434
  let result = await runCurl(url, options);
1387
1435
  if (result.hop === undefined && options.http3)
1388
1436
  result = await runCurl(url, { ...options, http3: false });
1389
- if (result.hop !== undefined && !options.get && (result.hop.status === 405 || result.hop.status === 501))
1437
+ if (result.hop !== undefined && !options.get && options.method === undefined && result.hop.status >= 400)
1390
1438
  result = await runCurl(url, { ...options, get: true });
1391
1439
  return result;
1392
1440
  }
@@ -1534,9 +1582,9 @@ function ms2(value) {
1534
1582
  return `${value}ms`;
1535
1583
  }
1536
1584
  function compact(report) {
1537
- const { dim } = paint(process14.stdout);
1585
+ const { dim } = paint(process15.stdout);
1538
1586
  const redirects = report.chain.length - 1;
1539
- const parts = [`${role("accent", process14.stdout)(versionLabel(report.version))} ${role("value", process14.stdout)(String(report.status))} ${role("path", process14.stdout)(report.url)}`, ms2(report.timings.total)];
1587
+ const parts = [`${role("accent", process15.stdout)(versionLabel(report.version))} ${role("value", process15.stdout)(String(report.status))} ${role("path", process15.stdout)(report.url)}`, ms2(report.timings.total)];
1540
1588
  const address = report.addresses.a[0] ?? report.addresses.aaaa[0];
1541
1589
  if (redirects > 0)
1542
1590
  parts.push(`${redirects} ${redirects === 1 ? "redirect" : "redirects"}`);
@@ -1545,14 +1593,14 @@ function compact(report) {
1545
1593
  if (address !== undefined)
1546
1594
  parts.push(address);
1547
1595
  const line = parts.join(dim(" "));
1548
- return report.warnings.length === 0 ? line : `${line} ${marked("warn", report.warnings.join("; "), process14.stdout)}`;
1596
+ return report.warnings.length === 0 ? line : `${line} ${marked("warn", report.warnings.join("; "), process15.stdout)}`;
1549
1597
  }
1550
1598
  function print(report) {
1551
- const label = role("label", process14.stdout);
1552
- const value = role("value", process14.stdout);
1553
- const accent = role("accent", process14.stdout);
1599
+ const label = role("label", process15.stdout);
1600
+ const value = role("value", process15.stdout);
1601
+ const accent = role("accent", process15.stdout);
1554
1602
  const row = (name, text) => console.log(`${label(name.padEnd(LABEL_WIDTH))} ${text}`);
1555
- console.log(`${accent(versionLabel(report.version))} ${value(String(report.status))} ${role("path", process14.stdout)(report.url)}`);
1603
+ console.log(`${accent(versionLabel(report.version))} ${value(String(report.status))} ${role("path", process15.stdout)(report.url)}`);
1556
1604
  console.log("");
1557
1605
  if (report.chain.length > 1) {
1558
1606
  console.log(table(report.chain.map((hop) => [String(hop.status), versionLabel(hop.version), ms2(hop.ms), hop.url]), { align: ["right", "left", "right", "left"] }));
@@ -1577,12 +1625,12 @@ function print(report) {
1577
1625
  if (report.httpRedirect !== null)
1578
1626
  row("http://", report.httpRedirect.toHttps ? `redirects to https (${report.httpRedirect.status})` : `answers ${report.httpRedirect.status}`);
1579
1627
  for (const warning of report.warnings)
1580
- console.log(marked("warn", warning, process14.stdout));
1628
+ console.log(marked("warn", warning, process15.stdout));
1581
1629
  }
1582
1630
  function printDns(report) {
1583
- const label = role("label", process14.stdout);
1631
+ const label = role("label", process15.stdout);
1584
1632
  const listed = (values) => values.length === 0 ? "-" : values.join(" ");
1585
- console.log(`${role("path", process14.stdout)(report.target)} ${label(report.zone === null ? "no zone found" : `zone ${report.zone}`)}`);
1633
+ console.log(`${role("path", process15.stdout)(report.target)} ${label(report.zone === null ? "no zone found" : `zone ${report.zone}`)}`);
1586
1634
  console.log(table([
1587
1635
  ["RESOLVER", "SERVER", "A", "AAAA", "CNAME", "TTL"],
1588
1636
  ...report.answers.map((answer) => [
@@ -1593,9 +1641,9 @@ function printDns(report) {
1593
1641
  ])
1594
1642
  ], { header: true }));
1595
1643
  if (report.agree)
1596
- console.log(marked("ok", "every resolver gives the same answer", process14.stdout));
1644
+ console.log(marked("ok", "every resolver gives the same answer", process15.stdout));
1597
1645
  for (const warning of report.warnings)
1598
- console.log(marked("warn", warning, process14.stdout));
1646
+ console.log(marked("warn", warning, process15.stdout));
1599
1647
  }
1600
1648
  async function dnsMain(inputs, timeoutMs, json) {
1601
1649
  const hosts = inputs.map((input) => {
@@ -1620,16 +1668,16 @@ async function dnsMain(inputs, timeoutMs, json) {
1620
1668
  return reports.every(known) ? 0 : 1;
1621
1669
  }
1622
1670
  function printCors(report) {
1623
- const label = role("label", process14.stdout);
1671
+ const label = role("label", process15.stdout);
1624
1672
  const { request } = report;
1625
1673
  const asked = `from ${request.origin}, ${request.method}${request.headers.length === 0 ? "" : ` with ${request.headers.join(", ")}`}`;
1626
- console.log(`${marked(report.allowed ? "ok" : "problem", report.allowed ? "allowed" : "refused", process14.stdout)} ${role("value", process14.stdout)(String(report.status))} ${role("path", process14.stdout)(report.url)} ${label(asked)}`);
1674
+ console.log(`${marked(report.allowed ? "ok" : "problem", report.allowed ? "allowed" : "refused", process15.stdout)} ${role("value", process15.stdout)(String(report.status))} ${role("path", process15.stdout)(report.url)} ${label(asked)}`);
1627
1675
  for (const [name, value] of Object.entries(report.headers))
1628
1676
  console.log(` ${label(name)} ${value}`);
1629
1677
  for (const reason of report.reasons)
1630
- console.log(marked("problem", reason, process14.stdout));
1678
+ console.log(marked("problem", reason, process15.stdout));
1631
1679
  for (const warning of report.warnings)
1632
- console.log(marked("warn", warning, process14.stdout));
1680
+ console.log(marked("warn", warning, process15.stdout));
1633
1681
  }
1634
1682
  async function corsMain(targets, request, { insecure, wire }, json) {
1635
1683
  const reports = await Promise.all(targets.map(async ({ input, target }) => {
@@ -1646,7 +1694,7 @@ async function corsMain(targets, request, { insecure, wire }, json) {
1646
1694
  } else {
1647
1695
  for (const report of reports) {
1648
1696
  if ("error" in report)
1649
- console.error(marked("problem", report.error, process14.stderr));
1697
+ console.error(marked("problem", report.error, process15.stderr));
1650
1698
  else
1651
1699
  printCors(report);
1652
1700
  }
@@ -1694,12 +1742,12 @@ async function main(args) {
1694
1742
  let first = true;
1695
1743
  for (const report of reports) {
1696
1744
  if ("error" in report) {
1697
- console.error(marked("problem", report.error, process14.stderr));
1745
+ console.error(marked("problem", report.error, process15.stderr));
1698
1746
  } else if (values.verbose === true) {
1699
1747
  if (!first)
1700
1748
  console.log("");
1701
1749
  if (reports.length > 1)
1702
- console.log(role("label", process14.stdout)(report.target));
1750
+ console.log(role("label", process15.stdout)(report.target));
1703
1751
  print(report);
1704
1752
  } else {
1705
1753
  console.log(compact(report));
@@ -1708,4 +1756,4 @@ async function main(args) {
1708
1756
  }
1709
1757
  return reports.some((report) => ("error" in report)) ? 1 : 0;
1710
1758
  }
1711
- process14.exitCode = await runMain({ name: "probe", run: main });
1759
+ process15.exitCode = await runMain({ name: "probe", run: main });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-probe",
3
3
  "type": "module",
4
- "version": "0.4.0",
4
+ "version": "0.4.1",
5
5
  "description": "probe: a site's HTTP version, redirect chain, timings, addresses, TLS certificate and notable headers in one call, with warnings.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -35,6 +35,6 @@
35
35
  "probe": "$npm_execpath src/probe.ts"
36
36
  },
37
37
  "devDependencies": {
38
- "@kaynooo/cli-kit": "0.38.1"
38
+ "@kaynooo/cli-kit": "0.39.0"
39
39
  }
40
40
  }