Node.js SDK API Reference

May 2, 2026 · View on GitHub

Complete API reference for the BoxLite Node.js/TypeScript SDK.

Node.js: 18+ Platforms: macOS (Apple Silicon), Linux (x86_64, ARM64)

Table of Contents


Runtime Management

JsBoxlite / Boxlite

The main runtime for creating and managing boxes.

import { JsBoxlite } from 'boxlite';
// or use the wrapper classes
import { SimpleBox } from 'boxlite';

Constructor

new JsBoxlite(options: JsOptions)

Static Methods

MethodSignatureDescription
withDefaultConfig()() => JsBoxliteGet runtime with default config (~/.boxlite)
initDefault()(options: JsOptions) => voidInitialize default runtime with custom options

Instance Methods

MethodSignatureDescription
create()(options: JsBoxOptions, name?: string) => Promise<JsBox>Create a new box
listInfo()() => Promise<JsBoxInfo[]>List all boxes
getInfo()(idOrName: string) => Promise<JsBoxInfo | null>Get box info
get()(idOrName: string) => Promise<JsBox | null>Get box handle
metrics()() => Promise<JsRuntimeMetrics>Get runtime metrics
remove()(idOrName: string, force?: boolean) => Promise<void>Remove a box
close()() => voidClose runtime (no-op)

Example

// Default runtime
const runtime = JsBoxlite.withDefaultConfig();

// Custom runtime
const runtime = new JsBoxlite({ homeDir: '/custom/path' });

// Create a box
const box = await runtime.create({
  image: 'alpine:latest',
  cpus: 2,
  memoryMib: 512
}, 'my-box');

// List all boxes
const boxes = await runtime.listInfo();
boxes.forEach(info => console.log(`${info.id}: ${info.status}`));

JsOptions

Runtime configuration options.

FieldTypeDefaultDescription
homeDirstring~/.boxliteBase directory for runtime data
imageRegistriesJsImageRegistry[][]Registry transport, TLS, search, and auth configuration

JsBoxOptions

Configuration options for creating a box.

FieldTypeDefaultDescription
imagestring-OCI image URI
rootfsPathstring-Pre-prepared rootfs directory (alternative to image)
cpusnumber1Number of CPU cores
memoryMibnumber512Memory limit in MiB
diskSizeGbnumber-Persistent disk size in GB
workingDirstring"/root"Working directory inside container
envJsEnvVar[][]Environment variables
volumesJsVolumeSpec[][]Volume mounts
networkNetworkSpec{ mode: "enabled" }Structured network configuration
portsJsPortSpec[][]Port mappings
secretsSecret[][]Outbound HTTP(S) secret substitution rules
autoRemovebooleanfalseAuto cleanup when stopped
detachbooleanfalseSurvive parent process exit

NetworkSpec

interface NetworkSpec {
  mode: "enabled" | "disabled";
  allowNet?: string[];
}

Use allowNet only when mode: "enabled". Empty or omitted allowNet means full outbound access. mode: "disabled" removes the guest network interface entirely.

JsEnvVar

interface JsEnvVar {
  key: string;
  value: string;
}

JsVolumeSpec

interface JsVolumeSpec {
  hostPath: string;    // Path on host
  guestPath: string;   // Path in container
  readOnly?: boolean;  // Default: false
}

JsPortSpec

interface JsPortSpec {
  hostPort?: number;   // None = auto-assign
  guestPort: number;   // Port inside container
  protocol?: string;   // "tcp" or "udp" (default: "tcp")
  hostIp?: string;     // Default: "0.0.0.0"
}

Secret

interface Secret {
  name: string;
  value: string;
  hosts?: string[];
  placeholder?: string; // Default: `<BOXLITE_SECRET:${name}>`
}

Box Handle

JsBox

Handle to a running or stopped box.

Properties

PropertyTypeDescription
idstringUnique box identifier (ULID)
namestring | nullUser-defined name

Methods

MethodSignatureDescription
info()() => JsBoxInfoGet box metadata (sync)
exec()(cmd, args?, env?, tty?) => Promise<JsExecution>Execute command
stop()() => Promise<void>Stop the box
metrics()() => Promise<JsBoxMetrics>Get resource metrics

JsBoxInfo

Metadata about a box.

FieldTypeDescription
idstringUnique box identifier (ULID)
namestring | undefinedUser-defined name
statusstringCurrent status: "Starting", "Running", "Stopped", etc.
createdAtstringCreation timestamp (ISO 8601)
lastUpdatedstringLast state change (ISO 8601)
pidnumber | undefinedProcess ID (if running)

Command Execution

JsExecution

Handle for a running command.

Methods

