# TypeScript SDK: Node.js, Deno, Bun & Cloudflare Workers

Official TypeScript client (bunqueue-client) for Node.js 20+, Deno 2+, Bun, and Cloudflare Workers with canonical Queue, Worker, FlowProducer, and Simple Mode APIs.

Canonical: https://bunqueue.dev/guide/sdks/typescript/

---

Run the canonical bunqueue API from Node.js 20+, Deno 2+, Bun, and Cloudflare Workers with full type safety, connection pooling, auto-batching, flows, and Simple Mode.

**In 30 seconds**

- bunqueue-client builds from the exact same source as bunqueue/client: identical Queue, Worker, FlowProducer, QueueEvents, and Bunqueue APIs.
- TCP mode (embedded: false) is the default unless embedded: true or BUNQUEUE_EMBEDDED=1 is set. Embedded SQLite requires Bun; pass embedded: false explicitly if BUNQUEUE_EMBEDDED=1 may be set in your environment.
- Attach worker.on("error", ...) in every worker process so Node EventEmitter errors never crash your runtime.
- Use *Async queue methods (getJobCountsAsync, pauseAsync, drainAsync, retryDlqAsync) for authoritative TCP calls.

*[Interactive doc iso diagram: Use bunqueue/client on Bun or bunqueue-client on Node.js, Deno, and Workers - Identical TypeScript API: same Queue, Worker, FlowProducer, QueueEvents, and Simple Mode across every JS runtime - open the HTML page to view it.]*

## Install

**Node.js (20+)**

```bash
npm install bunqueue-client
```

**Bun**

```bash
bun add bunqueue-client
```

**Deno (2+)**

```bash
deno add npm:bunqueue-client
```

