or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

console-integration.mdcore-logging.mdindex.mdinstance-management.mdprompts.mdreporters.mdutilities.md
tile.json

utilities.mddocs/

Utilities

Formatting and display utilities including box drawing with customizable styles, color functions with terminal support detection, string alignment and manipulation, and hierarchical tree structure rendering.

Capabilities

Box Drawing

Create styled text boxes with customizable borders, colors, and layout options for highlighted messages and notices.

/**
 * Create a styled text box with customizable appearance
 * @param text - Text content to display in the box
 * @param opts - Box styling and layout options
 * @returns Formatted box string ready for console output
 */
function box(text: string, opts?: BoxOpts): string;

interface BoxOpts {
  /** Title displayed at the top of the box */
  title?: string;
  /** Box styling configuration */
  style?: Partial<BoxStyle>;
}

interface BoxStyle {
  /** Border color using color names or hex values */
  borderColor: ColorName;
  /** Border style using preset names or custom characters */
  borderStyle: BoxBorderStyle | keyof typeof boxStylePresets;
  /** Vertical text alignment within the box */
  valign: "top" | "center" | "bottom";
  /** Inner padding around text content */
  padding: number;
  /** Left margin spacing */
  marginLeft: number;
  /** Top margin spacing */
  marginTop: number;
  /** Bottom margin spacing */
  marginBottom: number;
}

Usage Examples:

import { box } from "consola/utils";

// Simple box with default styling
const simpleBox = box("Hello World");
console.log(simpleBox);
/*
╭─────────────╮
│  Hello World  │
╰─────────────╯
*/

// Box with title and custom styling
const styledBox = box("System maintenance in progress", {
  title: "Notice",
  style: {
    borderColor: "yellow",
    borderStyle: "double",
    padding: 3,
    valign: "center"
  }
});

// Multi-line content box
const multiBox = box(
  "Line 1\nLine 2\nLine 3",
  {
    title: "Multi-line Content",
    style: {
      borderColor: "cyan",
      borderStyle: "solid",
      valign: "top"
    }
  }
);

Border Styles

Predefined and custom border character sets for box drawing.

interface BoxBorderStyle {
  /** Top-left corner character */
  tl: string;
  /** Top-right corner character */
  tr: string;
  /** Bottom-left corner character */
  bl: string;
  /** Bottom-right corner character */
  br: string;
  /** Horizontal line character */
  h: string;
  /** Vertical line character */
  v: string;
}

// Predefined border styles
const boxStylePresets: Record<string, BoxBorderStyle> = {
  solid: { tl: "┌", tr: "┐", bl: "└", br: "┘", h: "─", v: "│" },
  double: { tl: "╔", tr: "╗", bl: "╚", br: "╝", h: "═", v: "║" },
  rounded: { tl: "╭", tr: "╮", bl: "╰", br: "╯", h: "─", v: "│" },
  singleThick: { tl: "┏", tr: "┓", bl: "┗", br: "┛", h: "━", v: "┃" }
};

Usage Examples:

// Using preset styles
const doubleBox = box("Important Notice", {
  style: { borderStyle: "double" }
});

const roundedBox = box("Friendly Message", {
  style: { borderStyle: "rounded" }
});

// Custom border style
const customBox = box("Custom Border", {
  style: {
    borderStyle: {
      tl: "*", tr: "*", bl: "*", br: "*",
      h: "-", v: "|"
    }
  }
});

Color Functions

Terminal color support with automatic detection and fallback for different environments.

/**
 * Get color function by name with fallback support
 * @param color - Color name to retrieve
 * @param fallback - Fallback color if primary not available
 * @returns Color function that applies the specified color
 */
function getColor(color: ColorName, fallback?: ColorName): ColorFunction;

/**
 * Apply color to text string or number
 * @param color - Color name to apply
 * @param text - Text content to colorize
 * @returns Colored text string
 */
function colorize(color: ColorName, text: string | number): string;

/** Color function type that applies color formatting */
type ColorFunction = (text: string | number) => string;

/** Object containing all available color functions */
const colors: Record<ColorName, ColorFunction>;

Usage Examples:

import { colors, getColor, colorize } from "consola/utils";

// Direct color usage
console.log(colors.red("Error message"));
console.log(colors.green("Success!"));
console.log(colors.yellow("Warning"));

