Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 | 11x 11x 11x 11x 62x 62x 62x 11x 11x 11x 3x 3x 3x 3x 9x 3x 4x 4x 12x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 9x 9x 19x 19x 4x 15x 22x 1x 21x 1x 11x 910x 74x 74x 74x 74x 74x 74x 74x 74x 344x 344x 74x 74x 74x 74x 74x 344x 344x 74x 74x 3x 31x 2x 29x 29x 29x 29x 29x 99x 31x 31x 31x 31x 31x 22x 9x 29x 4x 12x 4x 34x 34x 34x 34x 34x 34x 34x 4x 4x 30x 4x 4x 26x 3x 3x 34x 11x 11x 11x 23x 23x 23x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 11x 11x 24x 24x 32x 24x 2x 2x 2x 2x 4x 4x 4x 4x 1x 48x 48x 41x 41x 7x 7x 7x 39x 39x 7x 32x 32x 7x 7x 7x 7x 10x 1x 9x 20x 9x 13x 28x 28x 1x 27x 13x 14x 9x 20x 24x 24x 9x 9x 20x 2x 2x 2x 4x 20x 9x 2x 4x 2x 4x 20x 9x 8x 8x 9x 9x 20x 20x 9x 13x 28x 9x 22x 22x 22x 41x 22x 22x 22x 22x 22x 3x 3x 3x 19x 19x 22x 22x 22x 3x 3x 9x 9x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 20x 1x 2x 2x 3x 3x 2x 1x 1x 3x 3x 3x 34x 3x 24x 2x 1x 1x 1x 2x 20x 20x 20x 1x 1x 11x 363x 230x 133x 133x 28x 28x 105x 2x 2x 2x 288x 2x 2x 2x 24x 2x 20x 20x 288x 288x 20x 20x 11x 11x 70x 70x 1x 1x 1x 1x 1x 10x 1x 10x 10x 20x 20x 20x 20x 20x 1x 1x 12x 12x 12x 120x 120x 120x 12x 1x 120x 210x 210x 90x 120x 45x 75x 75x 75x 75x 75x 45x 3x 3x 10x 10x 10x 10x 10x 3x 3x 10x 10x 50x 50x 50x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 10x 10x 10x 10x 3x 3x 10x 10x 3x 3x 3x 3x 2x 1x 1x 1x 4x 74x 74x 74x 35x 1x 34x 3x 31x 10x 22x 3x 2x 2x 74x 74x 74x 74x 74x 74x 39x 39x 39x 512x 512x 509x 3x 3x 3x 3x 39x 39x 39x 3x 36x 36x 3x 3x 138x 138x 138x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 138x 62x 62x 74x 20x 20x 15x 62x 62x 62x 74x 54x 20x 20x 62x 62x 138x 204x 6x 198x 198x 198x 30x 138x 138x 138x 138x 54x 62x 62x 62x 62x 50x 50x 50x 48x 50x 50x 50x 12x 12x 12x 12x 12x 62x 62x 62x 62x 62x 62x 62x 62x 9x 6x 5x 3x 2x | /**
* Dashboard widget renderers
*
* Renders actual widget data (time-series, tables, big numbers) for the
* `dashboard view` command. Uses a framebuffer approach: each widget is
* rendered into its grid-allocated region of a virtual screen buffer,
* then the buffer is printed as a single string. This enables correct
* overlapping layouts where tall widgets span multiple rows.
*/
import chalk from "chalk";
import stringWidth from "string-width";
import wrapAnsi from "wrap-ansi";
import type {
DashboardWidgetQuery,
ScalarResult,
TableResult,
TimeseriesResult,
WidgetDataResult,
} from "../../types/dashboard.js";
import { COLORS, muted, terminalLink } from "./colors.js";
import { renderMarkdown } from "./markdown.js";
import type { HumanRenderer } from "./output.js";
import { isPlainOutput } from "./plain-detect.js";
import { downsample, sparkline } from "./sparkline.js";
// ---------------------------------------------------------------------------
// Data type yielded by dashboard view command
// ---------------------------------------------------------------------------
/** Full dashboard state with resolved widget data, yielded as CommandOutput. */
export type DashboardViewData = {
id: string;
title: string;
period: string;
fetchedAt: string;
url: string;
dateCreated?: string;
environment?: string[];
widgets: DashboardViewWidget[];
};
/** A widget with its resolved data result */
export type DashboardViewWidget = {
title: string;
displayType: string;
widgetType?: string;
/** Markdown content for text widgets (from API passthrough field) */
description?: string;
layout?: { x: number; y: number; w: number; h: number };
queries?: DashboardWidgetQuery[];
data: WidgetDataResult;
};
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/** Sentry dashboard grid columns */
const GRID_COLS = 6;
/** Terminal lines per grid height unit */
const LINES_PER_UNIT = 6;
/** Minimum terminal width — floor for very narrow terminals or piped output */
const MIN_TERM_WIDTH = 80;
/** Fallback terminal width when stdout is not a TTY */
const DEFAULT_TERM_WIDTH = 100;
/**
* Get the effective terminal width.
*
* Uses the actual terminal column count when available (TTY),
* falls back to DEFAULT_TERM_WIDTH for piped/redirected output.
* Clamped to MIN_TERM_WIDTH to prevent broken layouts.
*/
function getTermWidth(): number {
const cols = process.stdout.columns;
Iif (cols && cols > 0) {
return Math.max(MIN_TERM_WIDTH, cols);
}
return DEFAULT_TERM_WIDTH;
}
// ---------------------------------------------------------------------------
// Big number ASCII art font
// ---------------------------------------------------------------------------
/** Small font: 3 lines tall, 3 chars wide per glyph. */
const DIGIT_FONT_SM: Record<string, string[]> = {
"0": ["█▀█", "█ █", "▀▀▀"],
"1": [" ▄█", " █", " ▀"],
"2": ["▀▀█", "▄▀▀", "▀▀▀"],
"3": ["▀▀█", " ▀█", "▀▀▀"],
"4": ["█ █", "▀▀█", " ▀"],
"5": ["█▀▀", "▀▀█", "▀▀▀"],
"6": ["█▀▀", "█▀█", "▀▀▀"],
"7": ["▀▀█", " █", " ▀"],
"8": ["█▀█", "█▀█", "▀▀▀"],
"9": ["█▀█", "▀▀█", "▀▀▀"],
".": [" ", " ", " ▀ "],
"-": [" ", "▀▀▀", " "],
K: ["█ █", "██ ", "█ █"],
M: ["█▄█", "█ █", "█ █"],
B: ["██ ", "██▄", "▀▀▀"],
T: ["▀█▀", " █ ", " ▀ "],
};
/** Medium font: 5 lines tall, 5 chars wide per glyph. */
const DIGIT_FONT_MD: Record<string, string[]> = {
"0": ["█████", "██ ██", "██ ██", "██ ██", "█████"],
"1": [" ▄███", " ██", " ██", " ██", " ██"],
"2": ["█████", " ██", "█████", "██ ", "█████"],
"3": ["█████", " ██", " ████", " ██", "█████"],
"4": ["██ ██", "██ ██", "█████", " ██", " ██"],
"5": ["█████", "██ ", "█████", " ██", "█████"],
"6": ["█████", "██ ", "█████", "██ ██", "█████"],
"7": ["█████", " ██", " ██", " ██ ", " ██ "],
"8": ["█████", "██ ██", "█████", "██ ██", "█████"],
"9": ["█████", "██ ██", "█████", " ██", "█████"],
".": [" ", " ", " ", " ", " ██ "],
"-": [" ", " ", "█████", " ", " "],
K: ["██ ██", "████ ", "███ ", "████ ", "██ ██"],
M: ["██ ██", "█████", "█████", "██▀██", "██ ██"],
B: ["████ ", "██ ██", "████ ", "██ ██", "████ "],
T: ["█████", " ██ ", " ██ ", " ██ ", " ██ "],
};
/** Large font: 7 lines tall, 7 chars wide per glyph. */
const DIGIT_FONT_LG: Record<string, string[]> = {
"0": [
"███████",
"██ ██",
"██ ██",
"██ ██",
"██ ██",
"██ ██",
"███████",
],
"1": [
" ▄████",
" ██",
" ██",
" ██",
" ██",
" ██",
" ██",
],
"2": [
"███████",
" ██",
" ██",
"███████",
"██ ",
"██ ",
"███████",
],
"3": [
"███████",
" ██",
" ██",
" ██████",
" ██",
" ██",
"███████",
],
"4": [
"██ ██",
"██ ██",
"██ ██",
"███████",
" ██",
" ██",
" ██",
],
"5": [
"███████",
"██ ",
"██ ",
"███████",
" ██",
" ██",
"███████",
],
"6": [
"███████",
"██ ",
"██ ",
"███████",
"██ ██",
"██ ██",
"███████",
],
"7": [
"███████",
" ██",
" ██",
" ██ ",
" ██ ",
" ██ ",
" ██ ",
],
"8": [
"███████",
"██ ██",
"██ ██",
"███████",
"██ ██",
"██ ██",
"███████",
],
"9": [
"███████",
"██ ██",
"██ ██",
"███████",
" ██",
" ██",
"███████",
],
K: [
"██ ██",
"██ ██ ",
"█████ ",
"████ ",
"█████ ",
"██ ██ ",
"██ ██",
],
M: [
"██ ██",
"███ ███",
"███████",
"███████",
"██ █ ██",
"██ ██",
"██ ██",
],
".": [
" ",
" ",
" ",
" ",
" ",
" ███ ",
" ███ ",
],
"-": [
" ",
" ",
" ",
"███████",
" ",
" ",
" ",
],
B: [
"██████ ",
"██ ██",
"██ ██",
"██████ ",
"██ ██",
"██ ██",
"██████ ",
],
T: [
"███████",
" ███ ",
" ███ ",
" ███ ",
" ███ ",
" ███ ",
" ███ ",
],
};
/** Build glyph row arrays from a formatted string and font. */
function buildGlyphRows(
formatted: string,
font: Record<string, string[]>
): string[][] {
const sampleGlyph = font["0"];
const numRows = sampleGlyph?.length ?? 3;
const glyphW = sampleGlyph?.[0]?.length ?? 3;
const blank = " ".repeat(glyphW);
const rows: string[][] = Array.from({ length: numRows }, () => []);
for (const ch of formatted) {
const glyph = font[ch];
for (let r = 0; r < numRows; r += 1) {
rows[r]?.push(glyph?.[r] ?? blank);
}
}
return rows;
}
/**
* Render a formatted number using a glyph font, centered horizontally.
*/
function renderBigNumber(opts: {
formatted: string;
font: Record<string, string[]>;
innerWidth: number;
}): string[] {
const { formatted, font, innerWidth } = opts;
Iif (isPlainOutput()) {
return [formatted];
}
const sampleGlyph = font["0"];
const glyphW = sampleGlyph?.[0]?.length ?? 3;
const rows = buildGlyphRows(formatted, font);
const color = chalk.hex(COLORS.green);
const rawWidth = formatted.length * (glyphW + 1) - 1;
const leftPad = Math.max(0, Math.floor((innerWidth - rawWidth) / 2));
const pad = " ".repeat(leftPad);
return rows.map((row) => `${pad}${color(row.join(" "))}`);
}
/**
* Calculate the visual width of a rendered number for a given font.
* Each glyph is `glyphWidth` chars wide + 1 space between glyphs.
*/
function calcGlyphWidth(formatted: string, glyphW: number): number {
return formatted.length * (glyphW + 1) - 1;
}
// ---------------------------------------------------------------------------
// Number formatting — shared helpers live in numbers.ts, dashboard-only
// helpers remain here.
// ---------------------------------------------------------------------------
import {
compactFormatter,
formatCompactWithUnit,
formatWithUnit,
} from "./numbers.js";
/**
* Format a value as a short Y-axis tick label (max ~4 chars).
*
* Always uses compact notation: 0 → "0", 500 → "500", 1234 → "1.2K",
* 23454 → "23K", 321305 → "321K", 1500000 → "1.5M".
* Rounds the input to avoid fractional mid-point ticks.
*/
function formatTickLabel(value: number): string {
const rounded = Math.round(value);
if (rounded === 0) {
return "0";
}
return compactFormatter.format(rounded);
}
/**
* Format a big number value with clean integer display.
* Uses compact notation (K, M, B, T) only for values >= 10,000.
* Below that threshold, shows the raw integer without commas.
*/
function formatBigNumberValue(value: number): string {
if (Math.abs(value) >= 10_000) {
return compactFormatter.format(value);
}
return Math.round(value).toString();
}
// ---------------------------------------------------------------------------
// Sort helper: descending by value, "Other" always last
// ---------------------------------------------------------------------------
type BarItem = { label: string; total: number; unit?: string | null };
/** Sort items by value descending, "Other" pinned to end. */
function sortBarItems(items: BarItem[]): BarItem[] {
return [...items].sort((a, b) => {
if (a.label === "Other") {
return 1;
}
if (b.label === "Other") {
return -1;
}
return b.total - a.total;
});
}
// ---------------------------------------------------------------------------
// Border wrapping
// ---------------------------------------------------------------------------
/** Border characters for rounded box-drawing. */
const BORDER = {
tl: "╭",
tr: "╮",
bl: "╰",
br: "╯",
h: "─",
v: "│",
} as const;
/**
* Apply muted color to border characters in rendered mode.
* In plain mode, return the text unchanged.
*/
function borderColor(text: string): string {
return isPlainOutput() ? text : muted(text);
}
/**
* Build the top border line with an embedded title.
*
* Format: `╭─ Title ─────────╮`
* The title is bold in rendered mode, plain otherwise.
*/
function buildTopBorder(title: string, width: number): string {
const plain = isPlainOutput();
const titleText = plain ? title : chalk.bold(title);
// Build left part: ╭─ Title ─
const leftRaw = `${BORDER.tl}${BORDER.h} `;
const left = `${borderColor(leftRaw)}${titleText} `;
// Measure visual width so far, fill remaining space with ─, then ╮
const leftWidth = stringWidth(left);
const fillLen = Math.max(0, width - leftWidth - 1); // -1 for closing ╮
return left + borderColor(`${BORDER.h.repeat(fillLen)}${BORDER.tr}`);
}
/** Build the bottom border line: `╰──────────╯` */
function buildBottomBorder(width: number): string {
return borderColor(
`${BORDER.bl}${BORDER.h.repeat(Math.max(0, width - 2))}${BORDER.br}`
);
}
/** Wrap a content line with left/right borders: `│ content │` */
function buildBorderedLine(content: string, innerWidth: number): string {
const padded = fitToWidth(content, innerWidth);
return `${borderColor(BORDER.v)} ${padded} ${borderColor(BORDER.v)}`;
}
/**
* Wrap content lines inside a bordered box with a title.
*
* The output has exactly `totalHeight` lines:
* - 1 top border (with embedded title)
* - totalHeight - 2 content lines (padded or truncated)
* - 1 bottom border
*/
function wrapInBorder(opts: {
title: string;
contentLines: string[];
width: number;
totalHeight: number;
}): string[] {
const { title, contentLines, width, totalHeight } = opts;
const innerWidth = Math.max(0, width - 4);
const contentSlots = Math.max(0, totalHeight - 2);
const lines: string[] = [buildTopBorder(title, width)];
for (let i = 0; i < contentSlots; i += 1) {
const content =
(i < contentLines.length ? contentLines[i] : undefined) ?? "";
lines.push(buildBorderedLine(content, innerWidth));
}
lines.push(buildBottomBorder(width));
return lines;
}
// ---------------------------------------------------------------------------
// Per-widget renderers — return string[] (content lines, no title/border)
// ---------------------------------------------------------------------------
/** Placeholder for empty data. */
function noDataLine(): string {
return isPlainOutput() ? "(no data)" : muted("(no data)");
}
/**
* Render timeseries content as sparklines (no title/border).
* Labels and sparklines are constrained to fit within the inner width.
*/
function renderTimeseriesContent(
data: TimeseriesResult,
innerWidth: number
): string[] {
if (data.series.length === 0) {
return [noDataLine()];
}
const lines: string[] = [];
const maxValueLen = 10;
const sparkWidth = Math.max(8, Math.min(innerWidth - 16, 40));
const maxLabelLen = Math.max(4, innerWidth - sparkWidth - maxValueLen - 4);
for (const s of data.series) {
const values = s.values.map((v) => v.value);
const graph = sparkline(values, sparkWidth);
const latest = values.length > 0 ? (values.at(-1) ?? 0) : 0;
const formatted = formatWithUnit(latest, s.unit);
const label =
s.label.length > maxLabelLen
? `${s.label.slice(0, maxLabelLen - 1)}…`
: s.label.padEnd(maxLabelLen);
if (isPlainOutput()) {
lines.push(`${label} ${graph} ${formatted}`);
} else {
lines.push(
`${chalk.hex(COLORS.cyan)(label)} ${chalk.hex(COLORS.magenta)(graph)} ${chalk.bold(formatted)}`
);
}
}
return lines;
}
// ---------------------------------------------------------------------------
// Y-axis helpers
// ---------------------------------------------------------------------------
/**
* Calculate Y-axis gutter width based on the widest tick label.
*
* Checks all three tick positions (max, mid, 0) because the mid-point
* can produce a wider label than the max (e.g., 7K vs 3.5K).
* Returns the width needed for "3.5K ┤" including the tick char and space.
*/
function yAxisGutterWidth(maxVal: number): number {
const labels = [
formatTickLabel(maxVal),
formatTickLabel(maxVal / 2),
formatTickLabel(0),
];
const widest = Math.max(...labels.map((l) => l.length));
return widest + 2; // value + " " + "┤"/"│"
}
/**
* Build a Y-axis segment for a given row.
*
* Shows tick labels at top, middle, and bottom positions.
* Other rows show a plain axis line.
*
* @param row - Current row (1 = bottom, maxHeight = top)
* @param maxHeight - Total bar height in rows
* @param maxVal - Maximum data value (for tick labels)
* @param gutterWidth - Width of the gutter (from yAxisGutterWidth)
*/
function buildYAxisSegment(opts: {
row: number;
maxHeight: number;
maxVal: number;
gutterWidth: number;
}): string {
const { row, maxHeight, maxVal, gutterWidth } = opts;
const plain = isPlainOutput();
const midRow = Math.round(maxHeight / 2);
const labelWidth = gutterWidth - 2; // space for " ┤" or " │"
let label = "";
let isTick = false;
if (row === maxHeight) {
label = formatTickLabel(maxVal);
isTick = true;
} else if (row === 1) {
// Check bottom before mid — when maxHeight=2, midRow is also 1
label = "0";
isTick = true;
} else if (row === midRow) {
label = formatTickLabel(maxVal / 2);
isTick = true;
}
if (isTick) {
const padded = label.padStart(labelWidth);
const tick = `${padded} ┤`;
return plain ? tick : muted(tick);
}
const padded = " ".repeat(labelWidth);
const axis = `${padded} │`;
return plain ? axis : muted(axis);
}
// ---------------------------------------------------------------------------
// Vertical bar chart helpers
// ---------------------------------------------------------------------------
/**
* Render categorical_bar content with vertical bars (no title/border).
*
* Labels use two modes:
* - **Direct**: When labels fit within barWidth (e.g., "US", "bun"),
* they appear directly below the bars — clean and readable.
* - **Legend**: When labels are too long (e.g., "sentry.issue.view"),
* letter keys (A, B, C...) appear below bars with a compact legend
* line at the bottom: "A:sentry.issue.view B:sentry.api …"
*/
function renderVerticalBarsContent(
data: TimeseriesResult,
opts: { innerWidth: number; contentHeight: number }
): string[] {
const { innerWidth, contentHeight } = opts;
Iif (data.series.length === 0) {
return [noDataLine()];
}
let items: BarItem[] = data.series.map((s) => ({
label: s.label,
total: s.values.reduce((sum, v) => sum + v.value, 0),
unit: s.unit,
}));
items = sortBarItems(items);
// Exclude "Other" from scale normalization — it often dominates and
// makes all real bars invisible. Cap Other's bar at max height.
const nonOther = items.filter((i) => i.label !== "Other");
const maxVal = Math.max(
...nonOther.map((i) => i.total),
...(nonOther.length === 0 ? items.map((i) => i.total) : []),
1
);
// Y-axis gutter
const gutterW = yAxisGutterWidth(maxVal);
const chartWidth = innerWidth - gutterW;
const gap = 1;
const numItems = items.length;
const barWidth = Math.max(
1,
Math.floor((chartWidth - (numItems - 1) * gap) / numItems)
);
// Check if non-Other labels fit directly below bars
const nonOtherLabels = nonOther.length > 0 ? nonOther : items;
const maxLabelLen = Math.max(...nonOtherLabels.map((i) => i.label.length));
const labelsDirectlyFit = maxLabelLen <= barWidth;
// Reserve lines: 1 axis + 1 label/legend
const footerLines = 2;
const maxBarHeight = Math.max(1, contentHeight - footerLines);
const lines: string[] = [];
const plain = isPlainOutput();
// Render bar rows with Y-axis ticks
for (let row = maxBarHeight; row >= 1; row -= 1) {
const yAxis = buildYAxisSegment({
row,
maxHeight: maxBarHeight,
maxVal,
gutterWidth: gutterW,
});
const barLine = renderVBarRow(items, {
row,
maxVal,
barWidth,
gap,
maxBarHeight,
});
lines.push(`${yAxis}${barLine}`);
}
// Bottom axis line
const axisLine = `${" ".repeat(gutterW - 1)}└${"─".repeat(chartWidth)}`;
lines.push(plain ? axisLine : muted(axisLine));
// Labels below axis
const gutterPad = " ".repeat(gutterW);
if (labelsDirectlyFit) {
const labelParts = items.map((item) => {
let text = item.label;
Iif (text === "Other" && text.length > barWidth) {
text = "Oth";
}
const lbl = text.padEnd(barWidth);
return plain ? lbl : muted(lbl);
});
lines.push(`${gutterPad}${labelParts.join(" ".repeat(gap))}`);
} else E{
// Color/fill-keyed legend line
const entries = items.map((item, i) => ({ label: item.label, index: i }));
lines.push(`${gutterPad}${buildColorLegend(entries, chartWidth)}`);
}
return lines;
}
/** Render one row of the vertical bar chart with per-bar colors. */
function renderVBarRow(
items: BarItem[],
opts: {
row: number;
maxVal: number;
barWidth: number;
gap: number;
maxBarHeight: number;
}
): string {
const plain = isPlainOutput();
const parts: string[] = [];
for (let i = 0; i < items.length; i += 1) {
const item = items[i];
Iif (!item) {
continue;
}
const barHeight = Math.round(
(item.total / opts.maxVal) * opts.maxBarHeight
);
if (barHeight >= opts.row) {
const fill = plain ? seriesFill(item.label, i) : "█";
const bar = fill.repeat(opts.barWidth);
parts.push(plain ? bar : chalk.hex(seriesColor(item.label, i))(bar));
} else E{
parts.push(" ".repeat(opts.barWidth));
}
}
return parts.join(" ".repeat(opts.gap));
}
/**
* Build a compact color/fill-keyed legend line.
*
* Color mode: `■ label1 ■ label2 ■ lab…` (each ■ matches series color)
* Plain mode: `█ label1 ▓ label2 ░ lab…` (fill chars match bars)
*
* Truncated to fit within maxWidth.
*/
function buildColorLegend(
entries: { label: string; index: number }[],
maxWidth: number
): string {
const plain = isPlainOutput();
const parts: string[] = [];
let totalLen = 0;
for (const { label: rawLabel, index } of entries) {
const label = rawLabel.length > 18 ? `${rawLabel.slice(0, 16)}…` : rawLabel;
const fill = seriesFill(rawLabel, index);
const entry = plain
? `${fill} ${label}`
: `${chalk.hex(seriesColor(rawLabel, index))("■")} ${label}`;
const entryLen = 2 + label.length;
const addedLen = totalLen > 0 ? entryLen + 2 : entryLen;
Iif (totalLen + addedLen > maxWidth) {
break;
}
parts.push(entry);
totalLen += addedLen;
}
return parts.join(" ");
}
/** Gap (in columns) between table columns. */
const TABLE_COL_GAP = 2;
/** Measure the max visual width of each column across headers and rows. */
function measureTableColWidths(
headers: string[],
cellRows: string[][]
): number[] {
return headers.map((h, i) => {
let maxW = stringWidth(h);
for (const row of cellRows) {
maxW = Math.max(maxW, stringWidth(row[i] ?? ""));
}
return maxW;
});
}
/**
* Rewrite numeric cells in-place using compact notation (10,000 → 10K).
* Only touches columns whose raw value is a number.
*/
function compactifyTableNumbers(cellRows: string[][], data: TableResult): void {
for (let ri = 0; ri < data.rows.length; ri++) {
const row = cellRows[ri];
Iif (!row) {
continue;
}
for (let ci = 0; ci < data.columns.length; ci++) {
const col = data.columns[ci];
Iif (!col) {
continue;
}
const val = data.rows[ri]?.[col.name];
if (typeof val === "number") {
row[ci] = formatCompactWithUnit(val, col.unit);
}
}
}
}
/** Fit a cell to its column width, padding or truncating with "\u2026". */
function fitTableCell(text: string, width: number, right: boolean): string {
const w = stringWidth(text);
if (w <= width) {
const pad = " ".repeat(width - w);
return right ? pad + text : text + pad;
}
// Truncate: walk chars to fit width - 1, then append "\u2026"
let result = "";
let used = 0;
for (const ch of text) {
const cw = stringWidth(ch);
if (used + cw + 1 > width) {
break;
}
result += ch;
used += cw;
}
result += "\u2026";
used = stringWidth(result);
const remaining = Math.max(0, width - used);
return right
? " ".repeat(remaining) + result
: result + " ".repeat(remaining);
}
/**
* Render table content as aligned text columns (no title/border).
*
* Produces one line per header/separator/row. Column widths are sized to
* fit content, compacted and shrunk if they exceed `innerWidth`, then
* expanded to fill remaining space. Numeric columns are right-aligned.
*/
function renderTableContent(data: TableResult, innerWidth: number): string[] {
if (data.rows.length === 0) {
return [noDataLine()];
}
const plain = isPlainOutput();
const headers = data.columns.map((c) => c.name.toUpperCase());
// Build plain text cell values
const cellRows: string[][] = data.rows.map((row) =>
data.columns.map((col) => {
const val = row[col.name];
if (val === null || val === undefined) {
return "";
}
if (typeof val === "number") {
return formatWithUnit(val, col.unit);
}
return String(val);
})
);
// Detect right-aligned (numeric) columns
const rightAlign = data.columns.map(
(col, ci) =>
cellRows.length > 0 &&
cellRows.every((_, ri) => {
const v = cellRows[ri]?.[ci] ?? "";
return v === "" || typeof data.rows[ri]?.[col.name] === "number";
})
);
const colWidths = measureTableColWidths(headers, cellRows);
const totalGap = TABLE_COL_GAP * Math.max(0, colWidths.length - 1);
// When columns overflow, try compact number formatting before shrinking
if (colWidths.reduce((s, w) => s + w, 0) + totalGap > innerWidth) {
compactifyTableNumbers(cellRows, data);
const remeasured = measureTableColWidths(headers, cellRows);
for (let i = 0; i < colWidths.length; i++) {
colWidths[i] = remeasured[i] ?? 0;
}
}
// Shrink columns proportionally if still exceeds innerWidth
const totalNatural = colWidths.reduce((s, w) => s + w, 0) + totalGap;
if (totalNatural > innerWidth && colWidths.length > 0) {
const available = Math.max(colWidths.length * 3, innerWidth - totalGap);
const scale = available / colWidths.reduce((s, w) => s + w, 0);
for (let i = 0; i < colWidths.length; i++) {
colWidths[i] = Math.max(3, Math.floor((colWidths[i] ?? 0) * scale));
}
}
// Expand last column to fill remaining widget width
const totalUsed = colWidths.reduce((s, w) => s + w, 0) + totalGap;
if (totalUsed < innerWidth && colWidths.length > 0) {
const lastIdx = colWidths.length - 1;
colWidths[lastIdx] = (colWidths[lastIdx] ?? 0) + (innerWidth - totalUsed);
}
const gap = " ".repeat(TABLE_COL_GAP);
const headerLine = headers
.map((h, i) => fitTableCell(h, colWidths[i] ?? 3, rightAlign[i] ?? false))
.join(gap);
const sepLine = colWidths.map((w) => "\u2500".repeat(w)).join(gap);
const dataLines = cellRows.map((row) =>
row
.map((cell, i) =>
fitTableCell(cell, colWidths[i] ?? 3, rightAlign[i] ?? false)
)
.join(gap)
);
return [
plain ? headerLine : chalk.bold(headerLine),
plain ? sepLine : muted(sepLine),
...dataLines,
];
}
/** Center lines vertically, returning a padded array. */
function centerVertically(lines: string[], contentHeight: number): string[] {
// Use ceil to bias slightly downward — looks better below the title border
const topPad = Math.max(0, Math.ceil((contentHeight - lines.length) / 2));
const result: string[] = [];
for (let i = 0; i < topPad; i += 1) {
result.push("");
}
result.push(...lines);
return result;
}
/**
* Render big_number content with auto-scaling font (no title/border).
*
* Tries fonts: large (7×7) → medium (5×5) → small (3×3) → single-line.
* Each font is used only if it fits both width and height.
* Content is centered both horizontally and vertically.
*/
function renderBigNumberContent(
data: ScalarResult,
opts: { innerWidth: number; contentHeight: number }
): string[] {
const { innerWidth, contentHeight } = opts;
const formatted = formatBigNumberValue(data.value);
if (!isPlainOutput()) {
const result = tryBigNumberFonts(formatted, innerWidth, contentHeight);
Eif (result) {
return result;
}
}
// Single-line fallback — center both ways
const withUnit = formatWithUnit(data.value, data.unit);
const display = isPlainOutput() ? withUnit : chalk.bold(withUnit);
const displayWidth = stringWidth(display);
const leftPad = Math.max(0, Math.floor((innerWidth - displayWidth) / 2));
return centerVertically([" ".repeat(leftPad) + display], contentHeight);
}
/**
* Try rendering a big number with progressively smaller fonts.
*
* Tiers: large (7-line) → medium (5-line) → small (3-line).
* Each font is used only if it fits the available width and height.
*/
function tryBigNumberFonts(
formatted: string,
innerWidth: number,
contentHeight: number
): string[] | undefined {
// Font tiers: [font, glyphWidth, minContentHeight]
const tiers: [Record<string, string[]>, number, number][] = [
[DIGIT_FONT_LG, 7, 9], // 7-line font needs ≥9 for centering
[DIGIT_FONT_MD, 5, 7], // 5-line font needs ≥7
[DIGIT_FONT_SM, 3, 3], // 3-line font works in tight spaces
];
for (const [font, glyphW, minHeight] of tiers) {
const width = calcGlyphWidth(formatted, glyphW);
if (width <= innerWidth && contentHeight >= minHeight) {
const bigLines = renderBigNumber({ formatted, font, innerWidth });
return centerVertically(bigLines, contentHeight);
}
}
return;
}
/**
* Render a timeseries as a vertical bar chart filling the available height.
* Used when contentHeight >= 8 (enough room for meaningful bars).
* Each time bucket gets a column; shows series label + max value at top.
*/
function renderTimeseriesBarsContent(
data: TimeseriesResult,
opts: { innerWidth: number; contentHeight: number }
): string[] {
const { innerWidth, contentHeight } = opts;
Iif (data.series.length === 0) {
return [noDataLine()];
}
const isMulti = data.series.length > 1;
// Aggregate for totals and timestamps
const aggregated = aggregateTimeseriesValues(data);
Iif (aggregated.values.length === 0) {
return [noDataLine()];
}
const { values, timestamps, label, unit, latest, maxVal } = aggregated;
// Header: series label + latest value
const headerLabel = label.length > 20 ? `${label.slice(0, 18)}…` : label;
const valStr = formatWithUnit(latest, unit);
const headerLine = isPlainOutput()
? `${headerLabel} ${valStr}`
: `${chalk.hex(COLORS.cyan)(headerLabel)} ${chalk.bold(valStr)}`;
const lines: string[] = [headerLine];
// Y-axis gutter
const gutterW = yAxisGutterWidth(maxVal);
const chartWidth = innerWidth - gutterW;
// Reserve: 1 header + 2 axis/time labels + 1 legend (multi-series only)
const reservedLines = isMulti ? 4 : 3;
const barHeight = Math.max(3, contentHeight - reservedLines);
const maxBars = Math.max(1, chartWidth);
const sampledTs = downsampleTimestamps(timestamps, maxBars);
if (isMulti) {
// Stacked multi-color bars: downsample each series independently
const stackedSeries = data.series.map((s) => ({
label: s.label,
values: downsample(
s.values.map((v) => v.value),
maxBars
),
}));
lines.push(
...renderStackedTimeBarRows(stackedSeries, {
maxVal,
barHeight,
gutterWidth: gutterW,
chartWidth,
})
);
} else {
const sampled = downsample(values, maxBars);
lines.push(
...renderTimeBarRows(sampled, {
maxVal,
barHeight,
gutterWidth: gutterW,
chartWidth,
})
);
}
// Bottom axis with tick marks + time labels
lines.push(
...buildTimeAxis({
timestamps: sampledTs,
chartWidth,
gutterWidth: gutterW,
})
);
// Color legend for multi-series (below time labels)
if (isMulti) {
const entries = data.series.map((s, i) => ({ label: s.label, index: i }));
const legend = buildColorLegend(entries, chartWidth);
lines.push(`${" ".repeat(gutterW)}${legend}`);
}
return lines;
}
/**
* Aggregate all timeseries into a single values array.
*
* For multi-series data (e.g., Errors grouped by title), sums all series
* per time bucket. Returns the aggregate values, label, and stats.
*/
/** Aggregated timeseries result with timestamps preserved. */
type AggregatedTimeseries = {
values: number[];
timestamps: number[];
label: string;
unit?: string | null;
latest: number;
maxVal: number;
};
function aggregateTimeseriesValues(
data: TimeseriesResult
): AggregatedTimeseries {
const first = data.series[0];
Iif (!first || first.values.length === 0) {
return { values: [], timestamps: [], label: "", latest: 0, maxVal: 1 };
}
const timestamps = first.values.map((v) => v.timestamp);
// Single series — use directly
if (data.series.length === 1) {
const values = first.values.map((v) => v.value);
return {
values,
timestamps,
label: first.label,
unit: first.unit,
latest: values.at(-1) ?? 0,
maxVal: Math.max(...values, 1),
};
}
// Multiple series — sum per time bucket
const bucketCount = first.values.length;
const summed = new Array<number>(bucketCount).fill(0);
for (const s of data.series) {
for (let i = 0; i < s.values.length; i += 1) {
const point = s.values[i];
Eif (point) {
summed[i] = (summed[i] ?? 0) + point.value;
}
}
}
const label = `${data.series.length} series`;
return {
values: summed,
timestamps,
label,
unit: first.unit,
latest: summed.at(-1) ?? 0,
maxVal: Math.max(...summed, 1),
};
}
/**
* Fractional block characters for smooth bar tops.
* Index 0 = empty, 8 = full block. Indices 1-7 are increasing fill.
*/
const FRAC_BLOCKS = [" ", "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];
/**
* Build a single column character for a time-series bar at a given row.
* Uses fractional blocks for the top-of-bar row to create smooth edges.
*
* @param fractionalHeight - The bar's height in fractional rows (0-barHeight)
* @param row - The current row being rendered (1 = bottom, barHeight = top)
*/
function buildTimeseriesBarColumn(
fractionalHeight: number,
row: number
): string {
if (fractionalHeight >= row) {
return "█";
}
// Fractional top: this row is partially filled
const fraction = fractionalHeight - (row - 1);
if (fraction > 0) {
const idx = Math.round(fraction * 8);
return FRAC_BLOCKS[Math.min(idx, 8)] ?? " ";
}
return " ";
}
/** Render time-series bar rows with smooth fractional block tops and Y-axis. */
function renderTimeBarRows(
sampled: number[],
opts: {
maxVal: number;
barHeight: number;
gutterWidth: number;
chartWidth: number;
}
): string[] {
const { maxVal, barHeight, gutterWidth, chartWidth } = opts;
const plain = isPlainOutput();
const colorFn = plain
? (s: string) => s
: (s: string) => chalk.hex(COLORS.magenta)(s);
const rows: string[] = [];
// Scale bar width so bars fill the full chart area.
// Distribute the floor-division remainder across the first N bars
// so the total rendered width exactly equals chartWidth.
const barWidth = Math.max(
1,
Math.floor(chartWidth / Math.max(1, sampled.length))
);
const barRemainder = chartWidth - barWidth * sampled.length;
// Pre-compute fractional heights for each column
const heights = sampled.map((v) => (v / maxVal) * barHeight);
for (let row = barHeight; row >= 1; row -= 1) {
const yAxis = buildYAxisSegment({
row,
maxHeight: barHeight,
maxVal,
gutterWidth,
});
const parts = heights.map((h, col) => {
const w = barWidth + (col < barRemainder ? 1 : 0);
return colorFn(buildTimeseriesBarColumn(h, row).repeat(w));
});
rows.push(`${yAxis}${parts.join("")}`);
}
return rows;
}
/**
* Chart color palette based on Sentry's categorical chart hues.
*
* Derived from sentry/static/app/utils/theme/scraps/tokens/color.tsx
* (categorical.dark / categorical.light), adjusted to a mid-luminance
* range so every color achieves ≥3:1 contrast on **both** dark (#1e1e1e)
* and light (#f0f0f0) terminal backgrounds.
*
* "Other" always gets muted gray (handled by seriesColor).
*/
const SERIES_PALETTE = [
"#7553FF", // blurple (Sentry primary)
"#F0369A", // pink
"#C06F20", // orange (darkened from #FF9838)
"#3D8F09", // green (darkened from #67C800)
"#8B6AC8", // purple (lightened from #5D3EB2)
"#E45560", // salmon (darkened from #FA6769)
"#B82D90", // magenta
"#9E8B18", // yellow (darkened from #FFD00E)
"#228A83", // teal (fills hue gap)
"#7B50D0", // indigo (lightened from #50219C)
] as const;
/**
* Fill characters for plain/no-color mode.
*
* Descending density so the most prominent series gets the densest fill.
* "Other" always gets the lightest fill (░).
*/
const PLAIN_FILLS = ["█", "▓", "▒", "#", "=", "*", "+", "~", ":", "."] as const;
/** Get the color for a series by index. "Other" gets muted gray. */
function seriesColor(label: string, index: number): string {
if (label === "Other") {
return COLORS.muted;
}
return SERIES_PALETTE[index % SERIES_PALETTE.length] ?? COLORS.magenta;
}
/** Get the fill character for a series in plain mode. "Other" gets ░. */
function seriesFill(label: string, index: number): string {
Iif (label === "Other") {
return "░";
}
return PLAIN_FILLS[index % PLAIN_FILLS.length] ?? "█";
}
/**
* Render stacked multi-color time-series bar rows.
*
* Each column shows stacked segments from each series, bottom to top.
* The first series is at the bottom, "Other" at the top.
* Each series gets a distinct color from SERIES_PALETTE.
*/
function renderStackedTimeBarRows(
stackedSeries: { label: string; values: number[] }[],
opts: {
maxVal: number;
barHeight: number;
gutterWidth: number;
chartWidth: number;
}
): string[] {
const { maxVal, barHeight, gutterWidth, chartWidth } = opts;
const plain = isPlainOutput();
const numBuckets = stackedSeries[0]?.values.length ?? 0;
// Scale bar width so bars fill the full chart area.
// Distribute the floor-division remainder across the first N bars.
const barWidth = Math.max(
1,
Math.floor(chartWidth / Math.max(1, numBuckets))
);
const barRemainder = chartWidth - barWidth * numBuckets;
// Pre-compute cumulative heights per column, bottom-up
const stackedHeights: {
bottom: number;
top: number;
label: string;
seriesIdx: number;
}[][] = Array.from({ length: numBuckets }, () => []);
for (let col = 0; col < numBuckets; col += 1) {
let cumulative = 0;
for (let s = 0; s < stackedSeries.length; s += 1) {
const series = stackedSeries[s];
const val = series?.values[col] ?? 0;
const bottom = cumulative;
cumulative += val;
stackedHeights[col]?.push({
bottom: (bottom / maxVal) * barHeight,
top: (cumulative / maxVal) * barHeight,
label: series?.label ?? "",
seriesIdx: s,
});
}
}
const rows: string[] = [];
for (let row = barHeight; row >= 1; row -= 1) {
const yAxis = buildYAxisSegment({
row,
maxHeight: barHeight,
maxVal,
gutterWidth,
});
const parts: string[] = [];
for (let col = 0; col < numBuckets; col += 1) {
const w = barWidth + (col < barRemainder ? 1 : 0);
const ch = buildStackedColumn(stackedHeights[col] ?? [], row, plain, w);
parts.push(ch);
}
rows.push(`${yAxis}${parts.join("")}`);
}
return rows;
}
/**
* Build characters for a stacked bar column at a given row.
*
* Returns `barWidth` characters (possibly wrapped in a single ANSI color
* escape) so that each data bucket fills its proportional share of the
* chart width.
*/
function buildStackedColumn(
segments: { bottom: number; top: number; label: string; seriesIdx: number }[],
row: number,
plain: boolean,
barWidth: number
): string {
// Walk segments top-down to find which series fills this row
for (let s = segments.length - 1; s >= 0; s -= 1) {
const seg = segments[s];
if (!seg || seg.top <= row - 1) {
continue;
}
if (seg.bottom >= row) {
continue;
}
// This segment contributes to this row
const ch = buildTimeseriesBarColumn(seg.top - seg.bottom, row - seg.bottom);
Iif (ch === " ") {
continue;
}
Eif (plain) {
// In plain mode, use the series fill character for full blocks
// but keep fractional blocks as-is for smooth tops
const fill = ch === "█" ? seriesFill(seg.label, seg.seriesIdx) : ch;
return fill.repeat(barWidth);
}
return chalk.hex(seriesColor(seg.label, seg.seriesIdx))(
ch.repeat(barWidth)
);
}
return " ".repeat(barWidth);
}
/**
* Pick representative timestamps for each downsampled bucket.
* Uses the midpoint timestamp of each bucket.
*/
function downsampleTimestamps(
timestamps: number[],
targetLen: number
): number[] {
Eif (timestamps.length <= targetLen) {
return timestamps;
}
const bucketSize = timestamps.length / targetLen;
const result: number[] = [];
for (let i = 0; i < targetLen; i += 1) {
const mid = Math.floor(i * bucketSize + bucketSize / 2);
result.push(timestamps[Math.min(mid, timestamps.length - 1)] ?? 0);
}
return result;
}
/**
* Format a Unix timestamp for a time-axis label.
*
* Adapts to the time span:
* - < 2 days: "HH:MM"
* - 2-30 days: "MM/DD"
* - > 30 days: "Mon DD"
*/
function formatTimestamp(ts: number, spanDays: number): string {
const d = new Date(ts * 1000);
Eif (spanDays < 2) {
const hh = String(d.getHours()).padStart(2, "0");
const mm = String(d.getMinutes()).padStart(2, "0");
return `${hh}:${mm}`;
}
if (spanDays <= 30) {
const mm = String(d.getMonth() + 1).padStart(2, "0");
const dd = String(d.getDate()).padStart(2, "0");
return `${mm}/${dd}`;
}
const months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
return `${months[d.getMonth()] ?? "???"} ${d.getDate()}`;
}
/**
* Build the bottom axis line (with ┬ tick marks) and time label line.
*
* Returns 2 lines:
* 1. `└──┬─────┬─────┬──` (axis with ticks at label positions)
* 2. ` 03/17 03/19 03/21` (labels centered on tick positions)
*/
/** Place labels onto a character array, centered on their positions. */
function placeLabelsOnLine(
labels: { pos: number; text: string }[],
width: number
): string {
const line = new Array(width).fill(" ");
for (const { pos, text } of labels) {
const start = Math.min(
width - text.length,
Math.max(0, pos - Math.floor(text.length / 2))
);
for (let c = 0; c < text.length; c += 1) {
const target = start + c;
Eif (target < width) {
line[target] = text[c] ?? " ";
}
}
}
return line.join("").trimEnd();
}
/**
* Build the bottom axis line (with ┬ tick marks) and time label line.
*
* Returns 2 lines:
* 1. `└──┬─────┬─────┬──` (axis with ticks at label positions)
* 2. ` 03/17 03/19 03/21` (labels centered on tick positions)
*/
function buildTimeAxis(opts: {
timestamps: number[];
chartWidth: number;
gutterWidth: number;
}): string[] {
const { timestamps, chartWidth, gutterWidth } = opts;
const plain = isPlainOutput();
Iif (timestamps.length < 2) {
const axis = `${" ".repeat(gutterWidth - 1)}└${"─".repeat(chartWidth)}`;
return [plain ? axis : muted(axis)];
}
const firstTs = timestamps[0] ?? 0;
const lastTs = timestamps.at(-1) ?? 0;
const spanDays = (lastTs - firstTs) / 86_400;
// Determine how many labels fit (each label ~5 chars + spacing)
const maxLabels = Math.max(2, Math.floor(chartWidth / 7));
const labelCount = Math.min(maxLabels, timestamps.length);
// Compute label positions and text
const labels: { pos: number; text: string }[] = [];
for (let i = 0; i < labelCount; i += 1) {
const idx = Math.round((i / (labelCount - 1)) * (timestamps.length - 1));
const ts = timestamps[idx] ?? 0;
labels.push({
pos: Math.round((idx / (timestamps.length - 1)) * (chartWidth - 1)),
text: formatTimestamp(ts, spanDays),
});
}
// Build axis line with ┬ at tick positions
const tickPositions = new Set(labels.map((l) => l.pos));
const axisChars = new Array(chartWidth).fill("─");
for (const pos of tickPositions) {
Eif (pos >= 0 && pos < chartWidth) {
axisChars[pos] = "┬";
}
}
const axisStr = `${" ".repeat(gutterWidth - 1)}└${axisChars.join("")}`;
const labelStr = `${" ".repeat(gutterWidth)}${placeLabelsOnLine(labels, chartWidth)}`;
return [plain ? axisStr : muted(axisStr), plain ? labelStr : muted(labelStr)];
}
/**
* Render text widget markdown content as terminal lines.
*
* Pipeline: markdown → renderMarkdown() (ANSI-styled) → wrap-ansi
* (width-constrained) → split into lines. Empty/missing content renders
* as a muted placeholder.
*/
function renderTextContent(content: string, innerWidth: number): string[] {
if (!content.trim()) {
return [isPlainOutput() ? "(empty)" : muted("(empty)")];
}
const rendered = renderMarkdown(content);
const wrapped = wrapAnsi(rendered, innerWidth, {
hard: true,
trim: false,
});
return wrapped.split("\n");
}
/** Render placeholder content for unsupported/error widgets (no title/border). */
function renderPlaceholderContent(message: string): string[] {
return [isPlainOutput() ? `(${message})` : muted(`(${message})`)];
}
/**
* Dispatch to the appropriate content renderer based on data type.
*
* Returns raw content lines (no title, no border). The caller handles
* border wrapping and height enforcement.
*/
function renderContentLines(opts: {
widget: DashboardViewWidget;
innerWidth: number;
contentHeight: number;
}): string[] {
const { widget, innerWidth, contentHeight } = opts;
const { data } = widget;
switch (data.type) {
case "timeseries":
if (widget.displayType === "categorical_bar") {
return renderVerticalBarsContent(data, { innerWidth, contentHeight });
}
// Use vertical bars when there's enough height, sparklines otherwise
if (contentHeight >= 8) {
return renderTimeseriesBarsContent(data, { innerWidth, contentHeight });
}
return renderTimeseriesContent(data, innerWidth);
case "table":
return renderTableContent(data, innerWidth);
case "scalar":
return renderBigNumberContent(data, { innerWidth, contentHeight });
case "text":
return renderTextContent(data.content, innerWidth);
case "unsupported":
return renderPlaceholderContent(data.reason);
case "error":
return renderPlaceholderContent(`query failed: ${data.message}`);
default:
return renderPlaceholderContent("unknown widget data type");
}
}
/**
* Render a widget into terminal lines with a bordered box.
*
* Returns exactly `layout.h * LINES_PER_UNIT` lines so the framebuffer
* grid composes correctly. The widget content is wrapped in a rounded
* Unicode border with the title embedded in the top border line.
*/
function renderWidgetLines(
widget: DashboardViewWidget,
width: number
): string[] {
const layout = widget.layout;
const totalHeight = layout ? layout.h * LINES_PER_UNIT : LINES_PER_UNIT;
const innerWidth = Math.max(0, width - 4);
const contentHeight = Math.max(0, totalHeight - 2);
const contentLines = renderContentLines({
widget,
innerWidth,
contentHeight,
});
return wrapInBorder({
title: widget.title,
contentLines,
width,
totalHeight,
});
}
// ---------------------------------------------------------------------------
// Framebuffer grid renderer
// ---------------------------------------------------------------------------
/**
* Clip a string to a visual width, accounting for ANSI escape codes.
* If the string is shorter, it is padded with spaces.
* If longer, it is truncated (ANSI-aware via character iteration).
*/
/** ANSI escape sequence type for the truncation state machine. */
type EscapeType = "none" | "start" | "csi" | "osc";
/** Check if a character is an ASCII letter (CSI sequence terminator). */
function isAsciiLetter(ch: string): boolean {
return (ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z");
}
/**
* Advance the ANSI escape state machine by one character.
*
* Returns `true` if the character is part of an escape sequence (should
* be appended to the output but NOT counted as visible width).
* Handles CSI (`\x1b[...letter`) and OSC (`\x1b]...BEL` or `\x1b]...\x1b\\`).
*/
function advanceEscape(
state: { type: EscapeType },
ch: string,
buffer: string
): boolean {
switch (state.type) {
case "none":
Iif (ch === "\x1b") {
state.type = "start";
return true;
}
return false;
case "start":
if (ch === "[") {
state.type = "csi";
} else if (ch === "]") {
state.type = "osc";
} else {
state.type = "none";
}
return true;
case "csi":
if (isAsciiLetter(ch)) {
state.type = "none";
}
return true;
case "osc":
// OSC ends at BEL (\x07) or ST (\x1b\\)
if (ch === "\x07" || (ch === "\\" && buffer.at(-1) === "\x1b")) {
state.type = "none";
}
return true;
default:
return false;
}
}
function fitToWidth(line: string, targetWidth: number): string {
const visibleWidth = stringWidth(line);
if (visibleWidth <= targetWidth) {
return line + " ".repeat(targetWidth - visibleWidth);
}
// Truncate: walk characters, tracking visible width
let result = "";
let width = 0;
const esc = { type: "none" as "none" | "start" | "csi" | "osc" };
for (const ch of line) {
Iif (advanceEscape(esc, ch, result)) {
result += ch;
continue;
}
const charWidth = stringWidth(ch);
if (width + charWidth > targetWidth) {
break;
}
result += ch;
width += charWidth;
}
// Pad remainder
Iif (width < targetWidth) {
result += " ".repeat(targetWidth - width);
}
return result;
}
/**
* Compose a single terminal row from active widgets.
* Each widget's content is clipped to its column width.
*/
function composeTermRow(
active: DashboardViewWidget[],
termRow: number,
termWidth: number,
rendered: Map<DashboardViewWidget, string[]>
): string {
let line = "";
let currentCol = 0;
for (const w of active) {
const layout = w.layout;
Iif (!layout) {
continue;
}
const startCol = Math.floor((layout.x / GRID_COLS) * termWidth);
const colWidth = Math.floor((layout.w / GRID_COLS) * termWidth);
const widgetStartRow = layout.y * LINES_PER_UNIT;
const lineIdx = termRow - widgetStartRow;
Iif (startCol > currentCol) {
line += " ".repeat(startCol - currentCol);
currentCol = startCol;
}
const widgetLines = rendered.get(w) ?? [];
const content = widgetLines[lineIdx] ?? "";
line += fitToWidth(content, colWidth);
currentCol = startCol + colWidth;
}
return line;
}
/**
* Render the dashboard as a framebuffer.
*
* Each widget is drawn at its grid-allocated position. Tall widgets
* correctly span multiple rows. For each terminal row, all active
* widgets are composed side-by-side at their column positions, clipped
* to prevent overflow.
*/
function renderGrid(
widgets: DashboardViewWidget[],
termWidth: number
): string[] {
let maxGridBottom = 0;
for (const w of widgets) {
if (w.layout) {
const bottom = w.layout.y + w.layout.h;
if (bottom > maxGridBottom) {
maxGridBottom = bottom;
}
}
}
const totalTermRows = maxGridBottom * LINES_PER_UNIT;
const rendered = new Map<DashboardViewWidget, string[]>();
for (const w of widgets) {
if (!w.layout) {
continue;
}
const colWidth = Math.floor((w.layout.w / GRID_COLS) * termWidth);
rendered.set(w, renderWidgetLines(w, colWidth));
}
const output: string[] = [];
for (let termRow = 0; termRow < totalTermRows; termRow++) {
const active = widgets
.filter((ww) => {
if (!ww.layout) {
return false;
}
const startRow = ww.layout.y * LINES_PER_UNIT;
const endRow = (ww.layout.y + ww.layout.h) * LINES_PER_UNIT;
return termRow >= startRow && termRow < endRow;
})
.sort((a, b) => (a.layout?.x ?? 0) - (b.layout?.x ?? 0));
Iif (active.length === 0) {
output.push("");
} else {
output.push(composeTermRow(active, termRow, termWidth, rendered));
}
}
const noLayout = widgets.filter((item) => !item.layout);
for (const w of noLayout) {
output.push("", ...renderWidgetLines(w, termWidth));
}
return output;
}
// ---------------------------------------------------------------------------
// Dashboard header
// ---------------------------------------------------------------------------
/** Render the compact dashboard header with linkified title, badges, and underline. */
function renderHeader(data: DashboardViewData, termWidth: number): string[] {
const lines: string[] = [];
const plain = isPlainOutput();
if (plain) {
lines.push(data.title);
let meta = `Period: ${data.period}`;
if (data.environment?.length) {
meta += ` Env: ${data.environment.join(", ")}`;
}
lines.push(meta);
lines.push(data.url);
lines.push("─".repeat(Math.min(data.url.length, termWidth)));
} else {
const title = terminalLink(chalk.bold(data.title), data.url);
const period = chalk.cyan(`[${data.period}]`);
const env = data.environment?.length
? chalk.green(`env: ${data.environment.join(", ")}`)
: "";
lines.push(`${title} ${period}${env ? ` ${env}` : ""}`);
lines.push(muted("─".repeat(termWidth)));
}
lines.push("");
return lines;
}
// ---------------------------------------------------------------------------
// Full dashboard renderer
// ---------------------------------------------------------------------------
/**
* Format a complete dashboard with resolved widget data.
*
* Renders a compact header, then lays out widgets using the framebuffer
* grid engine that respects the Sentry 6-column dashboard layout.
*/
export function formatDashboardWithData(data: DashboardViewData): string {
const termWidth = getTermWidth();
const lines: string[] = [];
lines.push(...renderHeader(data, termWidth));
lines.push(...renderGrid(data.widgets, termWidth));
lines.push("");
return lines.join("\n");
}
// ---------------------------------------------------------------------------
// HumanRenderer factory (supports --refresh mode)
// ---------------------------------------------------------------------------
export function createDashboardViewRenderer(): HumanRenderer<DashboardViewData> {
return {
render(data: DashboardViewData): string {
return formatDashboardWithData(data);
},
finalize(hint?: string): string {
if (!hint) {
return "";
}
return isPlainOutput() ? `\n${hint}\n` : "";
},
};
}
// ---------------------------------------------------------------------------
// JSON transform
|