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 | 14x 14x 11x 292x 292x 292x 14x 14x 14x 185x 17x 168x 48x 120x 185x 59x 126x 14x 7x 14x 14x 25x 25x 25x 25x 14x 14x 14x 30x 30x 30x 114x 4x 26x 61x 7x 30x 30x 30x 3x 2x 2x 2x 2x 2x 2x 1x 2x 7x 7x 7x 7x 7x 7x 7x 2x 7x 7x 13x 13x 13x 13x 13x 13x 3x 13x 13x 13x 11x 13x 13x 13x 13x 13x 13x 13x 1x 13x 13x 3x 13x 13x 5x 5x 5x 1x 2x 1x 1x 1x 5x 5x 1x 1x 1x 1x 14x 180x 3x 177x 70x 107x 54x 2x 19x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x 1x 9x 4x 5x 2x 3x 2x 1x 7x 7x 28x 7x 8x 1x 6x 6x 2x 4x 1x 3x 1x 2x 115x 55x 60x 60x 14x 46x 46x | /** Tail formatters for the local dev server. */
import { blue, bold, cyan, green, muted, red, yellow } from "./colors.js";
import { stripAnsi } from "./plain-detect.js";
import {
formatSemanticSpanDisplay,
inferSemanticOp,
mergeTransactionAttributes,
} from "./semantic-display.js";
/**
* Characters unsafe for JSON terminal display: C1 control characters
* (U+0080–U+009F, e.g. CSI=U+009B) and Unicode bidirectional overrides.
* `JSON.stringify` only escapes C0 (U+0000–U+001F) per RFC 8259;
* C1 and BiDi pass through unescaped.
*/
const JSON_UNSAFE_RE = /[\x80-\x9f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
/** BiDi-only regex for the full `sanitize()` function. */
const BIDI_RE = /[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
/**
* Strip C1 control characters and Unicode BiDi overrides from a string.
* Used for JSON output where `JSON.stringify` escapes C0 controls but
* leaves C1 (U+0080–U+009F) and BiDi chars intact — both can cause
* terminal injection when JSON output is displayed in a terminal.
*/
export function stripBidi(text: string): string {
return text.replace(JSON_UNSAFE_RE, "");
}
/**
* Strip ANSI escapes, collapse newlines, and remove C0/C1 control characters
* so envelope fields can't inject fake log lines or terminal commands.
*/
export function sanitize(text: string): string {
// Collapse CR, LF, and NEL (U+0085) which terminals treat as line breaks.
const stripped = stripAnsi(text).replace(/[\r\n\x85]+/g, " ");
// Strip C0 (0x00-0x1F, 0x7F) and C1 (0x80-0x9F) control characters.
const noCtrl = stripped.replace(
// biome-ignore lint/suspicious/noControlCharactersInRegex: stripping control chars from untrusted envelope data
/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\x80-\x9f]/g,
""
);
// Strip Unicode bidirectional override/isolate characters that can reorder terminal output.
return noCtrl.replace(BIDI_RE, "");
}
/** Canonical content type for Sentry envelopes. */
export const SENTRY_CONTENT_TYPE = "application/x-sentry-envelope";
/** Output format options for `--format`. */
export const FORMAT_VALUES = ["human", "json"] as const;
export type FormatValue = (typeof FORMAT_VALUES)[number];
/** Envelope item categories that can be filtered via `--filter`. */
export const FILTER_VALUES = ["error", "transaction", "log", "ai"] as const;
export type FilterValue = (typeof FILTER_VALUES)[number];
/** Format a local timestamp as HH:MM:SS from a Sentry timestamp. */
export function formatTime(timestamp?: number | string): string {
let date: Date;
if (!timestamp) {
date = new Date();
} else if (typeof timestamp === "string") {
date = new Date(timestamp);
} else {
date = new Date(timestamp * 1000);
}
if (Number.isNaN(date.getTime())) {
return "??:??:??";
}
return date.toLocaleTimeString("en-US", { hour12: false });
}
/** Level → color map for tail output. */
const LEVEL_COLORS: Record<string, (s: string) => string> = {
error: (s) => red(bold(s)),
fatal: (s) => red(bold(s)),
warning: yellow,
info: cyan,
trace: green,
debug: muted,
};
/** Longest bracketed type label: `[WARNING]` = 9 chars. */
const TYPE_WIDTH = 9;
/** Longest bracketed source label: `[BROWSER]` = 9 chars. */
const SOURCE_WIDTH = 9;
/** Format a type/level label as `[TYPE]` padded to fixed width. */
export function formatType(level: string): string {
const tag = `[${sanitize(level).toUpperCase()}]`;
const colorFn = LEVEL_COLORS[level.toLowerCase()];
const colored = colorFn ? colorFn(tag) : tag;
return colored + " ".repeat(Math.max(0, TYPE_WIDTH - tag.length));
}
/** Mobile SDK name substrings. */
const MOBILE_MARKERS = ["cocoa", "android", "react-native", "flutter"];
/** Server-side JS SDK name substrings — exclude from browser detection. */
const SERVER_JS_MARKERS = [
"node",
"bun",
"deno",
"nextjs",
"remix",
"astro",
"nuxt",
"sveltekit",
];
/** Source → color map for tail output. */
const SOURCE_COLORS: Record<string, (s: string) => string> = {
browser: yellow,
mobile: blue,
server: cyan,
};
/**
* Infer the source platform from the envelope header's `sdk.name` field.
* Returns a colored, bracketed, padded label like `[SERVER] `.
*/
export function inferSource(header: Record<string, unknown>): string {
const sdk = header.sdk as { name?: string } | undefined;
const name = sdk?.name ?? "";
let source = "server";
if (MOBILE_MARKERS.some((m) => name.includes(m))) {
source = "mobile";
} else if (
name.startsWith("sentry.javascript.") &&
!SERVER_JS_MARKERS.some((m) => name.includes(m))
) {
source = "browser";
}
const tag = `[${source.toUpperCase()}]`;
const colorFn = SOURCE_COLORS[source] ?? cyan;
return colorFn(tag) + " ".repeat(Math.max(0, SOURCE_WIDTH - tag.length));
}
/** Shape of a single stack frame in the exception value. */
export type StackFrame = {
filename?: string;
lineno?: number;
colno?: number;
function?: string;
in_app?: boolean;
};
/** Build the `[file:line:col] [func]` suffix for the best stack frame. */
export function formatFrameHint(frames: StackFrame[]): string {
const frame = frames.find((f) => f.in_app) ?? frames.at(-1);
Iif (!frame) {
return "";
}
let hint = "";
Eif (frame.filename && frame.lineno) {
const loc = sanitize(
frame.colno
? `${frame.filename}:${frame.lineno}:${frame.colno}`
: `${frame.filename}:${frame.lineno}`
);
hint += ` ${muted(`[${loc}]`)}`;
}
if (frame.function) {
hint += ` ${muted(`[${sanitize(frame.function)}]`)}`;
}
return hint;
}
/**
* Format an error event item into a colored one-liner.
*
* Output: `HH:MM:SS [ERROR] [SERVER] TypeError: x is not a function [file.ts:42:5] [handleRequest]`
*/
export function formatErrorItem(
event: Record<string, unknown>,
header: Record<string, unknown>
): string {
const exception = event.exception as
| {
values?: {
type?: string;
value?: string;
stacktrace?: { frames?: StackFrame[] };
}[];
}
| undefined;
// values is ordered oldest→newest; show the outermost (last) exception
const first = exception?.values?.at(-1);
const errorType = sanitize(String(first?.type ?? "Error"));
const errorValue = sanitize(
String(first?.value ?? event.message ?? "Unknown error")
);
let msg = `${errorType}: ${errorValue}`;
const frames = first?.stacktrace?.frames;
if (frames?.length) {
msg += formatFrameHint(frames);
}
const ts = formatTime(event.timestamp as number | undefined);
return `${muted(ts)} ${formatType("error")} ${inferSource(header)} ${msg}`;
}
/**
* Format a transaction event item into a colored one-liner.
*
* When OTel semantic attributes are present (e.g. `gen_ai.*`, `mcp.*`,
* `db.*`), the label is derived from those attributes for richer output.
* Falls back to the raw transaction name + trace.op otherwise.
*
* Output examples:
* - `HH:MM:SS [TRACE] [BROWSER] [http.client] GET /api/users [245ms] [3 spans]`
* - `HH:MM:SS [TRACE] [SERVER] [gen_ai] chat anthropic/claude-4-sonnet [1.2s] [5 spans]`
*/
export function formatTransactionItem(
event: Record<string, unknown>,
header: Record<string, unknown>
): string {
const trace = (event.contexts as Record<string, unknown> | undefined)
?.trace as
| { op?: string; status?: string; description?: string }
| undefined;
const txnName =
typeof event.transaction === "string"
? event.transaction
: (trace?.description ?? "Transaction");
// Try semantic display from OTel attributes first
const attrs = mergeTransactionAttributes(event);
const semantic = formatSemanticSpanDisplay(attrs, sanitize(txnName));
let msg = sanitize(semantic.label);
// Append semantic metadata (e.g. model name, status code, error type)
if (semantic.metadata.length > 0) {
msg += ` ${semantic.metadata.map((m) => muted(`[${sanitize(m)}]`)).join(" ")}`;
}
// Show op tag — prefer semantic category if detected
const semanticOp = inferSemanticOp(attrs);
const op = semanticOp ?? trace?.op;
if (op && op !== "default" && op !== "unknown") {
msg = `[${sanitize(op)}] ${msg}`;
}
const start = event.start_timestamp as number | undefined;
const end = event.timestamp as number | undefined;
Eif (start !== undefined && end !== undefined) {
const durationMs = Math.round((end - start) * 1000);
msg += ` ${muted(`[${durationMs}ms]`)}`;
}
const status = trace?.status;
if (status && status !== "ok") {
msg += ` ${muted(`[${sanitize(status)}]`)}`;
}
const spans = event.spans as unknown[] | undefined;
if (spans?.length) {
msg += ` ${muted(`[${spans.length} span${spans.length === 1 ? "" : "s"}]`)}`;
}
const ts = formatTime(event.timestamp as number | undefined);
return `${muted(ts)} ${formatType("trace")} ${inferSource(header)} ${msg}`;
}
/** Shape of a single log entry inside a log envelope item. */
export type LogEntry = {
level?: string;
body?: string;
timestamp?: number;
attributes?: Record<string, { value?: unknown }>;
};
/** Format one log entry into a colored tail line. */
export function formatSingleLog(logEntry: LogEntry, source: string): string {
const level = logEntry.level ?? "log";
let msg = sanitize(logEntry.body ?? "");
if (logEntry.attributes) {
const attrs = Object.entries(logEntry.attributes)
.filter(
([k, v]) =>
!k.startsWith("sentry.") &&
v !== null &&
v !== undefined &&
v.value !== null &&
v.value !== undefined
)
.map(([k, v]) => muted(`[${sanitize(k)}=${sanitize(String(v.value))}]`));
Eif (attrs.length > 0) {
msg += ` ${attrs.join(" ")}`;
}
}
const ts = formatTime(logEntry.timestamp);
return `${muted(ts)} ${formatType(level)} ${source} ${msg}`;
}
/**
* Format a log event item. A log envelope item contains an `items` array
* of individual log entries; each gets its own line.
*
* Output: `HH:MM:SS [INFO] [SERVER] User logged in [user_id=1234]`
*/
export function formatLogItem(
event: Record<string, unknown>,
header: Record<string, unknown>
): string[] {
const items = event.items as LogEntry[] | undefined;
Iif (!items?.length) {
return [];
}
const source = inferSource(header);
return items.map((logEntry) => formatSingleLog(logEntry, source));
}
/** Item types that map to the error formatter. */
export const ERROR_TYPES = new Set(["event", "error"]);
/**
* Map envelope item `type` to the corresponding `FilterValue`.
* Returns undefined for item types that don't map to a filter category.
*/
export function itemTypeToFilterCategory(
itemType: string | undefined
): FilterValue | undefined {
if (!itemType) {
return;
}
if (ERROR_TYPES.has(itemType)) {
return "error";
}
if (itemType === "transaction" || itemType === "log") {
return itemType;
}
}
/** Produce a fallback one-liner for unparseable or unsupported items. */
export function formatFallbackLine(label: string): string {
return `${muted(formatTime())} ${cyan("•")} ${bold(sanitize(label))}`;
}
/** Resolve a human label for a completely unparseable envelope. */
export function resolveUnparseableLabel(container: {
getContentType: () => string;
getEventTypes: () => string[] | null;
}): string {
const types = container.getEventTypes();
if (types && types.length > 0) {
return types.join("+");
}
const ct = container.getContentType();
return ct === "application/x-sentry-envelope" ? "envelope" : ct;
}
/** Strip BiDi from a string value, returning undefined for non-strings. */
function jsonSafe(value: unknown): string | undefined {
return typeof value === "string" ? stripBidi(value) : undefined;
}
/** Format an error item as a JSON object, including the best stack frame. */
function formatErrorJson(
payload: Record<string, unknown>,
header: Record<string, unknown>
): string {
const exception = payload.exception as
| {
values?: {
type?: string;
value?: string;
stacktrace?: { frames?: StackFrame[] };
}[];
}
| undefined;
const first = exception?.values?.at(-1);
const frame =
first?.stacktrace?.frames?.find((f) => f.in_app) ??
first?.stacktrace?.frames?.at(-1);
return JSON.stringify({
type: "error",
timestamp: payload.timestamp,
error_type: jsonSafe(first?.type) ?? "Error",
message:
jsonSafe(first?.value) ?? jsonSafe(payload.message) ?? "Unknown error",
filename: jsonSafe(frame?.filename),
lineno: frame?.lineno,
colno: frame?.colno,
function: jsonSafe(frame?.function),
source: inferSourceName(header),
});
}
/** Format a transaction item as a JSON object. */
function formatTransactionJson(
payload: Record<string, unknown>,
header: Record<string, unknown>
): string {
const trace = (payload.contexts as Record<string, unknown> | undefined)
?.trace as Record<string, unknown> | undefined;
const attrs = mergeTransactionAttributes(payload);
const semantic = formatSemanticSpanDisplay(
attrs,
String(payload.transaction ?? trace?.description ?? "Transaction")
);
const start = payload.start_timestamp as number | undefined;
const end = payload.timestamp as number | undefined;
const durationMs =
start !== undefined && end !== undefined
? Math.round((end - start) * 1000)
: undefined;
return JSON.stringify({
type: "transaction",
timestamp: payload.timestamp,
op: inferSemanticOp(attrs) ?? trace?.op,
label: stripBidi(semantic.label),
metadata:
semantic.metadata.length > 0
? semantic.metadata.map(stripBidi)
: undefined,
duration_ms: durationMs,
status: trace?.status,
span_count: (payload.spans as unknown[] | undefined)?.length,
source: inferSourceName(header),
});
}
/** Format a log item as JSON objects (one per entry). */
function formatLogJson(
payload: Record<string, unknown>,
header: Record<string, unknown>
): string[] {
const items = payload.items as LogEntry[] | undefined;
if (!items?.length) {
return [];
}
const source = inferSourceName(header);
return items.map((entry) =>
JSON.stringify({
type: "log",
timestamp: entry.timestamp,
level: entry.level ?? "log",
message: stripBidi(entry.body ?? ""),
attributes: entry.attributes
? Object.fromEntries(
Object.entries(entry.attributes)
.filter(
([k, v]) =>
!k.startsWith("sentry.") &&
v?.value !== null &&
v?.value !== undefined
)
.map(([k, v]) => [
k,
typeof v.value === "string" ? stripBidi(v.value) : v.value,
])
)
: undefined,
source,
})
);
}
/**
* Format a single envelope item as a JSON line (NDJSON).
*
* Produces a compact JSON object per item with `type`, `timestamp`,
* and item-specific fields. Designed for machine consumption by AI
* coding agents and automation tools.
*
* Unlike the human formatters, JSON output uses `stripBidi()` instead of
* the full `sanitize()`. `JSON.stringify()` escapes C0 control characters
* (U+0000–U+001F) but leaves C1 controls (U+0080–U+009F) and BiDi overrides
* intact. `stripBidi()` strips both, preventing terminal injection when
* JSON output is viewed in a terminal, while preserving the original data
* structure for downstream consumers.
*/
export function formatItemJson(
itemType: string | undefined,
payload: Record<string, unknown>,
header: Record<string, unknown>
): string[] {
if (itemType && ERROR_TYPES.has(itemType)) {
return [formatErrorJson(payload, header)];
}
if (itemType === "transaction") {
return [formatTransactionJson(payload, header)];
}
if (itemType === "log") {
return formatLogJson(payload, header);
}
return [
JSON.stringify({
type: itemType ?? "unknown",
timestamp: payload.timestamp,
}),
];
}
/** Infer the source platform name from the SDK header (for JSON output). */
function inferSourceName(header: Record<string, unknown>): string {
const sdk = header.sdk as { name?: string } | undefined;
const name = sdk?.name ?? "";
Iif (MOBILE_MARKERS.some((m) => name.includes(m))) {
return "mobile";
}
if (
name.startsWith("sentry.javascript.") &&
!SERVER_JS_MARKERS.some((m) => name.includes(m))
) {
return "browser";
}
return "server";
}
/** Format a single envelope item into one or more output lines. */
export function formatItem(
itemType: string | undefined,
payload: Record<string, unknown>,
header: Record<string, unknown>,
fallbackLabel: string
): string[] {
if (itemType && ERROR_TYPES.has(itemType)) {
return [formatErrorItem(payload, header)];
}
if (itemType === "transaction") {
return [formatTransactionItem(payload, header)];
}
if (itemType === "log") {
return formatLogItem(payload, header);
}
return [formatFallbackLine(fallbackLabel)];
}
/**
* Check whether an item should be shown given active filters.
*
* When `payload` is provided and the `ai` filter is active, transactions
* are checked for GenAI/MCP OTel attributes.
*/
export function isItemIncluded(
itemType: string | undefined,
activeFilters: ReadonlySet<FilterValue>,
payload?: Record<string, unknown>
): boolean {
if (activeFilters.size === 0) {
return true;
}
const category = itemTypeToFilterCategory(itemType);
if (category !== undefined && activeFilters.has(category)) {
return true;
}
// The "ai" filter matches transactions with GenAI or MCP attributes.
Iif (activeFilters.has("ai") && itemType === "transaction" && payload) {
const attrs = mergeTransactionAttributes(payload);
const op = inferSemanticOp(attrs);
return op === "gen_ai" || op === "mcp";
}
return false;
}
/**
* Format a freshly received envelope as NDJSON lines.
*
* Each item produces one JSON line. Filtering works identically to
* the human formatter.
*/
export function formatEnvelopeLinesJson(
container: {
getParsedEnvelope: () => {
envelope: [Record<string, unknown>, [{ type?: string }, unknown][]];
} | null;
getContentType: () => string;
getEventTypes: () => string[] | null;
},
activeFilters: ReadonlySet<FilterValue>
): string[] {
const parsed = container.getParsedEnvelope();
if (!parsed) {
return [];
}
const [header, items] = parsed.envelope;
const lines: string[] = [];
for (const [itemHeader, itemPayload] of items) {
const payload = itemPayload as Record<string, unknown>;
if (!isItemIncluded(itemHeader.type, activeFilters, payload)) {
continue;
}
lines.push(...formatItemJson(itemHeader.type, payload, header));
}
return lines;
}
/**
* Format a freshly received envelope for terminal output.
*
* When `activeFilters` is non-empty, only items whose category matches
* one of the filter values are rendered; non-matching items are silently
* dropped. When empty, all items are shown.
*/
export function formatEnvelopeLines(
container: {
getParsedEnvelope: () => {
envelope: [Record<string, unknown>, [{ type?: string }, unknown][]];
} | null;
getContentType: () => string;
getEventTypes: () => string[] | null;
},
activeFilters: ReadonlySet<FilterValue>
): string[] {
const parsed = container.getParsedEnvelope();
if (!parsed) {
if (activeFilters.size > 0) {
return [];
}
return [formatFallbackLine(resolveUnparseableLabel(container))];
}
const [header, items] = parsed.envelope;
const lines: string[] = [];
for (const [itemHeader, itemPayload] of items) {
const payload = itemPayload as Record<string, unknown>;
if (!isItemIncluded(itemHeader.type, activeFilters, payload)) {
continue;
}
lines.push(
...formatItem(
itemHeader.type,
payload,
header,
itemHeader.type ?? container.getContentType()
)
);
}
if (lines.length > 0) {
return lines;
}
if (activeFilters.size > 0) {
return [];
}
return [formatFallbackLine(resolveUnparseableLabel(container))];
}
|