// Dynamic color selection
const errorColor = getColor("red", "white");
console.log(errorColor("Fallback error message"));

// Colorize function
const blueText = colorize("blue", "Information");
const cyanNumber = colorize("cyan", 42);

// Background colors
console.log(colors.bgRed(colors.white("Alert")));
console.log(colors.bgGreen(colors.black("Success")));

// Text styling
console.log(colors.bold("Bold text"));
console.log(colors.italic("Italic text"));
console.log(colors.underline("Underlined text"));

Available Colors

Complete color palette with standard and bright variants.

type ColorName = 
  // Standard colors
  | "black" | "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "white" | "gray"
  // Bright colors  
  | "blackBright" | "redBright" | "greenBright" | "yellowBright" 
  | "blueBright" | "magentaBright" | "cyanBright" | "whiteBright"
  // Background colors
  | "bgBlack" | "bgRed" | "bgGreen" | "bgYellow" | "bgBlue" | "bgMagenta" | "bgCyan" | "bgWhite"
  // Bright background colors
  | "bgBlackBright" | "bgRedBright" | "bgGreenBright" | "bgYellowBright"
  | "bgBlueBright" | "bgMagentaBright" | "bgCyanBright" | "bgWhiteBright"
  // Text styles
  | "reset" | "bold" | "dim" | "italic" | "underline" | "inverse" | "hidden" | "strikethrough";

String Utilities

Text alignment, formatting, and ANSI escape code handling functions.

/**
 * Remove ANSI escape codes from text
 * @param text - Text containing ANSI codes
 * @returns Clean text without formatting codes
 */
function stripAnsi(text: string): string;

/**
 * Center-align text within specified width
 * @param str - Text to center
 * @param len - Total width for centering
 * @param space - Padding character (default: space)
 * @returns Center-aligned text
 */
function centerAlign(str: string, len: number, space?: string): string;

/**
 * Right-align text within specified width
 * @param str - Text to align
 * @param len - Total width for alignment
 * @param space - Padding character (default: space)
 * @returns Right-aligned text
 */
function rightAlign(str: string, len: number, space?: string): string;

/**
 * Left-align text within specified width
 * @param str - Text to align
 * @param len - Total width for alignment  
 * @param space - Padding character (default: space)
 * @returns Left-aligned text
 */
function leftAlign(str: string, len: number, space?: string): string;

/**
 * Align text using specified alignment mode
 * @param alignment - Alignment mode
 * @param str - Text to align
 * @param len - Total width for alignment
 * @param space - Padding character (default: space)
 * @returns Aligned text
 */
function align(
  alignment: "left" | "right" | "center",
  str: string,
  len: number,
  space?: string
): string;

Usage Examples:

import { stripAnsi, centerAlign, rightAlign, leftAlign, align } from "consola/utils";

// Remove ANSI codes for length calculation
const coloredText = "\x1b[31mRed Text\x1b[0m";
const cleanText = stripAnsi(coloredText); // "Red Text"
const length = cleanText.length; // 8

// Text alignment
const centered = centerAlign("Hello", 20);     // "       Hello        "
const rightAligned = rightAlign("World", 20);  // "               World"
const leftAligned = leftAlign("Test", 20);     // "Test                "

// Generic alignment function
const alignedText = align("center", "Content", 30);

// Custom padding character
const paddedWithDots = centerAlign("Title", 20, ".");  // ".......Title......."

// Practical usage in formatting
function formatTableRow(col1: string, col2: string, col3: string) {
  return [
    leftAlign(col1, 15),
    centerAlign(col2, 10),
    rightAlign(col3, 8)
  ].join(" | ");
}

console.log(formatTableRow("Name", "Status", "Count"));
console.log(formatTableRow("John", "Active", "42"));

Tree Rendering

Hierarchical tree structure rendering with customizable styling and depth control.

/**
 * Format hierarchical data as a tree structure
 * @param items - Array of tree items to render
 * @param options - Tree rendering configuration
 * @returns Formatted tree string
 */
function formatTree(items: TreeItem[], options?: TreeOptions): string;

/** Tree item can be simple string or object with children */
type TreeItem = string | TreeItemObject;

