Skip to content

lumen ​

@c9up/lumen: terminal output with no dependencies: colours, a logger with a fixed vocabulary, tables, boxes, steps and task reports, plus a raw mode that makes all of it assertable. Guide: Terminal output.

Installation ​

bash
pnpm add @c9up/lumen

@c9up/ream depends on lumen, and @c9up/ream/console re-exports Ui, Logger, Action, Box, Table, Tasks and TaskContext for commands.

Entry points ​

ImportContents
@c9up/lumenlumen(), Ui, the logger, the widgets, the renderers, colours and layout helpers.
@c9up/lumen/colorsThe colour implementations and supportsColor, without the widgets and without any node: import.
@c9up/lumen/helpersText measurement and layout: stringWidth, terminalWidth, justify, wrap, truncate, sanitize.

Exports ​

@c9up/lumen ​

ExportKindDescription
lumenfunctionBuilds a Ui, detecting the mode when it is not given.
UiclassOne object carrying the colours, the logger and the widgets.
UiModetype"normal" | "silent" | "raw".
LumenOptionsinterfaceLoggerOptions plus mode?: UiMode.
LoggerclassThe logger: one method per level, actions and spinners.
LoggerOptionsinterfacedim?: boolean dims the whole message; dimLabels?: boolean dims only the labels (defaults to dim).
MessageOptionsinterfacePer-message decoration: prefix, suffix, startTime, silent.
ActionclassA step whose outcome is reported once it is over.
SpinnerclassA message with animated trailing dots, for work of unknown length.
SpinnerDecoratortype(text: string, options: MessageOptions) => () => string.
BoxclassA bordered box, built by ui.sticker() and ui.instructions().
BorderPaintertype(character: string, colors: Colors) => string, called for every border glyph.
TableclassA bordered table.
TableCellinterfaceOne cell with layout hints: content, hAlign, vAlign, colSpan, rowSpan.
TableInputtypestring | TableCell.
TableRowtypereadonly TableInput[] | Record<string, readonly TableInput[]>.
TableCharsinterfaceThe border glyphs (top, top-mid, left, mid-mid, …).
TableOptionsinterfaceraw?: boolean prints cells joined by | with no border or colour; chars?: Partial<TableChars>.
errorsnamespaceThe package's errors, one class per code, see Errors.
StepsclassA numbered list of things to do next.
TasksclassA sequence of steps run in order, each with its outcome.
TaskclassOne step: its state, and the API its callback uses to report progress.
TaskContextclassAlias of Task.
TaskCallbacktype(task: Task) => Promise<TaskResult> | TaskResult.
TaskResulttypestring | Error | TaskError | Task | undefined: what a task callback may return.
TaskErrorinterface{ message: string; isError: true }: a failure reported as a value.
TaskFailuretypeWhat task.error() returns: the Error itself, or a TaskError for a string.
TaskOutcomeinterface{ title, state: "succeeded" | "failed", message, duration: string | null, error?: Error }.
TaskStatetype"idle" | "running" | "succeeded" | "failed".
TasksOptionsinterfaceicons?: boolean marks each outcome with a glyph; verbose?: boolean prints every progress message.
RendererinterfaceWhere lines go: log, logError, logUpdate, logUpdatePersist, getLogs, flushLogs.
ConsoleRendererclassWrites to the process streams; keeps nothing.
MemoryRendererclassKeeps every line in memory instead of printing it.
CapturedLoginterface{ message: string; stream: Stream }.
Streamtype"stdout" | "stderr".
ColorsinterfaceA chain of styles that renders text: colors.dim.yellow("text").
ColorStreaminterface{ isTTY?: boolean }: a stream that can be asked about colour support.
StyleNametypeThe name of one style (bold, red, bgBlue, …).
STYLE_NAMESconstEvery style name, in declaration order.
ansiColorsfunctionansiColors(): Colors: escape codes.
silentColorsfunctionsilentColors(): Colors: no transformation.
rawColorsfunctionrawColors(): Colors: the transformations spelled out, dim(yellow(2 files)).
supportsColorfunctionsupportsColor(stream?: ColorStream, env?: Record<string, string | undefined>, argv?: readonly string[]): boolean.
stripAnsifunctionstripAnsi(text: string): string: drops every escape sequence.
sanitizefunctionsanitize(text: string, options?: SanitizeOptions): string: renders every control character visibly.
SanitizeOptionsinterfacekeepNewlines?: boolean leaves \n alone.
stringWidthfunctionstringWidth(text: string): number: terminal columns a string occupies, escape codes excluded.
terminalWidthfunctionterminalWidth(): number: columns available, or 80 when the output is not a terminal.
justifyfunctionjustify(columns: readonly string[], options: JustifyOptions): string[]: pads every column to the same width.
JustifyOptionsinterfacemaxWidth: number, align?: "left" | "right", paddingChar?: string (a space by default).
wrapfunctionwrap(columns: readonly string[], options: WrapOptions): string[]: wraps between two columns.
WrapOptionsinterfacestartColumn: number, endColumn: number, trimStart?: boolean.
truncatefunctiontruncate(columns: readonly string[], options: TruncateOptions): string[]: cuts each column to maxWidth.
TruncateOptionsinterfacemaxWidth: number, truncationChar?: string (an ellipsis by default), position?: "start" | "middle" | "end".
formatDurationfunctionformatDuration(milliseconds: number): string: the shortest precise form.
elapsedSincefunctionelapsedSince(start: StartTime, now?: number): number: milliseconds elapsed.
StartTimetypenumber | bigint | [number, number]: Date.now(), process.hrtime.bigint() or a process.hrtime() tuple.
iconsconstThe glyph set for the current platform.
iconsForfunctioniconsFor(platform?: string, env?: Record<string, string | undefined>): Icons.
Iconsinterfacetick, cross, bullet, pointer, info, warning, squareSmallFilled and the six border glyphs.

