bkr

reference

Built-in modules

Import built-in modules by bare name, such as import { serve } from "http". Any other bare specifier throws a module load error.

http — HTTP, HTTPS, and WebSocket server

Requires --allow-net for the bound hostname and port, plus --allow-read for TLS certificate and key files.

serve(options, fetch?) -> Server

Start an HTTP or HTTPS server on uWebSockets.

  • Options: hostname (default "0.0.0.0"), port (default 8080; 0 picks an ephemeral port), tls: { cert, key } (PEM paths), routes, static, fetch(req, server), error(err), and onListen(server).
  • routes: Maps paths (exact, :param, or terminal /*) to a handler function, a buffered Response snapshot, a per-method map (GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE, CONNECT), or false to fall through to fetch.
  • static: Maps exact paths to unused buffered Response objects serialized into wire bytes at startup and answered directly from native code (equivalent to passing a Response in routes).
  • Directory routes: A /* route may map to { dir, transpile, sourceMaps }. Requests resolve by extension, with .js falling back to .tsx, .ts, .jsx, .mts, and .cts. With transpile: true, transpiled output is cached in memory until mtime or size changes. sourceMaps accepts "linked" (default, served at <path>.map), "inline", or false. Registers GET and HEAD, sends weak ETags (honoring If-None-Match), and redirects the bare prefix to the trailing-slash path.
  • Server: Exposes hostname, port, url (URL), workers, ready (Promise<Server>), finished (Promise<void>), stop(force = false), and [Symbol.asyncDispose]().

upgradeWebSocket(request, options?) -> { socket: WebSocket, response: Response }

Upgrade a request inside a route or fetch handler. Pass options.protocol to pick an offered subprotocol. Return response (a 101 response) from the handler to complete the handshake. Server sockets enforce a 16 MiB message limit, a 120 s idle timeout, and automatic pings.

net — TCP, TLS, and DNS

Requires --allow-net.

connect({ hostname, port, tls = false }) -> Promise<Conn>

Open a TCP or TLS connection. When tls is true, verifies the peer certificate and hostname against the system root store using OpenSSL 3.

listen({ hostname = "0.0.0.0", port = 0 }) -> Listener

Bind a TCP listener. Returns { hostname, port, accept(), close(), [Symbol.asyncIterator]() }, where accept() resolves to a Conn or null after close.

resolve(hostname) -> Promise<string[]>

Resolve IPv4 and IPv6 addresses for hostname on the native thread pool.

Conn / Handle: { localPort, remoteAddress, remotePort, read(), write(data), closeWrite(), close(), readable, writable }

Resource handle shared by sockets, open files, and stdio pipes. read() resolves to a Uint8Array or null on EOF. write(data) accepts a Uint8Array, view, or string and resolves to the byte count written. readable and writable expose Web stream wrappers.

file — Filesystem operations

Requires --allow-read or --allow-write for the canonicalized target path. Paths accept a string or a file: URL.

body(path) -> FileBody

Create a lazy file body for new Response(body(path)). Passed untouched to the HTTP server, it streams in 64 KiB chunks with socket backpressure and checks read permission when sending starts.

read(path) -> Promise<Uint8Array> · readText(path) -> Promise<string>

Read a file on the thread pool as raw bytes or UTF-8 text (stripping a leading UTF-8 BOM if present).

write(path, data, { append = false }?) -> Promise<null> · writeText(path, data, options?)

Write a string or byte buffer to path, creating or truncating by default, or appending with append: true.

open(path, mode = "r") -> Promise<Handle>

Open a file handle. mode is one of "r", "w", "a", "x", or "rw".

stat(path) -> Promise<{ kind, size, mtime, mode }> · exists(path) -> Promise<boolean> · list(path) -> Promise<Array<{ kind, name }>>

stat() runs lstat (kind is "file", "dir", "symlink", or "other"; mtime is a Date). exists() tests path existence. list() returns directory entries.

mkdir(path, { recursive = false }?) -> Promise<null> · remove(path, { recursive = false }?) -> Promise<null>

Create a directory or remove a file or directory.

rename(from, to) -> Promise<null> · copy(from, to) -> Promise<null>

Rename a path (needs write permission on both paths) or copy file contents from from to to.

process — Arguments, environment, stdio, and child processes

args: string[] · main: string · execPath: string · pid: number · exit(code = 0)

Arguments after the entry script, absolute path of the entry module, path to the running bkr binary, process ID, and immediate process exit.

env: { get(name), set(name, value), delete(name), toObject() }

Read or modify environment variables. Requires --allow-env for the variable name; toObject() requires an unrestricted --allow-env grant.

stdin: Handle · stdout: Handle · stderr: Handle

Resource handles for file descriptors 0, 1, and 2.

spawn(command, options?) -> Child · run(command, options?) -> Promise<{ code, stdout, stderr }>

Spawn a subprocess. Requires --allow-run for command.

  • Options: args (string[]), env (Record<string, string>), cwd, and stdin / stdout / stderr ("inherit", "piped", or "null").
  • Child: Exposes pid, stdin, stdout, stderr, status (Promise<number>, negative signal number if killed), and kill(signal = 15).
  • run(): Pipes stdout and stderr and resolves to their Uint8Array buffers and exit code.

path — POSIX path utilities

Pure path helpers. No permissions required except when resolve() reads the current working directory.

sep = "/" · delimiter = ":" · normalize(p) · join(...parts) · resolve(...parts) · relative(from, to) · isAbsolute(p)

Normalize, join, resolve against the working directory, compute relative paths, and test for a leading /.

dirname(p) · basename(p, ext?) · extname(p) · parse(p) · format(obj)

Extract or reassemble { root, dir, base, ext, name } components.

toFileUrl(p) -> URL · fromFileUrl(url) -> string

Convert between filesystem paths and file:// URLs.

permissions — Runtime permission inspection

query(desc) -> Promise<{ state }> · request(desc) -> Promise<{ state }> · revoke(desc) -> Promise<{ state }>

Inspect, prompt for, or revoke permissions. desc is a category name string or an object with name ("net", "read", "write", "env", "run", "ffi", "sys", "import") and an optional scope field (host, path, variable, command, or kind). Returns state as "granted", "prompt", or "denied".

sqlite — Synchronous SQLite 3.31+ binding (optional)

Available when the system SQLite shared library (3.31+) can be loaded at startup. File databases require --allow-read (and --allow-write unless read-only) for the database file and its -journal, -wal, and -shm sidecars.

new Database(path = ":memory:", { readonly = false }?)

Open an in-memory or file-backed database.

  • Methods and getters: exec(sql), prepare(sql) -> Statement, query(sql) -> Statement, transaction(fn) -> fn (savepoint-backed synchronous wrapper), inTransaction: boolean, close(), and [Symbol.dispose]().
  • Confinement: An authorizer blocks ATTACH, VACUUM INTO, extension loading, and disk temp-store changes so queries stay inside the granted path.

Statement: { all(...params), get(...params), run(...params), finalize(), [Symbol.dispose]() }

Reusable prepared statement.

  • Binding: Pass parameters positionally, as a single array, or as a single named-parameter object (matching bare or :, $, @-prefixed SQL names).
  • Results: all() returns null-prototype row objects; get() returns the first row or undefined; run() returns { changes, lastInsertRowid }. 64-bit integers outside the safe Number range come back as BigInt.

version: string

Loaded SQLite library version string, such as "3.46.1".

crypto — Native hashing, Argon2id, and Web Crypto

randomBytes(size) -> Uint8Array · sha256(stringOrBytes) -> Uint8Array · hex(bytes) -> string

Generate 0–65,536 cryptographically random bytes, compute a 32-byte SHA-256 digest, or format a Uint8Array as lowercase hex.

timingSafeEqual(a, b) -> boolean

Constant-time byte comparison via OpenSSL CRYPTO_memcmp for equal-length buffers. Returns false immediately if lengths differ.

hashPassword(password) -> Promise<string> · verifyPassword(password, encoded) -> Promise<boolean>

Asynchronous Argon2id password hashing and verification on the native thread pool.

  • Parameters: m=19456 KiB, t=2, p=1, 32-byte random salt, 32-byte output.
  • Limits: Up to 4,096 UTF-8 password bytes. At most 2 concurrent jobs; further calls reject with code: "BUSY".

subtle: SubtleCrypto

Re-export of globalThis.crypto.subtle.

typescript — Type erasure, JSX lowering, and source maps

transpile(source, options?) -> string

Strip TypeScript types and lower JSX to browser JavaScript using boomkat's parser.

  • Options: filename (default "module.ts"; .tsx/.jsx enables JSX), module (default true), jsx ("automatic" or "classic"), jsxImportSource (default "preact"), jsxFactory (default "h"), jsxFragmentFactory (default "Fragment"), and sourceMap ("inline" or false).

transpileWithMap(source, options?) -> { code: string, map: string }

Return transpiled JavaScript code (without a trailing sourceMappingURL comment) alongside a version 3 source map as JSON text.

test — Test registration, hooks, and assertions

test(name, fn) · it(name, fn) · describe(name, fn)

Register tests and suites for bkr test. Both test/it and describe support .skip(name, fn) and .only(name, fn). test.todo(name) records a placeholder.

beforeAll(fn) · afterAll(fn) · beforeEach(fn) · afterEach(fn)

Lifecycle hooks scoped to the current file or enclosing describe block. Sync or async.

Assertions and AssertionError

  • assert(cond, msg?), fail(msg?)
  • assertEquals(a, b, msg?), assertNotEquals(a, b, msg?) — deep structural equality across plain objects, arrays, Map, Set, Date, RegExp, ArrayBuffer, and typed views, including circular references.
  • assertStrictEquals(a, b, msg?), assertMatch(text, regex, msg?)
  • assertThrows(fn, ErrorClass?, includes?), assertRejects(fnOrPromise, ErrorClass?, includes?)