interface TreeItemObject {
  /** Text content for this tree node */
  text: string;
  /** Child items under this node */
  children?: TreeItem[];
  /** Color for this specific item */
  color?: ColorName;
}

interface TreeOptions {
  /** Overall tree color */
  color?: ColorName;
  /** Prefix for tree branch characters */
  prefix?: string;
  /** Maximum depth to render */
  maxDepth?: number;
  /** Ellipsis text for truncated branches */
  ellipsis?: string;
}

Usage Examples:

import { formatTree } from "consola/utils";

// Simple string tree
const simpleTree = formatTree([
  "Root Item",
  "Another Root Item",
  "Third Root Item"
]);
console.log(simpleTree);
/*
├─Root Item
├─Another Root Item
└─Third Root Item
*/

// Hierarchical tree with objects
const hierarchicalTree = formatTree([
  {
    text: "src",
    children: [
      "index.ts",
      {
        text: "components",
        children: [
          "Button.tsx",
          "Input.tsx"
        ]
      },
      "utils.ts"
    ]
  },
  {
    text: "tests",
    children: [
      "unit.test.ts",
      "integration.test.ts"
    ]
  }
]);

// Tree with colors and custom options
const coloredTree = formatTree([
  {
    text: "Database",
    color: "green",
    children: [
      { text: "Connected", color: "green" },
      { text: "Tables: 15", color: "cyan" }
    ]
  },
  {
    text: "Redis",
    color: "red", 
    children: [
      { text: "Disconnected", color: "red" },
      { text: "Retrying...", color: "yellow" }
    ]
  }
], {
  color: "blue",
  prefix: "  ",
  maxDepth: 3
});

// File system representation
const fileTree = formatTree([
  {
    text: "project/",
    children: [
      "package.json",
      "README.md",
      {
        text: "src/",
        children: [
          "main.ts",
          "types.ts",
          {
            text: "lib/",
            children: ["utils.ts", "helpers.ts"]
          }
        ]
      },
      {
        text: "dist/",
        children: ["main.js", "main.d.ts"]
      }
    ]
  }
]);

Practical Usage Patterns

Real-world utility combinations for common formatting tasks.

Usage Examples:

import { box, colors, formatTree, centerAlign } from "consola/utils";

// Status dashboard
function createStatusDashboard(services: any[]) {
  const statusTree = services.map(service => ({
    text: service.name,
    color: service.status === "online" ? "green" : "red",
    children: [
      `Status: ${service.status}`,
      `Uptime: ${service.uptime}`,
      `Load: ${service.load}`
    ]
  }));
  
  const treeOutput = formatTree(statusTree, { prefix: "  " });
  
  return box(treeOutput, {
    title: "Service Status",
    style: {
      borderColor: "cyan",
      borderStyle: "rounded",
      padding: 2
    }
  });
}

// Configuration summary
function displayConfig(config: Record<string, any>) {
  const configLines = Object.entries(config).map(([key, value]) => {
    const formattedKey = rightAlign(key + ":", 20);
    const formattedValue = colors.cyan(String(value));
    return `${formattedKey} ${formattedValue}`;
  });
  
  return box(configLines.join("\n"), {
    title: "Configuration",
    style: { borderColor: "yellow" }
  });
}

// Progress indicator with tree
function showBuildProgress(steps: Array<{name: string; status: 'pending' | 'running' | 'done' | 'error'}>) {
  const treeItems = steps.map(step => {
    let color: ColorName = "gray";
    let icon = "○";
    
    switch(step.status) {
      case "running": color = "yellow"; icon = "◐"; break;
      case "done": color = "green"; icon = "●"; break;
      case "error": color = "red"; icon = "✗"; break;
    }
    
    return {
      text: `${icon} ${step.name}`,
      color
    };
  });
  
  return formatTree(treeItems, { prefix: "  " });
}

Types

interface BoxOpts {
  title?: string;
  style?: Partial<BoxStyle>;
}

interface BoxBorderStyle {
  tl: string; tr: string; bl: string; br: string;
  h: string; v: string;
}

type ColorName = "black" | "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "white" | "gray" | /* ... all color variants */;

type ColorFunction = (text: string | number) => string;

type TreeItem = string | TreeItemObject;

interface TreeItemObject {
  text: string;
  children?: TreeItem[];
  color?: ColorName;
}