npm package: @revbridge/connect-email
Description: Enterprise-grade Node.js SDK for the RevBridge Connect Email API.
Author: RevBridge
Latest version: 0.1.0

@revbridge/connect-email
========================

Enterprise-grade TypeScript SDK for the RevBridge Connect Email API. This client wraps the messaging, deliverability, and analytics surfaces (emails, webhooks, suppressions, and stats) with first-class typing, resilient HTTP primitives, and built-in webhook signature utilities—delivering the polished developer experience teams expect from modern email platforms.

Features
--------

- ⚡ **Modern stack** – ESM & CJS bundles with full TypeScript definitions (Node.js ≥ 18).
- 🔐 **Secure by default** – Automatic Bearer auth, rate-limit aware retries, idempotency helpers, and webhook HMAC verification.
- 📬 **Messaging ready** – High-level email send/status/history helpers with polling utilities.
- 📊 **Deliverability tooling** – Webhook CRUD/test, suppression management, activity timelines, and stats dashboards.
- 🧪 **Test harness** – Jest + MSW fixtures demonstrate how to stub the RevBridge API for integration testing.

Installation
------------

```bash
npm install @revbridge/connect-email
# or
yarn add @revbridge/connect-email
```

Quick start
-----------

```ts
import { RevBridgeConnectClient } from '@revbridge/connect-email';

const client = new RevBridgeConnectClient({
  apiKey: process.env.REVBRIDGE_API_KEY!,
  baseUrl: process.env.REVBRIDGE_BASE_URL! // customer-specific API host (required)
});

const sendResponse = await client.emails.send({
  domainName: 'revbridge.io',
  subject: 'Welcome to RevBridge',
  from: { email: 'hello@revbridge.io', name: 'RevBridge Team' },
  personalizations: [
    {
      to: [{ email: 'customer@example.com', name: 'Customer' }],
      dynamicData: { first_name: 'Taylor' }
    }
  ],
  content: {
    html: '<p>Hey {{first_name}} — your domain is provisioned.</p>',
    text: 'Hey {{first_name}} — your domain is provisioned.'
  }
});

console.log(sendResponse.data.messageId); // msg_abc123
```

Configuration
-------------

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `apiKey` | `string` | — | **Required.** JWT API key generated in RevBridge Connect. |
| `baseUrl` | `string` | — | **Required.** Customer-specific RevBridge API host (e.g. `https://<slug>.revbridge.ai`). |
| `timeoutMs` | `number` | `30000` | Global request timeout. Override per-call via request options. |
| `retry` | `Partial<RetryOptions>` | `{ maxRetries: 3, minDelay: 250, maxDelay: 4000 }` | Tweak retry behaviour (status codes, jitter, etc.). |
| `fetch` | `FetchLike` | `undici.fetch` | Provide a custom `fetch` implementation (useful for tests or custom agents). |
| `logger` | `Partial<Logger>` | noop | Optional logger for tracing HTTP attempts. |

Modules
-------

### Emails

- `send(payload, options)` – enqueue transactional or marketing messages with idempotency support.
- `getStatus(messageId)` – inspect delivery status.
- `listHistory(filters)` – search historical deliveries with pagination.
- `pollStatus(messageId, { intervalMs, timeoutMs, onUpdate })` – await a terminal state (sent/delivered/bounced/failed).

```ts
const { data: status } = await client.emails.pollStatus('msg_abc123', {
  intervalMs: 2000,
  timeoutMs: 60000,
  onUpdate: (snapshot) => console.log('Status update', snapshot.status)
});
```

### Webhooks

- Full CRUD (`list`, `get`, `create`, `update`, `delete`).
- Delivery diagnostics (`listEvents`) and performance snapshots (`stats`).
- HMAC signature helpers (`createSignature`, `verifySignature`) to validate RevBridge callbacks.

```ts
const signature = request.headers['x-revbridge-signature'];
const valid = client.webhooks.verifySignature({
  payload: request.body,
  secret: process.env.REVBRIDGE_WEBHOOK_SECRET!,
  signatureHeader: signature
});
```

### Suppressions

- `list` – audit suppressed addresses by reason/domain.
- `create` & `createMany` – add targeted or bulk suppressions.
- `delete` – restore recipients (optionally hard delete).
- `metrics` – quick suppression breakdown by reason for compliance reporting.

### Stats

- `overview` – aggregate engagement KPIs (sends, deliveries, opens, clicks, complaints).
- `dashboard` – executive-friendly metrics plus top campaign/domain charts.
- `timeSeries` – time-bucketed slices for trend analysis.
- `activity` – event stream powering audit trails or dashboards.

Webhook signature verification
------------------------------

RevBridge webhooks include a signature header formatted as `t=<timestamp>,v1=<hex>`. Use the SDK helpers to compare the HMAC digest within an allowed tolerance (default 30 seconds):

```ts
const isValid = client.webhooks.verifySignature({
  payload: rawBodyBuffer,
  secret: process.env.REVBRIDGE_WEBHOOK_SECRET!,
  signatureHeader: req.headers['x-revbridge-signature'] as string,
  toleranceMs: 5 * 60 * 1000 // optional override
});

if (!isValid) {
  res.status(400).send('Invalid signature');
  return;
}
```

Testing
-------

The repository ships with Jest + MSW examples (`tests/**`) to help you stub the RevBridge API during unit or integration tests. To run locally:

```bash
npm test
```

Or to lint/build/type-check:

```bash
npm run lint
npm run typecheck
npm run build
```

Publishing
----------

Before publishing to npm:

1. Ensure the package version in `package.json` is bumped appropriately.
2. Run the full QA suite (`npm run lint && npm run typecheck && npm test && npm run build`).
3. Publish with `npm publish --access public`.

Documentation
-------------

See [`docs/usage.md`](docs/usage.md) for a deeper dive into advanced flows, including retry tuning, custom transports, and webhook simulations.