Skip to content

API Design & Reference

Last Updated: 2026-06-28

API Style

@jsvision/core is an ESM-only TypeScript library. The public contract is the set of exports of src/engine/index.ts — the single entry point. Everything else under src/engine/** is internal and may change without a major bump (see the README "Versioning & stability" policy and ADR-001).

  • Module system: ESM only; require() is unsupported (no CommonJS condition).
  • Import specifiers: NodeNext — .js extensions on source imports.
  • Stability: pre-1.0 the surface may change between minors; the index exports are the contract, internals are not.

Conventions

  • Pure where possible: rendering, decoding, and colour encoding are pure functions. The only stateful API is the host.
  • Injectable seams: capabilities (TerminalQuery), the runtime (RuntimeAdapter), and the style encoder (StyleEncoder) are all injectable — tests pass fakes, production passes real implementations.
  • Frozen results: a resolved CapabilityProfile is deeply frozen.
  • Typed errors: failures throw subclasses of TuiError.

Public Surface by Subsystem

The reference below groups the src/engine/index.ts exports. Each symbol carries JSDoc in source (purpose, params, returns, side effects).

Package

SymbolKindSummary
VERSIONconstThe package version string (SemVer).

Capability detection (RD-02)

SymbolKindSummary
resolveCapabilities(options)fnResolve a frozen CapabilityProfile from env/platform/table/override (sync).
resolveCapabilitiesAsync(options)fnAs above plus a bounded layer-2 live TerminalQuery.
CapabilityProfile, CapabilityResolution, CapabilityReasonstypeThe resolved profile, result, and per-field provenance.
ColorDepth, GlyphCaps, KeyboardCaps, MouseCaps, OscCaps, UnicodeCapstypeCapability field shapes.
ResolveOptions, SyncResolveOptions, TerminalQuerytypeInputs + the live-query seam.
Platform, ReasonLayer, DeepPartialtypeSupporting types.

Input decoder (RD-06)

SymbolKindSummary
createDecoderState()fnCreate the mutable decoder carry state.
decode(bytes, state, options)fnDecode a byte chunk into InputEvents (pure transform + carry).
flush(state)fnFlush a pending escape/partial sequence at end-of-input.
createKeymap()fnBuild the default key map.
ESC_TIMEOUT_MS, PASTE_CAP_BYTESconstDecoder timing/size bounds.
KeyEvent, MouseEvent, WheelEvent, PasteEvent, FocusEvent, InputEvent, QueryResponsetypeDecoded event shapes.
DecodeResult, DecoderState, DecodeOptions, KeymaptypeDecoder I/O types.

Rendering engine (RD-04)

SymbolKindSummary
ScreenBufferclassWidth-correct cell grid; set/text/fillRect/box/shadow/rows.
serialize(current, previous, options)fnPure damage-diff → minimal ANSI (bytes ∝ damage).
defaultEncodeStyleconstThe default StyleEncoder (RD-05 encodeStyle).
fallbackGlyph(char, caps)fnCapability-driven ASCII glyph fallback.
AttrconstAttribute bit flags (bold, reverse, …).
charWidth(cp, mode)fnDisplay width of a code point.
hyperlink, setClipboard, setTitle, bell, notifyfnOSC feature emitters.
cursor, CSI, SGR_RESET, SYNC_BEGIN, SYNC_END, cursorToconst/fnCursor + low-level ANSI helpers.
Cell, Style, Color, Ansi16Name, AttrMask, WidthMode, StyleEncoder, RenderOptionstypeRender data + option types.

Color & styling (RD-05)

SymbolKindSummary
encode(color, role, depth)fnEncode one colour to a standalone SGR for a depth.
encodeStyle(fg, bg, attrs, caps)fnMerge attrs + fg + bg into one depth-aware SGR (the serialize default).
styleKey(fg, bg, attrs)fnStable key for a style (cache/dedup).
nearest256(rgb), nearest16(rgb)fnRedmean nearest-colour downsampling.
InvalidColorErrorclassThrown on malformed colour input (extends TuiError).
PALETTE, defaultThemeconstDOS-16 palette + typed default theme.
ColorRole, Rgb, Theme, ThemeRoletypeColour/theme types.

Host & lifecycle (RD-07) — the only stateful subsystem

SymbolKindSummary
createHost(options)fnNative tty host: raw mode, alt-screen, signals, guaranteed restore.
detectTty(streams)fnPre-start TTY probe (RD-08 PF-001).
createTerminalQuery(options)fnReal tty-backed TerminalQuery (completes RD-02 layer-2).
Host, HostOptions, ResizeEvent, RuntimeAdapter, HostSignal, TimerHandle, StreamOptions, TerminalQueryOptions, ManagedTerminalQuerytypeHost API + the injectable runtime seam.

Safety (RD-08)

SymbolKindSummary
sanitize(str)fnCanonical injection boundary: strip control bytes from untrusted text.
evaluateEssentials(facts), essentialsMet(report), assertEssentials(facts)fnThe pre-start essentials gate.
createLogger(options)fnScreen-safe logger (never corrupts the alt-screen).
redactEvent(event), dumpCaps(caps)fnRedaction + capability dump (no secrets/PII).
TuiError, EssentialsNotMetError, LoggerConfigErrorclassTyped error model.
EssentialsReport, Degradation, HostFacts, Logger, LoggerOptions, LogLevel, LogRecord, LogSink, LoggerFs, RedactedEventtypeSafety types.

Error Handling

All thrown errors extend TuiError. Notable cases:

ErrorWhenNotes
EssentialsNotMetErrorThe essentials gate fails (e.g. non-TTY / TERM=dumb)Degrades, never crashes mid-render
InvalidColorErrorA malformed colour reaches encode()The render-path encoder seam degrades crash-safe instead
LoggerConfigErrorInvalid logger configurationThrown at logger construction

Performance Contract

  • Composing + diff-serializing a 200×50 frame has a median ≤ 16 ms on a modern dev machine (npm run bench; enforced off-CI by test/perf-budget.spec.test.ts).
  • A steady-state single-cell update emits a byte count independent of screen size (output ∝ damage).
  • Capability detection against a non-responding terminal falls back within timeoutMs + slack.