@c9up/lumen/colors ​

ansiColors, silentColors, rawColors, supportsColor, stripAnsi, STYLE_NAMES, and the types Colors, ColorStream, StyleName: the same as above.

@c9up/lumen/helpers ​

stringWidth, terminalWidth, justify, wrap, truncate, sanitize, and the types JustifyOptions, WrapOptions, TruncateOptions, SanitizeOptions: the same as above.

lumen() ​

ts
function lumen(options?: LumenOptions): Ui

Without mode, the stream decides between normal and silent: FORCE_COLOR and the --color / --no-color flags first, then NO_COLOR, then whether the stream is a terminal, then TERM=dumb and known CI services. raw is never detected; pass it in tests.

ModeColoursOutput
normalescape codesthe terminal
silentnonethe terminal
rawspelled out, dim(yellow(2 files))memory

Ui ​

MemberSignatureDescription
constructornew Ui(mode?: UiMode, options?: LoggerOptions)
modeget mode(): UiModeThe current mode.
colorsget colors(): ColorsThe colours of the current mode.
loggerget logger(): LoggerThe logger.
iconsget icons(): IconsThe glyph set.
switchModeswitchMode(mode: UiMode): thisSwaps the mode, and with it the colours and where lines go.
useRendereruseRenderer(renderer: Renderer): thisReplaces the renderer every widget writes through.
useColorsuseColors(colors: Colors): thisReplaces the colours.
writewrite(line: string, stream?: Stream): voidWrites one line through the renderer.
getLogsgetLogs(): string[]Everything written since raw mode was switched on.
getCapturedLogsgetCapturedLogs(): CapturedLog[]The same lines, each with its stream.
flushLogsflushLogs(): voidEmpties the captured lines.
getTableRowsgetTableRows(): string[][]Rows of the last table built through this UI, as given.
getTableHeadgetTableHead(): string[]Head cells of that table.
tabletable(options?: TableOptions): TableA new table.
stickersticker(): BoxA highlighted block.
instructionsinstructions(): BoxThe same box, every line marked with a pointer.
stepssteps(): StepsNumbered steps.
taskstasks(options?: TasksOptions): TasksA task list.

