# TypeScript SDK

> The @dissolve-email/sdk client for Node, Deno, Bun, Workers and browsers: install, options, the scoped client.v1 methods, typed errors, retries and the OAuth helpers.

Source: https://docs.dissolve.email/sdk

`@dissolve-email/sdk` is the TypeScript client for the API. It has no runtime dependencies, ships ESM and CommonJS builds with types, and runs anywhere with `fetch` and Web Crypto: Node 20 or later, Deno, Bun, Cloudflare Workers and browsers. It replaces `@buun_group/destroy-network-sdk`.

## Install

```bash npm
npm install @dissolve-email/sdk
```

```bash pnpm
pnpm add @dissolve-email/sdk
```

## Make a client

```ts
import { Dissolve } from '@dissolve-email/sdk';

// Reads DISSOLVE_API_KEY (then the old DESTROY_NETWORK_API_KEY) from the environment
const client = new Dissolve();

const inbox = await client.v1.createInbox();
const code = await client.v1.waitForCode(inbox.id, { timeout: 30 });
if (code.found) console.log(code.value);
```

| Option | Default | What it does |
|---|---|---|
| `apiKey` | `DISSOLVE_API_KEY`, then `DESTROY_NETWORK_API_KEY` | An `sk_live_` API key or a `dna_at_` OAuth access token |
| `baseURL` (or `baseUrl`) | `DISSOLVE_BASE_URL`, then `https://api.dissolve.email` | Another host, such as a local API |
| `timeout` | `30000` | Milliseconds before a request gives up (wait calls extend it by themselves) |
| `retry` | 2 retries, 500 ms doubling to 8 s, with jitter | `maxRetries` (0 turns retries off), `initialDelayMs`, `maxDelayMs` and the rest of the retry settings |
| `fetch` | the global `fetch` | Your own `fetch`, for tests or older runtimes |

Only `https:` base addresses are accepted, except plain `http:` to `localhost`, `127.0.0.1`, `[::1]` or a `*.localhost` name, so a credential never crosses the network in the clear. Anything else throws `ConfigurationError` when the client is made.

```ts
new Dissolve({ baseURL: 'http://localhost:27110' }); // a local API
new Dissolve({ baseURL: 'https://destroy.network' }); // the old host, while it still answers
```

## The scoped API: client.v1

`client.v1` covers every [/v1 endpoint](/reference), takes an API key or an OAuth access token, and is the part of the SDK these docs use in their examples. Each method needs the scope its endpoint names.

| Area | Methods |
|---|---|
| Account | `connection()`, `me()`, `listDomains()` |
| Inboxes | `listInboxes()`, `createInbox(params)`, `getInbox(id)`, `updateInbox(id, { forwardTo })`, `deleteInbox(id)`, `extendInbox(id)` |
| Aliases | `listAliases(inboxId)`, `createAlias(inboxId, { alias })`, `deleteAlias(inboxId, aliasId)` |
| Messages | `listMessages(inboxId)`, `getMessage(inboxId, messageId)`, `listAttachments(inboxId, messageId)`, `downloadAttachment(inboxId, messageId, attachmentId)` |
| Waiting | `waitForMessage(inboxId, { timeout, since, from })`, `waitForCode(inboxId, { timeout, since, from })` |
| Labels on messages | `addLabel(messageId, labelId)`, `removeLabel(messageId, labelId)` |
| Identities | `listIdentities()`, `createIdentity(params)`, `getIdentity(id)`, `updateIdentity(id, params)`, `deleteIdentity(id)`, `listIdentityMessages(id)`, `getIdentityMessage(id, messageId)`, `waitForIdentityMessage(id, options)`, `waitForIdentityCode(id, options)` |
| Vault | `listVault()`, `createVaultEntry(params)`, `getVaultEntry(id)`, `updateVaultEntry(id, params)`, `deleteVaultEntry(id)` |
| Webhooks | `listWebhooks()`, `createWebhook(params)`, `getWebhook(id)`, `updateWebhook(id, params)`, `deleteWebhook(id)` |
| Labels | `listLabels()`, `createLabel(params)`, `updateLabel(id, params)`, `deleteLabel(id)` |
| Rules | `listRules()`, `createRule(params)`, `getRule(id)`, `updateRule(id, params)`, `deleteRule(id)` |
| Templates | `listTemplates()`, `createTemplate(params)`, `deleteTemplate(id)` |

`downloadAttachment` returns the raw `Response`: read it with `arrayBuffer()` or stream its body. The wait methods give the request the wait's `timeout` plus 15 seconds before giving up.

```ts
const identity = await client.v1.createIdentity({ label: 'signup', persona: true, country: 'AU' });
console.log(identity.email, identity.password);

const result = await client.v1.waitForIdentityCode(identity.id, { timeout: 60 });
await client.v1.deleteIdentity(identity.id);
```

## The other resources