> **Note: Upgrading from 0.1.x?**
>
> `bunqueue-client` 0.2.0+ ships the canonical `bunqueue/client` API by default with nested `connection: { host, port, token, tls }`. See the [0.1.x migration guide](https://github.com/egeominotti/bunqueue/blob/main/sdk/typescript/README.md#migrating-from-01x).

## Produce jobs

Create one pooled `Queue` per queue name and enqueue single jobs or batches over TCP (concurrent `add()` calls auto-batch by default):

```typescript
import { Queue } from 'bunqueue-client';

const queue = new Queue('emails', {
  embedded: false,
  connection: {
    host: process.env.BUNQUEUE_HOST ?? 'localhost',
    port: 6789,
    token: process.env.BUNQUEUE_TOKEN,
    tls: true, // or { caFile: './ca.pem' }
    poolSize: 4, // parallel TCP sockets (default: 4)
    commandTimeout: 30_000,
    maxInFlight: 100,
  },
});

// Single job with priority, retries, and durable flag
await queue.add('welcome', { to: 'user@example.com' }, {
  jobId: 'welcome-user-42', priority: 10, attempts: 5, durable: true,
});

// Bulk enqueue (one round-trip; concurrent add() calls also auto-batch by default)
await queue.addBulk(orders.map((o) => ({ name: 'ingest', data: o, opts: { jobId: `order-${o.id}` } })));
```

## Process jobs

Start a concurrent `Worker` with automatic lease heartbeats, typed error routing (`UnrecoverableError`, `DelayedError`, `RateLimitError`), and graceful `SIGTERM` draining:

```typescript
import { UnrecoverableError, Worker } from 'bunqueue-client';

const worker = new Worker('emails', async (job) => {
  if (!job.data.to) throw new UnrecoverableError('missing recipient'); // skips retries -> DLQ
  await sendEmail(job.data.to);
  return { sent: true };
}, {
  embedded: false,
  connection: { host: 'localhost', port: 6789, token: process.env.BUNQUEUE_TOKEN },
  concurrency: 10, lockDuration: 30_000, heartbeatInterval: 10_000,
});

worker.on('completed', (job, result) => console.log('done:', job.id, result));
worker.on('failed', (job, err) => console.warn('failed:', job?.id, err.message));
worker.on('error', (err) => console.error('worker error:', err)); // always attach!

process.on('SIGTERM', async () => { await worker.close(); process.exit(0); }); // drains active jobs
```

Transport and command rejections throw standard `Error` instances; always attach `worker.on('error', ...)`.

## Query, control, and flows

Use `*Async` queue methods for authoritative TCP reads/mutations, `QueueEvents` for push-based completion waits, and `FlowProducer` for atomic job graphs:

```typescript
import { QueueEvents } from 'bunqueue-client';

// Authoritative TCP reads and mutations
const job = await queue.getJob(id); // null when missing
const state = await queue.getJobState(id);
const counts = await queue.getJobCountsAsync();
await queue.pauseAsync();
const dropped = await queue.drainAsync();
const retried = await queue.retryDlqAsync();

// Wait for completion using QueueEvents (filter broker stream with eventTypes)
const events = new QueueEvents('emails', {
  connection: { host: 'localhost', port: 6789, token: process.env.BUNQUEUE_TOKEN },
  eventTypes: ['completed', 'failed'],
});
await events.waitUntilReady();
const result = await job?.waitUntilFinished(events, 30_000);
events.close();

// Readiness / health probe on Queue, Worker, FlowProducer, or Bunqueue
const health = queue.getHealth(); // PoolHealth | null (null in embedded mode)
```

Passing `null` to `job.waitUntilFinished(null, 30_000)` falls back to polling with extra round-trips and latency compared to `QueueEvents`.

Atomic trees, chains, and fan-in via `FlowProducer`:

```typescript
import { FlowProducer } from 'bunqueue-client';

const flow = new FlowProducer({ embedded: false });

await flow.addChain([
  { name: 'extract', queueName: 'etl', data: {} },
  { name: 'transform', queueName: 'etl', data: {} },
  { name: 'load', queueName: 'etl', data: {} },
]);

await flow.add({
  name: 'assemble',
  queueName: 'orders',
  data: {},
  children: [
    { name: 'reserve-stock', queueName: 'orders', data: {} },
    { name: 'charge-card', queueName: 'orders', data: {} },
  ],
});

await flow.addBulkThen(parts, { name: 'merge', queueName: 'orders', data: {} });
```

## Simple Mode (`Bunqueue`)

Bundle queue, worker, named routes, middleware, retry policies, and circuit breakers in one object:

```typescript
import { Bunqueue } from 'bunqueue-client';

const app = new Bunqueue('notifications', {
  embedded: false,
  connection: { host: 'localhost', port: 6789, token: process.env.BUNQUEUE_TOKEN },
  routes: {
    'send-email': async (job) => ({ sent: true }),
    'send-sms': async (job) => ({ sent: true }),
  },
  concurrency: 10,
  retry: { maxAttempts: 5, strategy: 'jitter' },
  circuitBreaker: { threshold: 5, resetTimeout: 30_000 },
});

app.on('error', (err) => console.error('app error:', err));

app.use(async (job, next) => {
  const start = Date.now();
  const out = await next();
  console.log(job.name, Date.now() - start, 'ms');
  return out;
});

await app.add('send-email', { to: 'alice@example.com' });
await app.cron('daily-digest', '0 9 * * *', { to: 'all' });
```

## Broker administration (`BrokerAdmin`)

Run broker-wide TCP commands (stats, metrics, Prometheus text, storage status, memory compaction, queue/worker/cron/webhook management, queue limits, job inspection, and dashboard snapshots) via `BrokerAdmin`, which accepts canonical `{ connection }` options (or wraps an existing `Connection`/`ConnectionPool`) and reads `BQ_TOKEN` / `BUNQUEUE_TOKEN` automatically:

```typescript
import { BrokerAdmin } from 'bunqueue-client';

const admin = new BrokerAdmin({ connection: { host: 'localhost', port: 6789, token: process.env.BUNQUEUE_TOKEN } });
await admin.waitUntilReady();

const [stats, queues, limits, prometheus] = await Promise.all([
  admin.getStats(), admin.listQueues(), admin.getQueueLimits('emails'), admin.getPrometheusMetrics(),
]);
admin.close();
```

## Cloudflare Workers

Enable `nodejs_compat` in `wrangler.toml`, enqueue inside `fetch` handlers (calling `disconnect()` in `finally`), and consume in batches from Cron Triggers:

```toml
# wrangler.toml
compatibility_flags = ["nodejs_compat"]
compatibility_date = "2025-01-01"
```

```typescript
import { Queue } from 'bunqueue-client';

export default {
  async fetch(req: Request, env: Env): Promise<Response> {
    const queue = new Queue('signups', {
      embedded: false,
      connection: { host: env.BQ_HOST, port: 6789, token: env.BQ_TOKEN, tls: true, poolSize: 1 },
    });
    try {
      const job = await queue.add('welcome', await req.json());
      return Response.json({ queued: job.id });
    } finally {
      await queue.disconnect();
    }
  },
};
```

> **Caution: Cloudflare's 6-connection limit**
>
> Workers cap each invocation at 6 outbound connections while `Queue` defaults to `poolSize: 4`. Always set `poolSize: 1` (at most `2`) and call `await queue.disconnect()` in `finally` against a publicly reachable broker with `AUTH_TOKENS` and trusted TLS.

## Runtime caveats

| Area | Rule / detail |
|---|---|
| **Default mode** | TCP (`embedded: false`) unless `embedded: true` or `BUNQUEUE_EMBEDDED=1` is set. Node.js, Deno, and Cloudflare Workers lack `bun:sqlite`, so pass `embedded: false` explicitly if that env var may be inherited. |
| **Module & types** | Pure ESM (`"type": "module"`); CommonJS Node apps use `await import('bunqueue-client')` or bundle with esbuild/tsup/Vite. Compile against `@types/node` 20+. |
| **Deno** | Use `deno add --minimum-dependency-age=0 npm:bunqueue-client` if Deno's age check blocks a new release. Deno skips `msgpackr-extract` scripts and falls back to pure-JS `msgpackr` with identical wire output. |
| **TLS & Unix sockets** | `connection.tls` accepts `true` or file paths (`caFile`, `certFile`, `keyFile`) / inline PEM strings or `Buffer`s (`ca`, `cert`, `key`, `passphrase`), plus `servername` (SNI) and `rejectUnauthorized` (default `true`). Use `connection: { socketPath }` for local Unix sockets. |
| **Auth fallback & legacy** | Omitting `connection.token` reads `BQ_TOKEN` or `BUNQUEUE_TOKEN` across `Queue`, `Worker`, `FlowProducer`, `QueueEvents`, `SandboxedWorker`, `Bunqueue`, and `BrokerAdmin`. Import `bunqueue-client/legacy` during incremental `0.1.x` migrations. |

## See also

- [SDKs Overview](https://bunqueue.dev/guide/sdks/): cross-language architecture and protocol v3 matrix
- [Queue API](https://bunqueue.dev/guide/queue/) & [Worker API](https://bunqueue.dev/guide/worker/): full canonical TypeScript guides
- [Source & Changelog](https://github.com/egeominotti/bunqueue/tree/main/sdk/typescript)
