or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

database.mdffi.mdfile-system.mdglobals.mdhtml-rewriter.mdhttp-server.mdindex.mdprocess-management.mdredis.mds3.mdshell.mdtesting.mdutilities.md
tile.json

tessl/npm-bun-types

TypeScript type definitions for Bun's JavaScript runtime APIs, enabling type-safe access to Bun's enhanced performance features and runtime-specific functionality.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/bun-types@1.2.x

To install, run

npx @tessl/cli install tessl/npm-bun-types@1.2.0

index.mddocs/

Bun Types

Bun Types provides comprehensive TypeScript definitions for Bun's runtime APIs, including core runtime operations, web standards implementations, testing framework, and extensive Node.js compatibility. It enables full type safety and autocomplete support when developing with the Bun JavaScript runtime.

Package Information

  • Package Name: bun-types
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install bun-types (automatically included with Bun)

Core Imports

import { Database } from "bun:sqlite";
import { test, expect, describe } from "bun:test";
import { dlopen, FFIType } from "bun:ffi";

Global Bun namespace:

// Available globally, no import needed
Bun.serve({ fetch: (req) => new Response("Hello World!") });
Bun.file("./package.json").json();

Basic Usage

import { Database } from "bun:sqlite";

// File operations with BunFile
const file = Bun.file("data.json");
const data = await file.json();
await Bun.write("output.txt", "Hello from Bun!");

// HTTP server with WebSocket support
Bun.serve({
  port: 3000,
  fetch(req, server) {
    if (server.upgrade(req)) return; // WebSocket upgrade
    return new Response("Hello World!");
  },
  websocket: {
    message(ws, message) {
      ws.send(`Echo: ${message}`);
    }
  }
});

// Spawn processes
const proc = Bun.spawn(["echo", "Hello"], {
  stdout: "pipe"
});
console.log(await new Response(proc.stdout).text());

Architecture

Bun Types is organized around several key API domains:

  • Global APIs: Web standards, streams, timers, and enhanced built-ins available globally
  • Core Runtime: File system, process management, networking, and utilities via Bun namespace
  • Module System: Specialized modules imported via bun:* specifiers for database, testing, FFI
  • Compatibility Layer: Node.js and browser API compatibility with Bun-specific enhancements
  • Type System: Complete TypeScript definitions with generic type preservation and strict typing

Capabilities

File System Operations

High-performance file operations with BunFile interface, atomic writes, and memory mapping capabilities.

function Bun.file(path: string | URL): BunFile;
function Bun.file(data: ArrayBufferLike | Uint8Array): BunFile;
function Bun.file(fd: number): BunFile;

function Bun.write(
  destination: string | number | FileDescriptor | BunFile,
  input: string | ArrayBufferLike | BunFile | Response | Blob,
  options?: { createPath?: boolean }
): Promise<number>;

interface BunFile extends File {
  exists(): Promise<boolean>;
  json<T = any>(): Promise<T>;
  text(): Promise<string>;
  arrayBuffer(): Promise<ArrayBuffer>;
  bytes(): Promise<Uint8Array>;
  stream(): ReadableStream<Uint8Array>;
}

File System

Process Management

Spawn child processes with comprehensive I/O control, shell scripting with template literals, and cross-platform compatibility.

function Bun.spawn(
  command: string[],
  options?: Bun.SpawnOptions
): Subprocess;

function Bun.spawnSync(
  command: string[],
  options?: Bun.SpawnOptions
): Bun.SyncSubprocess;

function Bun.$(template: TemplateStringsArray, ...expressions: any[]): Promise<ShellOutput>;

Process Management

HTTP Server

High-performance HTTP/WebSocket server with hot reloading, static file serving, and TLS support.

function Bun.serve(options: Bun.ServeOptions): Server;

interface Bun.ServeOptions {
  port?: number;
  hostname?: string;
  fetch: (req: Request, server: Server) => Response | Promise<Response>;
  websocket?: WebSocketHandler<any>;
  tls?: TLSOptions;
  static?: StaticOptions;
}

HTTP Server

Testing Framework

Jest-compatible testing framework with built-in mocking, fake timers, and comprehensive expectation matchers.