MethodSignatureDescription
id()() => Promise<string>Get execution ID
stdin()() => Promise<JsExecStdin>Get stdin writer
stdout()() => Promise<JsExecStdout>Get stdout reader
stderr()() => Promise<JsExecStderr>Get stderr reader
wait()() => Promise<JsExecResult>Wait for completion
kill()() => Promise<void>Send SIGKILL

Example

const execution = await box.exec('ls', ['-la', '/']);

// Read stdout
const stdout = await execution.stdout();
while (true) {
  const line = await stdout.next();
  if (line === null) break;
  console.log(line);
}

// Wait for completion
const result = await execution.wait();
console.log(`Exit code: ${result.exitCode}`);

JsExecStdin

Writer for sending input to a running process.

MethodSignatureDescription
write()(data: Buffer) => Promise<void>Write bytes
writeString()(text: string) => Promise<void>Write UTF-8 string
const stdin = await execution.stdin();
await stdin.writeString('Hello, World!\n');
await stdin.write(Buffer.from([10])); // newline

JsExecStdout / JsExecStderr

Readers for streaming output.

MethodSignatureDescription
next()() => Promise<string | null>Read next line (null = EOF)

Stream Consumption: Each stream can only be consumed once. After iterating to EOF, subsequent calls return null.

const stdout = await execution.stdout();
while (true) {
  const line = await stdout.next();
  if (line === null) break;
  console.log(line);
}

JsExecResult

Result of a completed execution.

FieldTypeDescription
exitCodenumberProcess exit code (0 = success)

Box Types

SimpleBox

Context manager for basic command execution with automatic cleanup.

import { SimpleBox } from 'boxlite';

Constructor Options

interface SimpleBoxOptions {
  image?: string;         // Default: "python:slim"
  memoryMib?: number;     // Memory in MiB
  cpus?: number;          // CPU cores
  runtime?: JsBoxlite;    // Runtime instance
  name?: string;          // Box name
  autoRemove?: boolean;   // Default: true
  detach?: boolean;       // Default: false
  workingDir?: string;    // Working directory
  env?: Record<string, string>;  // Environment variables
  volumes?: VolumeSpec[]; // Volume mounts
  network?: NetworkSpec;
  ports?: PortSpec[];     // Port mappings
  secrets?: Secret[];
}

Properties

PropertyTypeDescription
idstringBox ID (throws if not started)
namestring | undefinedBox name

Methods

MethodSignatureDescription
getId()() => Promise<string>Get box ID (async)
getInfo()() => Promise<JsBoxInfo>Get box info (async)
exec()(cmd, ...args) => Promise<ExecResult>Execute and wait (variadic)
exec()(cmd, args[], env?, options?) => Promise<ExecResult>Execute with options (array form)
stop()() => Promise<void>Stop the box
[Symbol.asyncDispose]()() => Promise<void>Async disposal

Example

// With async disposal (TypeScript 5.2+)
await using box = new SimpleBox({ image: 'alpine:latest' });
const result = await box.exec('echo', 'Hello!');
console.log(result.stdout);

// Manual cleanup
const box = new SimpleBox({ image: 'alpine:latest' });
try {
  const result = await box.exec('ls', '-la');
  console.log(result.stdout);

  // Per-command options (array form)
  const pwd = await box.exec('pwd', [], undefined, { cwd: '/tmp' });
  const who = await box.exec('whoami', [], undefined, { user: 'nobody' });
  const timed = await box.exec('sleep', ['60'], undefined, { timeoutSecs: 5 });
} finally {
  await box.stop();
}

The options parameter accepts { cwd?: string; user?: string; timeoutSecs?: number }.


CodeBox

Python code execution sandbox.

import { CodeBox } from 'boxlite';

Constructor Options

interface CodeBoxOptions extends SimpleBoxOptions {
  image?: string;  // Default: "python:slim"
}

Methods

MethodSignatureDescription
run()(code: string) => Promise<string>Execute Python code
runScript()(scriptPath: string) => Promise<string>Run script file
installPackage()(pkg: string) => Promise<string>pip install
installPackages()(...pkgs: string[]) => Promise<string>Install multiple

Example

const codebox = new CodeBox({ memoryMib: 1024 });
try {
  await codebox.installPackage('requests');
  const result = await codebox.run(`
import requests
print(requests.get('https://api.github.com/zen').text)
  `);
  console.log(result);
} finally {
  await codebox.stop();
}

BrowserBox

Browser automation with Chrome DevTools Protocol.

import { BrowserBox, BrowserType } from 'boxlite';

Constructor Options

interface BrowserBoxOptions {
  browser?: BrowserType;  // "chromium" | "firefox" | "webkit"
  memoryMib?: number;     // Default: 2048
  cpus?: number;          // Default: 2
}

Browser CDP Ports

