ANSI Terminal Styling & Formatting (vael:ansi & vael:fmt)
VaelJS ships zero-dependency terminal styling and formatting in both vjs and vjs-lite through vael:ansi and vael:fmt (plus focused subpaths vael:fmt/printf, vael:fmt/inspect, vael:fmt/strip-ansi-code, vael:fmt/bytes, and vael:fmt/duration).
1. Respecting Color Environment & detectColorLevel()
Section titled “1. Respecting Color Environment & detectColorLevel()”vael:ansi checks standard environment variables (NO_COLOR, FORCE_COLOR, CLICOLOR, COLORTERM, TERM=dumb) and host TTY capabilities automatically via detectColorLevel() and isColorEnabled():
ColorLevel.NONE(0): No color support (NO_COLORnon-empty,TERM=dumb, or non-TTY withoutFORCE_COLOR).ColorLevel.BASIC(1): 16-color ANSI SGR.ColorLevel.ANSI256(2): 256-color palette (rgb256/bgRgb256).ColorLevel.TRUECOLOR(3): 24-bit RGB truecolor (rgb24/hex).
import { bold, ColorLevel, detectColorLevel, green, hex, isColorEnabled, style } from "vael:ansi";
const level = detectColorLevel();const enabled = isColorEnabled();
function badge(label: string): string { if (!enabled) return `[${label}]`; if (level >= ColorLevel.TRUECOLOR) { return style(` ${label} `, { bold: true, fg: "#e8ede5", bg: "#6d28d9" }); } return bold(green(`[${label}]`));}
console.log(badge("READY"), hex("#e0b85c", "Artifact verified"));2. SGR Styles, 16/256/TrueColor RGB & Nesting
Section titled “2. SGR Styles, 16/256/TrueColor RGB & Nesting”vael:ansi supports single-attribute helpers (bold, dim, italic, underline, blink, inverse, hidden, strikethrough, overline, reset), all 16 standard + bright foreground and background helpers (black..brightWhite, bgBlack..bgBrightWhite), 256-color (rgb256, bgRgb256), 24-bit RGB (rgb24, bgRgb24), hex (hex, bgHex), and the combined style(text, options) builder.
Nested calls restore the outer SGR attribute automatically rather than prematurely resetting everything with \x1b[0m:
import { bgRgb256, bold, green, magenta, rgb24, rgb256, style } from "vael:ansi";
console.log(bold(`Status: ${green("healthy")} (inner reset restored bold)`));console.log(magenta("Purple accent"), rgb256(214, "Amber 256"), bgRgb256(236, "Chip"));console.log(rgb24(182, 147, 247, "Truecolor #b693f7"));console.log(style("Deploy Gate", { bold: true, underline: true, fg: "brightWhite", bg: [109, 40, 217] }));3. Cursor Control, Screen Erase, Alt-Screen, OSC 8 & DEC 2026
Section titled “3. Cursor Control, Screen Erase, Alt-Screen, OSC 8 & DEC 2026”Use vael:ansi control sequences with vael:stdio (stdout.writeSync in vjs) or vael:fmt’s printf (both vjs and vjs-lite) to render progress bars, TUIs, and clickable terminal links without tearing:
- Cursor movement & shape:
cursorUp,cursorDown,cursorForward,cursorBack,cursorNextLine,cursorPrevLine,cursorHorizontalAbsolute,cursorTo(col, row?),cursorMove(dx, dy?),cursorHome(),cursorSave(),cursorRestore(),cursorHide(),cursorShow(),cursorShape(CursorShape.BAR). - Erasing & alternate screen:
eraseLine(),eraseLineToEnd(),eraseLineToStart(),eraseLines(n),eraseScreen(),eraseScreenToEnd(),eraseScreenToStart(),eraseScrollback(),clearScreen(),scrollUp(n?),scrollDown(n?),enterAltScreen(),exitAltScreen(),enableLineWrap(),disableLineWrap(). - OSC & synchronized output:
hyperlink(text, url, id?)(OSC 8 clickable link),setTitle(title)(sanitized OSC 0/2 title),beep(),syncOutput(content)/syncOutputStart()/syncOutputEnd()(DEC mode 2026 flicker-free frame bracketing).
import { cursorHide, cursorShow, eraseLine, green, hyperlink, syncOutput,} from "vael:ansi";import { printf } from "vael:fmt";
printf("%s", cursorHide());try { for (const pct of [25, 60, 100]) { const frame = `\r${eraseLine()}${green("●")} Uploading [${pct}%]`; printf("%s", syncOutput(frame)); } printf("\n%s\n", hyperlink("View release notes", "https://vaeljs.com"));} finally { printf("%s", cursorShow());}Note that hyperlink() and setTitle() automatically strip embedded control characters from URLs and titles to prevent terminal escape injection.
4. ANSI-Aware Width, Truncation & Wrapping
Section titled “4. ANSI-Aware Width, Truncation & Wrapping”Measuring .length on styled or Unicode text breaks table alignment because ANSI escape codes count as characters and wide CJK/emoji graphemes occupy 2 terminal columns. Use visibleWidth, truncate, wrap, and stripAnsi:
import { bold, magenta, stripAnsi, truncate, visibleWidth, wrap } from "vael:ansi";
const label = bold(magenta("Deploy: 龍"));console.log("Visible columns:", visibleWidth(label)); // 10 (ANSI codes ignored, wide CJK = 2)console.log("Truncated:", truncate(label, 8)); // closes SGR before "…"console.log("Wrapped:\n" + wrap(magenta("alpha beta gamma delta"), 11));console.log("Plain:", stripAnsi(label)); // "Deploy: 龍"5. Formatting with vael:fmt (printf, inspect, bytes, duration)
Section titled “5. Formatting with vael:fmt (printf, inspect, bytes, duration)”vael:fmt brings @neotales/fmt-compatible formatting directly into the standard library across both vjs and vjs-lite:
- Formatted output & errors:
sprintf,printf,print,echo,echof,errorf, andsetNoColor(boolean)(controls%i/%Icolor output). Supports Go/POSIX verbs (%s,%d,%b,%o,%x,%X,%f,%g,%t,%v,%#v,%T,%j,%i,%I,%%) and 1-based positional indices (%[2]s). - Diagnostic inspection:
inspect(value, { colors, compact, depth, breakLength, sorted, trailingComma, showHidden })handles cycles safely. - ANSI stripping:
stripAnsiCode(text)(also at"vael:fmt/strip-ansi-code"). - Human-readable sizes & durations:
"vael:fmt/bytes"(format) and"vael:fmt/duration"(format).
import { echof, errorf, inspect, sprintf, stripAnsiCode } from "vael:fmt";import { format as formatBytes } from "vael:fmt/bytes";import { format as formatDuration } from "vael:fmt/duration";
const summary = sprintf( "Bundle %s built in %s", formatBytes(1_572_864, { binary: true }), // "1.5 MiB" formatDuration(99_674, { ignoreZero: true }), // "1m 39s 674ms");echof("%s", summary);
console.log(inspect({ status: "ok", items: [1, 2, 3] }, { colors: false, sorted: true }));console.log(stripAnsiCode("\x1b[32mOK\x1b[0m"));
if (false) { throw errorf("Artifact %s exceeded %d bytes", "app.tar.gz", 1024);}6. Safe Log Hygiene (Never Persist Untrusted ANSI)
Section titled “6. Safe Log Hygiene (Never Persist Untrusted ANSI)”Whenever you write logs to disk, emit structured JSONL, or echo untrusted user input (request paths, branch names, filenames), strip ANSI sequences and ASCII control bytes first so untrusted input cannot forge log lines or inject terminal escapes:
import { info } from "vael:console";import { stripAnsiCode } from "vael:fmt/strip-ansi-code";import { writeFileAtomic } from "vael:fs";import { Buffer } from "node:buffer";
export function sanitizeLogText(input: string): string { return stripAnsiCode(input).replace(/[\x00-\x1f\x7f]/g, " ");}
const safePath = sanitizeLogText("/items\x1b[31mFAKE\r\nINFO forged");info("GET", safePath, 404);
const line = JSON.stringify({ event: "not_found", path: safePath }) + "\n";writeFileAtomic("./audit.jsonl", Buffer.from(line, "utf8"), { sync: true });