function describe(name: string, fn: () => void): void;
function test(name: string, fn: () => void | Promise<void>): void;
function it(name: string, fn: () => void | Promise<void>): void;

function expect<T>(actual: T): Matchers<T>;

interface Matchers<T> {
  toBe(expected: T): void;
  toEqual(expected: T): void;
  toThrow(error?: string | RegExp | Error): void;
}

Testing

Database Operations

Fast SQLite database integration with prepared statements, transactions, and type-safe operations.

class Database {
  constructor(filename?: string, options?: DatabaseOptions);
  query<T = any>(sql: string): Statement<T>;
  exec(sql: string): void;
  close(): void;
  transaction<T>(fn: () => T): () => T;
}

interface Statement<T = any> {
  all(...params: any[]): T[];
  get(...params: any[]): T | undefined;
  run(...params: any[]): { changes: number; lastInsertRowid: number };
}

Database

Foreign Function Interface

Native library integration with C function binding, pointer manipulation, and type-safe FFI declarations.

function dlopen(
  library: string,
  symbols: Record<string, FFIFunction>
): Library;

interface FFIFunction {
  args?: FFIType[];
  returns?: FFIType;
}

enum FFIType {
  char = "char",
  int8_t = "int8_t",
  uint8_t = "uint8_t",
  int32_t = "int32_t",
  uint32_t = "uint32_t",
  ptr = "ptr",
  void = "void"
}

Foreign Function Interface

Utilities

Comprehensive utilities including hashing, password operations, compression, and string processing.

function Bun.hash(input: string | ArrayBufferLike, hashInto?: Uint8Array): number;

namespace Bun.password {
  function hash(password: string, options?: HashOptions): Promise<string>;
  function verify(password: string, hash: string): Promise<boolean>;
}

function Bun.gzipSync(data: ArrayBufferLike): Uint8Array;
function Bun.gunzipSync(data: ArrayBufferLike): Uint8Array;

Utilities

Global APIs

Enhanced web standards, streams, timers, events, and extended JavaScript built-ins with Bun-specific features.

function setTimeout(handler: TimerHandler, timeout?: number, ...args: any[]): Bun.Timer;
function setInterval(handler: TimerHandler, interval?: number, ...args: any[]): Bun.Timer;

interface ReadableStream<R = any> {
  [Symbol.asyncIterator](): AsyncIterableIterator<R>;
}

declare const crypto: Crypto & {
  timingSafeEqual(a: ArrayBufferView, b: ArrayBufferView): boolean;
};

Global APIs

Redis Client

High-performance Redis client with connection management, command pipelining, and comprehensive Redis data type operations.

class RedisClient {
  constructor(url?: string, options?: RedisOptions);
  connect(): Promise<void>;
  get(key: KeyLike): Promise<string | null>;
  set(key: KeyLike, value: KeyLike): Promise<"OK">;
  del(...keys: KeyLike[]): Promise<number>;
  incr(key: KeyLike): Promise<number>;
  exists(key: KeyLike): Promise<boolean>;
}

Redis Client

Amazon S3 Integration

Amazon S3 client with file operations, presigned URLs, streaming support, and seamless cloud storage integration.

class S3Client {
  constructor(options?: S3Options);
  file(path: string, options?: S3Options): S3File;
  write(path: string, data: BlobOrStringOrBuffer, options?: S3Options): Promise<number>;
  delete(path: string, options?: S3Options): Promise<void>;
  presign(path: string, options?: S3FilePresignOptions): string;
}

Amazon S3

HTML Rewriter

Fast HTML parsing and transformation API with CSS selector-based targeting and streaming DOM manipulation.

class HTMLRewriter {
  constructor();
  on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter;
  onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter;
  transform(input: Response | Blob | ArrayBuffer | string): Response | ArrayBuffer | string;
}

HTML Rewriter

Shell Scripting

Enhanced shell scripting with template literals, cross-platform compatibility, and comprehensive process control.

function $(strings: TemplateStringsArray, ...expressions: ShellExpression[]): $.ShellPromise;

namespace $ {
  function braces(pattern: string): string[];
  function escape(input: string): string; 
  function env(newEnv?: Record<string, string | undefined>): $;
  function cwd(newCwd?: string): $;
}

Shell Scripting