In raw mode, widgets drop their layout: a table prints its cells joined by |, boxes print the heading and lines without a frame, steps print their lines without indent.

Logger ​

MemberSignatureDescription
constructornew Logger(colors: Colors, renderer?: Renderer, options?: LoggerOptions)
colorsget colors(): ColorsAlso getColors().
useColorsuseColors(colors: Colors): this
getRenderer / useRenderergetRenderer(): Renderer / useRenderer(renderer: Renderer): this
getLogsgetLogs(): CapturedLog[]What was captured, each line with its stream.
flushLogsflushLogs(): void
prefixprefix(value: string): thisPrepends a fixed marker to every later message.
suffixsuffix(value: string): thisAppends a fixed marker to every later message.
childchild(options?: LoggerOptions): LoggerA child sharing the colours and renderer, with its own options.
dummydummy(): LoggerA logger that discards everything.
successsuccess(message: string, options?: MessageOptions): void[ success ], green, stdout.
infoinfo(message: string, options?: MessageOptions): void[ info ], blue, stdout.
warningwarning(message: string, options?: MessageOptions): void[ warn ], yellow, stderr.
errorerror(message: string | Error, options?: MessageOptions): void[ error ], red, stderr.
fatalfatal(message: string | Error, options?: MessageOptions): voidAn error plus its stack, indented and dimmed, stderr.
debugdebug(message: string, options?: MessageOptions): void[ debug ], cyan. Always prints.
loglog(message: string, stream?: Stream): voidA line with no decoration: the command's own output.
logErrorlogError(message: string): voidThe same, on stderr.
logUpdatelogUpdate(message: string): voidOverwrites the line written last.
logUpdatePersistlogUpdatePersist(): voidMakes the last updated line permanent.
actionaction(title: string): ActionA step whose outcome is reported later.
awaitawait(message: string, options?: MessageOptions): Spinner[ wait ] with animated dots.
prepareprepare(level, message: string, options?: MessageOptions): stringBuilds the line without writing it. Level: "success" | "error" | "fatal" | "warning" | "info" | "debug" | "await".
prepareSuccess … prepareDebugprepareSuccess(message, options?): stringOne prepare per level: prepareSuccess, prepareInfo, prepareWarning, prepareError, prepareFatal, prepareDebug.

MessageOptions:

FieldTypeDescription
prefixstring | numberRendered dim ahead of the label; %time% becomes the current ISO time.
suffixstring | numberRendered dim yellow, in parentheses, after the message.
startTimeStartTimeWhen the work started; the elapsed time is appended.
silentbooleanBuilds the line but does not write it.

Action ​

MemberSignatureDescription
displayDurationdisplayDuration(): thisAppends how long the action took.
succeededsucceeded(): voidWrites the DONE line.
skippedskipped(reason?: string): voidWrites the SKIPPED line.
failedfailed(error: unknown): voidWrites the FAILED line.
prepareSucceeded / prepareSkipped / prepareFailed(…): stringThe same lines, without writing them.
prepareprepare(label: string, colour: "green" | "cyan" | "red"): string

Spinner ​

MemberSignatureDescription
FRAMESstatic readonly FRAMES: string[]The animation frames.
INTERVALstatic readonly INTERVAL = 200Milliseconds between frames.
startstart(): this
updateupdate(render: string | (() => string), options?: MessageOptions): thisChanges the text, keeping the label and options.
taptap(writer: (line: string) => void): thisWrites the animation yourself instead of the renderer.
stopstop(): void

Table ​

MemberSignatureDescription
constructornew Table(colors: Colors, renderer: Renderer, options?: TableOptions)
headhead(columns: readonly TableInput[]): this
rowrow(cells: TableRow): this
getRowsgetRows(): string[][]The rows as given, unpadded.
getHeadgetHead(): string[]
fullWidthfullWidth(renderFullWidth?: boolean): thisStretches to the terminal width; one column absorbs the slack.
fluidColumnIndexfluidColumnIndex(index: number): thisWhich column absorbs the slack (the first by default).
columnWidthscolumnWidths(widths: readonly number[]): thisFixes the column widths, padding included.
prepareprepare(): string[]The rendered lines, without writing them.
renderrender(): void
getColors / useColors / getRenderer / useRendererAs on Logger.