BrowserPortImage
chromium9222mcr.microsoft.com/playwright:v1.47.2-jammy
firefox9223browserless/firefox:latest
webkit9224browserless/webkit:latest

Methods

MethodSignatureDescription
start()(timeout?: number) => Promise<void>Start browser
endpoint()() => stringGet CDP endpoint URL

Example

import puppeteer from 'puppeteer-core';

const browser = new BrowserBox({ browser: 'chromium' });
try {
  await browser.start();
  const endpoint = browser.endpoint();  // "http://localhost:9222"

  const instance = await puppeteer.connect({ browserURL: endpoint });
  const page = await instance.newPage();
  await page.goto('https://example.com');
  console.log(await page.title());
} finally {
  await browser.stop();
}

ComputerBox

Desktop automation with full GUI environment.

import { ComputerBox } from 'boxlite';

Constructor Options

interface ComputerBoxOptions {
  cpus?: number;          // Default: 2
  memoryMib?: number;     // Default: 2048
  guiHttpPort?: number;   // Default: 3000
  guiHttpsPort?: number;  // Default: 3001
}

Mouse Methods

MethodSignatureDescription
mouseMove()(x: number, y: number) => Promise<void>Move cursor
leftClick()() => Promise<void>Left click
rightClick()() => Promise<void>Right click
middleClick()() => Promise<void>Middle click
doubleClick()() => Promise<void>Double click
tripleClick()() => Promise<void>Triple click
leftClickDrag()(startX, startY, endX, endY) => Promise<void>Drag
cursorPosition()() => Promise<[number, number]>Get cursor pos

Keyboard Methods

MethodSignatureDescription
type()(text: string) => Promise<void>Type text
key()(keySequence: string) => Promise<void>Press key(s)
Key Syntax Reference (xdotool format)
KeySyntax
EnterReturn
TabTab
EscapeEscape
BackspaceBackSpace
DeleteDelete
Spacespace
Arrow keysUp, Down, Left, Right
Function keysF1, F2, ... F12
Page keysPage_Up, Page_Down, Home, End
Modifiersctrl, alt, shift, super
Combinationsctrl+c, ctrl+shift+s, alt+Tab

Examples:

await desktop.key('Return');        // Press Enter
await desktop.key('ctrl+c');        // Copy
await desktop.key('ctrl+shift+s');  // Save As
await desktop.key('alt+Tab');       // Switch window
await desktop.key('ctrl+a Delete'); // Select all and delete

Display Methods

MethodSignatureDescription
waitUntilReady()(timeout?: number) => Promise<void>Wait for desktop
screenshot()() => Promise<Screenshot>Capture screen
scroll()(x, y, direction, amount?) => Promise<void>Scroll
getScreenSize()() => Promise<[number, number]>Get dimensions
Screenshot Return Type
interface Screenshot {
  data: string;    // Base64-encoded PNG
  width: number;   // 1024 (default)
  height: number;  // 768 (default)
  format: 'png';
}
Scroll Directions
DirectionDescription
"up"Scroll up
"down"Scroll down
"left"Scroll left
"right"Scroll right

Example

const desktop = new ComputerBox({ cpus: 4, memoryMib: 4096 });
try {
  await desktop.waitUntilReady(60);

  // Take screenshot
  const screenshot = await desktop.screenshot();
  console.log(`${screenshot.width}x${screenshot.height}`);

  // GUI interaction
  await desktop.mouseMove(100, 200);
  await desktop.leftClick();
  await desktop.type('Hello, World!');
  await desktop.key('Return');

  // Access via browser: http://localhost:3000
} finally {
  await desktop.stop();
}

InteractiveBox

Interactive terminal sessions with PTY support.

import { InteractiveBox } from 'boxlite';

Constructor Options

interface InteractiveBoxOptions extends SimpleBoxOptions {
  shell?: string;        // Default: "/bin/sh"
  tty?: boolean;         // undefined = auto-detect
}
TTY Mode
ValueBehavior
undefinedAuto-detect from stdin
trueForce TTY with I/O forwarding
falseNo I/O forwarding

Methods

MethodSignatureDescription
start()() => Promise<void>Start PTY session
wait()() => Promise<void>Wait for shell exit

Example

const box = new InteractiveBox({
  image: 'alpine:latest',
  shell: '/bin/sh',
  tty: true
});
try {
  await box.start();
  await box.wait();  // Blocks until shell exits
} finally {
  await box.stop();
}

Error Types

import { BoxliteError, ExecError, TimeoutError, ParseError } from 'boxlite';

Exception Hierarchy

BoxliteError (base)
├── ExecError       # Command failed
├── TimeoutError    # Operation timeout
└── ParseError      # Output parsing failed

BoxliteError