The client also carries resources named after the app's own routes: `inboxes`, `agent`, `labels`, `inboxRules`, `inboxTemplates`, `webhooks`, `user`, `digest`, `teams`, `apiKeys`, `billing` and `auth`. They take an API key, never an OAuth token: the client refuses to send a `dna_at_` token anywhere but `/v1` and throws `ConfigurationError` instead.

A few of them answer only to a signed-in session in the app, so with an API key they get 401: `apiKeys.*`, `billing.*`, `teams.*`, `auth.logoutAll()`, `user.listInboxHistory()`, `user.forgetInboxHistory()` and `user.updatePersonaDefaults()`. Prefer `client.v1` for new code.

## Errors

Every failed request throws. An answer from the API throws an `APIError` subclass carrying `status`, `code` and the response headers; a request that never got an answer throws `ConnectionError` or `TimeoutError`.

| Class | When |
|---|---|
| `BadRequestError` | 400 |
| `AuthenticationError` | 401 |
| `PermissionError` | 403 |
| `NotFoundError` | 404 |
| `RateLimitError` | 429, with `retryAfter` in seconds |
| `InternalServerError` | 500 |
| `APIError` | Any other status |
| `ConnectionError` | The network failed |
| `TimeoutError` | The request took longer than `timeout` |
| `ConfigurationError` | A bad base address, or an OAuth token sent outside `/v1`, before any request |

```ts
import { Dissolve, RateLimitError, PermissionError } from '@dissolve-email/sdk';

try {
  await client.v1.createInbox();
} catch (error) {
  if (error instanceof RateLimitError) console.log(`try again in ${error.retryAfter} s`);
  else if (error instanceof PermissionError) console.log(error.code, error.message);
  else throw error;
}
```

[Errors](/errors) lists the codes the API sends.

## Retries

Failed requests are retried with exponential backoff and jitter: 429 always, and 408, 500, 502, 503 and 504 on `GET`, `HEAD`, `OPTIONS`, `PUT` and `DELETE` only, so a create is never sent twice by the SDK. Two retries by default; `retry: { maxRetries: 0 }` turns them off.

## OAuth helpers

`@dissolve-email/sdk/oauth` runs the OAuth 2.1 flow with PKCE on `fetch` and Web Crypto, for apps that act for other people. See [Authentication](/authentication#oauth-2-1-with-pkce) for the flow itself.

| Export | What it does |
|---|---|
| `createPkce()` | Makes a code verifier and its S256 challenge |
| `authorizeUrl(options)` | Builds the authorization address and a random `state` |
| `parseRedirect(url, state)` | Reads the code from the redirect, checking `state` and the issuer |
| `exchangeCode(options)` | Trades the code and verifier for tokens |
| `refreshToken(options)`, `withRefresh(tokens, options)` | Refreshes by hand, or wraps tokens so they refresh before they expire (`onRefresh` saves the new pair) |
| `revokeToken(options)` | Revokes a token and its connection |
| `readMetadata()` | Reads the authorization server metadata |
| `SCOPES`, `DissolveOAuthError` | The scope names, and the error the helpers throw |

```ts
import { authorizeUrl, createPkce, exchangeCode, parseRedirect, withRefresh } from '@dissolve-email/sdk/oauth';
import { Dissolve } from '@dissolve-email/sdk';

const pkce = await createPkce();
const { url, state } = authorizeUrl({ clientId, redirectUri, scopes: ['profile', 'inboxes:read'], codeChallenge: pkce.challenge });
// ... the browser goes to url and comes back to redirectUri ...
const code = parseRedirect(location.href, state);
const tokens = await exchangeCode({ clientId, code, redirectUri, codeVerifier: pkce.verifier });

const client = new Dissolve({ apiKey: tokens.accessToken });
console.log(await client.v1.connection());
```

The issuer and default base address are `https://api.dissolve.email`.

## Migrating from @buun_group/destroy-network-sdk

```bash
npm uninstall @buun_group/destroy-network-sdk
npm install @dissolve-email/sdk
```

1. Change the imports to `@dissolve-email/sdk` and `@dissolve-email/sdk/oauth`. `DestroyNetwork` and `DestroyOAuthError` remain as deprecated aliases, so the rest compiles.
2. Your `sk_live_` keys, `dna_at_` and `dna_rt_` tokens and registered OAuth clients keep working.
3. The default host is now `https://api.dissolve.email`. Pass `baseURL: 'https://destroy.network'` to keep using the old host while it answers.
4. Read the breaking changes in the SDK's changelog: plain http is refused, OAuth tokens only go to `/v1`, the template, API key and webhook paths were fixed, and the domains resource is gone, as that feature is switched off.

The source, changelog and examples are in the [dissolve-sdk repository](https://github.com/dissolve-email/dissolve-sdk). [Migrating from destroy.network](/migrating) covers the rest of the move.