Cells are sanitised before they are measured.

Box ​

MemberSignatureDescription
constructornew Box(colors: Colors, renderer: Renderer, options?: { pointer?: boolean; icons?: boolean; raw?: boolean })
headingheading(text: string): this
addadd(line: string): this
fullScreenfullScreen(): thisStretches the box to the terminal width.
drawBorderdrawBorder(painter: BorderPainter): this
prepareprepare(): string[]
renderrender(stream?: "stdout" | "stderr"): void
getColors / useColors / getRenderer / useRendererAs on Logger.

Steps ​

MemberSignatureDescription
constructornew Steps(colors: Colors, renderer: Renderer, options?: { raw?: boolean })
addadd(title: string, content?: string): this
prepareprepare(): string[]
renderrender(): void
getColors / useColors / getRenderer / useRendererAs on Logger.

Tasks ​

MemberSignatureDescription
constructornew Tasks(colors: Colors, renderer: Renderer, options?: TasksOptions)
addadd(title: string, work: TaskCallback): this
addIfaddIf(condition: boolean, title: string, work: TaskCallback): thisAdds the task only when the condition holds.
addUnlessaddUnless(condition: boolean, title: string, work: TaskCallback): this
taskstasks(): Task[]Every task, in declaration order.
getStategetState(): TaskStatefailed as soon as one did; succeeded once they all have.
outcomesget outcomes(): TaskOutcome[]Results in declaration order, including the task that failed.
runrun(): Promise<TaskOutcome[]>
getColors / useColors / getRenderer / useRendererAs on Logger.

Task ​

MemberSignatureDescription
constructornew Task(title: string)
titleget title(): string
getStategetState(): TaskState
getDurationgetDuration(): string | nullFormatted; null until it finishes.
getErrorgetError(): unknown
getSuccessMessagegetSuccessMessage(): string | nullThe final message, or the last progress message.
getLastLoggedLinegetLastLoggedLine(): string | null
onUpdateonUpdate(listener: (task: Task) => void): thisCalled whenever the task moves.
startstart(): this
updateupdate(message: string): thisReports progress.
markAsSucceededmarkAsSucceeded(message?: string): this
markAsFailedmarkAsFailed(error: unknown): this
errorerror(reason: string): TaskError / error<T extends Error>(reason: T): TMarks the task failed and returns the failure.

ConsoleRenderer, MemoryRenderer ​

Both implement Renderer:

MemberSignatureDescription
loglog(message: string, stream?: Stream): void
logErrorlogError(message: string): void
logUpdatelogUpdate(message: string): voidOverwrites the last line; a plain line in memory.
logUpdatePersistlogUpdatePersist(): void
getLogsgetLogs(): CapturedLog[]Always empty for ConsoleRenderer.
flushLogsflushLogs(): void

Errors ​

CodeRaised when
E_LUMEN_INVALID_COLUMNfluidColumnIndex() or columnWidths() gets a negative or fractional value, a colSpan / rowSpan is not a positive integer, or fullWidth() names a fluid column the table does not have.
E_LUMEN_TASK_NO_RESULTA task callback returned nothing and did not mark the task itself; found on the outcome's error, not thrown.
E_LUMEN_TASK_FAILEDA task failed with something that is not an Error (a string, a thrown value, a returned { message, isError: true }); found on the outcome's error, with the original value as cause.
E_LUMEN_INTERNALAn invariant inside lumen broke; a bug to report.

Migration ​

  • InvalidColumnError is now errors.E_LUMEN_INVALID_COLUMN: replace instanceof InvalidColumnError with error.code === 'E_LUMEN_INVALID_COLUMN' or instanceof errors.E_LUMEN_INVALID_COLUMN.
  • A task's failure built from a value that is not an Error is errors.E_LUMEN_TASK_FAILED, and a task that returned nothing is errors.E_LUMEN_TASK_NO_RESULT: read error.code on the outcome.

See also ​