Base error class for all BoxLite errors.

try {
  await box.exec('invalid-command');
} catch (err) {
  if (err instanceof BoxliteError) {
    console.error('BoxLite error:', err.message);
  }
}

ExecError

Command execution failed (non-zero exit code).

PropertyTypeDescription
commandstringFailed command
exitCodenumberNon-zero exit code
stderrstringStandard error output
try {
  await box.exec('false');
} catch (err) {
  if (err instanceof ExecError) {
    console.error(`Command: ${err.command}`);
    console.error(`Exit code: ${err.exitCode}`);
    console.error(`Stderr: ${err.stderr}`);
  }
}

TimeoutError

Operation exceeded time limit.

try {
  await desktop.waitUntilReady(5);
} catch (err) {
  if (err instanceof TimeoutError) {
    console.error('Desktop did not become ready');
  }
}

ParseError

Failed to parse command output.

try {
  const pos = await desktop.cursorPosition();
} catch (err) {
  if (err instanceof ParseError) {
    console.error('Failed to parse cursor position');
  }
}

Metrics

JsRuntimeMetrics

Runtime-wide metrics.

FieldTypeDescription
boxesCreatedTotalnumberTotal boxes created
boxesFailedTotalnumberBoxes that failed during creation
numRunningBoxesnumberCurrently running boxes
totalCommandsExecutednumberTotal commands executed
totalExecErrorsnumberTotal execution errors
const metrics = await runtime.metrics();
console.log(`Boxes created: ${metrics.boxesCreatedTotal}`);
console.log(`Running: ${metrics.numRunningBoxes}`);

JsBoxMetrics

Per-box resource metrics.

Counter Fields

FieldTypeDescription
commandsExecutedTotalnumberCommands executed on this box
execErrorsTotalnumberExecution errors on this box
bytesSentTotalnumberBytes sent via stdin
bytesReceivedTotalnumberBytes received via stdout/stderr

Resource Fields

FieldTypeDescription
cpuPercentnumber | undefinedCPU usage (0.0-100.0)
memoryBytesnumber | undefinedMemory usage in bytes
networkBytesSentnumber | undefinedNetwork bytes sent
networkBytesReceivednumber | undefinedNetwork bytes received
networkTcpConnectionsnumber | undefinedCurrent TCP connections
networkTcpErrorsnumber | undefinedTotal TCP errors

Timing Fields (milliseconds)

FieldTypeDescription
totalCreateDurationMsnumber | undefinedTotal create time
guestBootDurationMsnumber | undefinedGuest agent ready time
stageFilesystemSetupMsnumber | undefinedDirectory setup time
stageImagePrepareMsnumber | undefinedImage pull/prepare time
stageGuestRootfsMsnumber | undefinedRootfs bootstrap time
stageBoxConfigMsnumber | undefinedConfiguration build time
stageBoxSpawnMsnumber | undefinedSubprocess spawn time
stageContainerInitMsnumber | undefinedContainer init time
const metrics = await box.metrics();
console.log(`CPU: ${metrics.cpuPercent}%`);
console.log(`Memory: ${(metrics.memoryBytes || 0) / (1024 * 1024)} MB`);
console.log(`Boot time: ${metrics.guestBootDurationMs}ms`);

Type Definitions

ExecResult (wrapper)

Result from SimpleBox.exec().

interface ExecResult {
  exitCode: number;
  stdout: string;
  stderr: string;
}

Screenshot

Screenshot capture result.

interface Screenshot {
  data: string;     // Base64-encoded PNG
  width: number;
  height: number;
  format: 'png';
}

BrowserType

Supported browser types.

type BrowserType = 'chromium' | 'firefox' | 'webkit';

Constants

Default values used by BoxLite.

Resource Defaults

ConstantValueDescription
DEFAULT_CPUS1Default CPU cores
DEFAULT_MEMORY_MIB512Default memory in MiB

ComputerBox Defaults

ConstantValueDescription
COMPUTERBOX_CPUS2Default CPUs
COMPUTERBOX_MEMORY_MIB2048Default memory
COMPUTERBOX_DISPLAY_WIDTH1024Screen width
COMPUTERBOX_DISPLAY_HEIGHT768Screen height
COMPUTERBOX_GUI_HTTP_PORT3000HTTP GUI port
COMPUTERBOX_GUI_HTTPS_PORT3001HTTPS GUI port
DESKTOP_READY_TIMEOUT60Ready timeout (seconds)

BrowserBox Ports

ConstantValueDescription
BROWSERBOX_PORT_CHROMIUM9222Chromium CDP port
BROWSERBOX_PORT_FIREFOX9223Firefox CDP port
BROWSERBOX_PORT_WEBKIT9224WebKit CDP port

See Also