---
title: "TypeScript SDK: the client, errors, stream and helpers"
description: "What @doorman/inbox-sdk exports besides the resources of the API: the client and its options, the parameters of lists and sends, pagination, errors, the stream, webhook verification, OAuth and the transport."
url: https://doorman.fyi/docs/sdk/reference/client
markdown: https://doorman.fyi/docs/sdk/reference/client.md
area: "SDKs and tools"
section: "TypeScript SDK"
---

# TypeScript SDK: the client, errors, stream and helpers

What @doorman/inbox-sdk exports besides the resources of the API: the client and its options, the parameters of lists and sends, pagination, errors, the stream, webhook verification, OAuth and the transport.

Source: https://doorman.fyi/docs/sdk/reference/client

## The client

One `DoormanInbox` holds the credential and the API origin, and every call goes through it. `apiKey` takes an API key or an app's access token; the client refuses an empty one when it is constructed. `baseUrl` is always given: the client never assumes a deployment. `fetch` and `WebSocket` replace the platform's own, for a test or a runtime that has neither.

TypeScript:
```ts
import { DoormanInbox } from "@doorman/inbox-sdk";

const client = new DoormanInbox({
  apiKey: process.env.DOORMAN_API_KEY ?? "",
  baseUrl: "https://api.doorman.fyi",
});
```

The properties below are the resources of the API. Each one's methods are on the page of its tag, listed in [the index](https://doorman.fyi/docs/sdk/reference.md).

### DoormanInbox

The Doorman Inbox API, one method per operation, grouped as the contract's registry ids them: `inboxes.create` is `client.inboxes.create(...)`.

Class:
```ts
new DoormanInbox(options: DoormanInboxOptions)
```

**Properties**

| Property | Type | Description |
| --- | --- | --- |
| `inboxes` | `Inboxes` |  |
| `domains` | `Domains` |  |
| `passport` | `Passport` |  |
| `services` | `Services` |  |
| `threads` | `Threads` |  |
| `messages` | `Messages` |  |
| `attachments` | `Attachments` |  |
| `events` | `Events` |  |
| `webhooks` | `Webhooks` |  |
| `deliveries` | `Deliveries` |  |
| `apiKeys` | `ApiKeys` |  |
| `security` | `Security` |  |
| `senderRules` | `SenderRules` |  |
| `heldSends` | `HeldSends` |  |
| `drafts` | `Drafts` |  |
| `apps` | `Apps` |  |
| `installs` | `Installs` |  |
| `oauthRequests` | `OAuthRequests` |  |
| `signIn` | `SignIn` |  |
| `billing` | `Billing` |  |
| `baa` | `Baa` |  |
| `guardrails` | `Guardrails` |  |
| `push` | `Push` |  |
| `members` | `Members` |  |
| `invitations` | `Invitations` |  |
| `organization` | `OrganizationResource` |  |
| `oauth` | `InboxOAuth` |  |
| `transport` | `Transport` |  |
| `baseUrl` | `string` | The API's base URL as the client uses it: no trailing slash. |

### DoormanInboxOptions

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `apiKey` | `string` | yes | A `dm_` API key, a REST-resource app access token, or a console session token. |
| `baseUrl` | `string` | yes | The API's origin, for example `https://api.doorman.example`. Required: the client never assumes a deployment. |
| `accountId` | `string` | no | The account this client is meant for, `acc_...`. When given, every request names it in the `x-doorman-account` header, and the API refuses the request with 409 `account_mismatch` unless the credential acts for that account. It is for a caller that holds credentials for several accounts, so that a credential picked by mistake does nothing. The stream does not carry it. |
| `fetch` | `FetchLike` | no | The `fetch` to send requests with. Defaults to the global one. |
| `WebSocket` | `WebSocketConstructor` | no | The `WebSocket` the stream opens connections with. Defaults to the global one. |

## Parameters of lists and sends

The shapes the list methods and `send` take. A request body and an answer are the contract's own types, described under [Schemas](https://doorman.fyi/docs/reference/schemas.md) and exported from this package by the same names. A send answers the stored message, or a held send where the security policy keeps it for the owner: `isHeldSend(result)` tells the two apart. See [Sends that wait for the owner](https://doorman.fyi/docs/security.md#held-sends).

### PageParams

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `limit` | `number` | no | Page size, 1 to 100. Defaults to 50. |
| `offset` | `number` | no | Rows to skip. Defaults to 0. |

### CursorParams

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `limit` | `number` | no | Page size, 1 to 100. Defaults to 50. |
| `cursor` | `string` | no | Where to continue from: the previous page's `nextCursor`. |

### ListInboxesParams

Extends `PageParams`: every field of it is a field here.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `q` | `string` | no | Keep the inboxes whose address or display name contains this text, case-insensitively. |
| `externalId` | `string` | no | Keep the inbox with exactly this `externalId`: at most one. |

### ListThreadsParams

Extends `PageParams`: every field of it is a field here.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `isRead` | `boolean` | no | Only read or only unread threads. |
| `label` | `string` | no | Only threads carrying this exact, case-sensitive label. |
| `q` | `string` | no | Keep the threads whose subject or a participant address contains this text, case-insensitively. |

### ListMessagesParams

Extends `PageParams`: every field of it is a field here.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `direction` | `"inbound" \| "outbound"` | no | Only received or only sent messages. |

### EventFilters

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `inboxId` | `string` | no | Only this inbox. |
| `threadId` | `string` | no | Only this thread's events, across all stored history within the caller's scope. |
| `type` | `EventType` | no | Only this event type. |

### ListEventsParams

Extends `CursorParams, EventFilters`: every field of it is a field here.

### PollEventsParams

Extends `EventFilters`: every field of it is a field here.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `limit` | `number` | no | Page size, 1 to 100. Defaults to 50. |

### MetricsParams

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `from` | `string \| Date` | no | Start of the range. Defaults to 7 days before `to`. |
| `to` | `string \| Date` | no | End of the range. Defaults to now. |
| `interval` | `"hour" \| "day"` | no | Bucket size. Defaults to day. |
| `inboxId` | `string` | no | Only this inbox; omit for the whole account. |

### ListApiKeysParams

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `scope` | `"all"` | no | `all` adds the inbox-scoped keys; every item then carries `inboxAddress`. |

### ListServicesParams

Extends `PageParams`: every field of it is a field here.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `inboxId` | `string` | no | Only this inbox's services. |
| `status` | `ServiceStatus` | no | Only services with this status. Without it, every status but archived. |
| `attention` | `boolean` | no | Only services with (`true`) or without (`false`) an active warning. |
| `q` | `string` | no | Keep the services whose domain or name contains this text, case-insensitively. |

### ListVerificationsParams

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `domain` | `string` | no | Only codes and links from this service's domain, or a host under it. |
| `since` | `string \| Date` | no | Only those that arrived after this instant. |
| `waitSeconds` | `number` | no | When none has arrived yet, wait up to this many seconds (0 to 20) for one. |

### ListSendersParams

Extends `PageParams`: every field of it is a field here.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `standing` | `SenderStanding` | no | Only senders with this standing. |
| `q` | `string` | no | Keep senders whose address or display name contains this text, case-insensitively. |

### ListSenderRulesParams

Extends `PageParams`: every field of it is a field here.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `inboxId` | `string` | no | Only rules scoped to this inbox; omit for every rule of the account. |
| `standing` | `"trusted" \| "blocked"` | no | Only trusted or only blocked rules. |
| `q` | `string` | no | Keep rules whose address or domain contains this text. |

### ListSecurityAuditParams

Extends `PageParams`: every field of it is a field here.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `inboxId` | `string` | no | Only audit entries concerning this inbox. |

### ListHeldSendsParams

Extends `PageParams`: every field of it is a field here.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `status` | `HeldSendStatus` | no | Only held sends in this state. Defaults to the ones still waiting. |
| `kind` | `HeldSendKind` | no | Only the sends the security policy kept (`held`) or only drafts (`draft`). Both when left out. |

### ListGuardrailRulesParams

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `inboxId` | `string` | no | Only the guardrails that apply to this inbox alone. |

### SendOptions

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `idempotencyKey` | `string` | no | 1 to 255 printable ASCII characters that make a retry replay the original answer instead of sending twice. |

### SendMessageInput

A message to send: the contract's `SendMessage`, with attachment contents as bytes or base64.

Extends `Omit<SendMessage, "attachments">`: every field of it is a field here.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `attachments` | `readonly SendAttachmentInput[]` | no |  |

### SendAttachmentInput

A file to attach: the contract's attachment, with the content as bytes or as base64.

Extends `Omit<SendAttachment, "content">`: every field of it is a field here.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `content` | `string \| Uint8Array \| ArrayBuffer` | yes | The file's bytes, or their base64 encoding. |

### ReplyInput

Type:
```ts
type ReplyInput = Omit<SendMessageInput, "threadId">
```

A reply: everything a send takes except the thread, which is given separately.

### SendResult

Type:
```ts
type SendResult = (SentMessage | HeldSend) & { replayed: boolean }
```

What a send answers, plus whether the answer was replayed for an `Idempotency-Key` seen before: the stored outbound message, or, where the security policy asks for the owner's word (`sendApproval`), a held send. A held send was not sent. Tell the two apart with `isHeldSend()`.

### isHeldSend

Function:
```ts
isHeldSend<T extends SentMessage | HeldSend>(result: T): result is Extract<T, HeldSend>
```

Whether a send's answer is a held send: the message waits for the owner and was not sent. Do not send it again; read where it stands with `client.heldSends.get(result.id)`.

## Pagination

Every list that pages has an `iterate` method beside it, built on the two functions below. They ask for the next page only when the loop reaches it. An offset walk ends at the first page shorter than its limit, and a cursor walk when `nextCursor` is null. See [Pagination](https://doorman.fyi/docs/pagination.md).

### iterateOffsetPages

Function:
```ts
iterateOffsetPages<T>(fetchPage: (offset: number) => Promise<OffsetPage<T>>, start = 0): AsyncGenerator<T, void, undefined>
```

Every item of an offset-paginated list, page by page, from `start`. The walk ends at the first page shorter than its applied limit. Items that arrive while walking can shift the pages; a cursor list does not have that problem.

### iterateCursorPages

Function:
```ts
iterateCursorPages<T>(fetchPage: (cursor: string | undefined) => Promise<CursorPage<T>>, start?: string): AsyncGenerator<T, void, undefined>
```

Every item of a cursor-paginated list, page by page, from `start` (the first page when absent).

### OffsetPage

A page of an offset-paginated list, as inboxes, threads and messages are listed.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `data` | `T[]` | yes |  |
| `limit` | `number` | yes | The page size that was applied. |
| `offset` | `number` | yes | The offset that was applied. |

### CursorPage

A page of a cursor-paginated list, as events and deliveries are listed.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `data` | `T[]` | yes |  |
| `nextCursor` | `string \| null` | yes | The cursor of the next page; null on the last one. |

## Errors

An answer of `400` or more is thrown as an `ApiError`. The type guards narrow a caught value, and `isApiError` takes a code to match. See [Errors](https://doorman.fyi/docs/errors.md).

### ApiError

An answer with a status of 400 or more. `code` is one of the contract's error codes (`ERROR_CODES` in `@doorman/inbox-api`), or `unexpected_response` when the body was not an error the contract describes.

Class, extends Error:
```ts
new ApiError(input: ApiErrorInput)
```

**Properties**

| Property | Type | Description |
| --- | --- | --- |
| `name` |  |  |
| `operation` | `string` | The operation's id in the contract's registry, for example `inboxes.send`. |
| `status` | `number` |  |
| `code` | `string` |  |
| `details` | `ErrorDetails` |  |
| `retryAfterSeconds` | `number \| null` | Seconds from the `Retry-After` header, when the answer carried one. |
| `guard` | `"reply" \| "recipient" \| "content" \| null` | On a `403 risk_blocked` error: which guard refused (`reply`, `recipient` or `content`), or null otherwise. |
| `isSessionRequired` | `boolean` | True when the operation requires a console session because loosening protection is restricted (`403 session_required`). |

### ErrorDetails

The fields some error codes add beside `error` and `message`; see the contract's `Error` schema. Anything else the API adds in the future is kept under its own name.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `permission` | `OrgPermission` | no | `permission_denied`: the permission the signed-in member's role in the organization lacks. |
| `scope` | `"inboxes" \| "account" \| "inbox"` | no | `plan_limit_reached`: `inboxes` or `account`. `rate_limit_exceeded` on a send: `inbox`. |
| `plan` | `string` | no | `plan_limit_reached`: the account's plan. |
| `limit` | `number` | no | `plan_limit_reached` and `rate_limit_exceeded`: the limit that applied. |
| `used` | `number` | no | `plan_limit_reached`: how much of the allowance is used. |
| `resetsAt` | `string` | no | `plan_limit_reached` (sends) and `rate_limit_exceeded`: when the count starts again. |
| `providerCode` | `string` | no | `send_rejected` and `send_failed`: the sending provider's own code. |
| `guard` | `"reply" \| "recipient" \| "content"` | no | `risk_blocked`: which guard refused (`reply`, `recipient`, or `content` when an attachment or a link did not pass its check). |
| `reasons` | `string[]` | no | `risk_blocked` with the `content` guard: the reason codes for what was found. |

### isApiError

Function:
```ts
isApiError(value: unknown, code?: string): value is ApiError
```

Whether `value` is an `ApiError`, and with `code` given, one with that code.

### isRiskBlockedError

Function:
```ts
isRiskBlockedError(value: unknown): value is ApiError
```

Whether `value` is a `403 risk_blocked` error: a send or a download one of the guards refused.

### isSessionRequiredError

Function:
```ts
isSessionRequiredError(value: unknown): value is ApiError
```

Whether `value` is a `403 session_required` error indicating the owner must act in the console.

### UNEXPECTED_RESPONSE

Constant:
```ts
UNEXPECTED_RESPONSE = "unexpected_response"
```

The code the client uses when an answer is not an error the contract describes (a proxy's HTML page, say).

## The stream

`client.stream(options)` returns an `InboxStream`: the WebSocket of [The WebSocket stream](https://doorman.fyi/docs/stream.md) with the subscription, the keepalive and the reconnect handled. Events go to `onEvent` when given, otherwise to the async iterator.

### InboxStream

One connection to `/v1/ws`, kept alive with pings and reopened after an unexpected close, where it subscribes again with the last event it saw so nothing is missed. Events go to `onEvent` when given, otherwise to the async iterator (`for await (const event of stream)`); leaving that loop closes the stream.

Class:
```ts
new InboxStream(url: string, WebSocket: WebSocketConstructor, options: StreamOptions = {})
```

**Properties**

| Property | Type | Description |
| --- | --- | --- |
| `state` | `StreamState` |  |
| `lastEventId` | `string \| null` | The id of the last event received (or asked to replay from): what a reconnect resumes with. |

**Methods**

| Method | Description |
| --- | --- |
| `subscribe(subscription: StreamSubscription = {}): Promise<StreamSubscribed>` | Sends a subscribe frame and resolves with the subscription in force; rejects when the server refuses it. |
| `unsubscribe(inboxIds: readonly string[] = []): Promise<StreamUnsubscribed>` | Stops receiving: everything, or the given inboxes. |
| `close(): void` | Closes the socket, stops reconnecting and ends the iterator. |
| `[Symbol.asyncIterator](): AsyncIterator<StreamEvent, undefined, undefined>` | The events as an async iterator, for `for await`. Leaving the loop closes the stream. |

### StreamOptions

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `subscribe` | `StreamSubscription` | no | Subscribe as soon as the socket opens, and again after every reconnect. |
| `reconnect` | `boolean` | no | Reconnect after an unexpected close, resuming with `last_event_id`. Defaults to true. |
| `pingIntervalMs` | `number` | no | How often to send a keepalive ping. Defaults to 45 seconds, inside the window the API asks for. |
| `onEvent` | `(event: StreamEvent) => void` | no | Receives every event. Without it, events queue for the async iterator. |
| `onError` | `(error: Error) => void` | no | Receives a frame the server could not honour, an unreadable frame, or an exception thrown by `onEvent`. |
| `onOpen` | `() => void` | no | Called every time the socket opens, the first time and after each reconnect. |
| `onClose` | `(info: StreamCloseInfo) => void` | no | Called every time the socket closes, with whether a reconnect follows. |

### StreamSubscription

What to receive. Subscriptions accumulate on the server, as they do here.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `inboxIds` | `readonly string[]` | no | Only these inboxes (all of them the key's); absent or empty means every inbox the key can see. |
| `eventTypes` | `readonly EventType[]` | no | Only these event types; absent or empty means all. |
| `lastEventId` | `string` | no | Replay the events after this one before live events, up to the stream's replay limit. |

### StreamState

Type:
```ts
type StreamState = "connecting" | "open" | "closed"
```

### StreamCloseInfo

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `code` | `number` | yes |  |
| `reason` | `string` | yes |  |
| `reconnecting` | `boolean` | yes | Whether the stream will reconnect on its own. |

### StreamClosedError

The socket closed while a request was waiting for its answer, or the stream was closed by the caller.

Class, extends Error:
```ts
new StreamClosedError(code: number, reason: string)
```

**Properties**

| Property | Type | Description |
| --- | --- | --- |
| `name` |  |  |
| `code` | `number` |  |
| `reason` | `string` |  |

### StreamFrameError

A frame the server could not honour (`{ "type": "error" }`), or one the client could not read.

Extends `Error`.

**Properties**

| Property | Type | Description |
| --- | --- | --- |
| `name` |  |  |

### WebSocketLike

The part of a WebSocket the stream uses; the platform `WebSocket` has it.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `readyState` | `number` | yes |  |

**Methods**

| Method | Description |
| --- | --- |
| `send(data: string): void` |  |
| `close(code?: number, reason?: string): void` |  |
| `addEventListener(type: "open", listener: () => void): void` |  |
| `addEventListener(type: "message", listener: (event: { data: unknown }) => void): void` |  |
| `addEventListener(type: "close", listener: (event: { code: number; reason: string }) => void): void` |  |
| `addEventListener(type: "error", listener: () => void): void` |  |

### WebSocketConstructor

Type:
```ts
type WebSocketConstructor = new (url: string) => WebSocketLike
```

## Verifying webhooks

The check a receiver makes before it trusts a delivery, over the body exactly as it arrived. See [Verifying a delivery](https://doorman.fyi/docs/webhooks.md#verify).

### verifyWebhook

Function:
```ts
verifyWebhook(headers: WebhookHeaders, body: string | Uint8Array | ArrayBuffer, secret: string, options: VerifyWebhookOptions = {}): Promise<WebhookEvent>
```

Verifies a supported event delivery and returns its discriminated payload. The headers are the request's, the body its bytes or text exactly as received, the secret the one the API returned when the webhook or endpoint was set up (`whsec_...`). Deliveries are at least once: deduplicate on `event_id`.

### verifyWebhookSignature

Function:
```ts
verifyWebhookSignature(headers: WebhookHeaders, body: string | Uint8Array | ArrayBuffer, secret: string, options: VerifyWebhookOptions = {}): Promise<string>
```

Verifies a delivery's Standard Webhooks signature (`webhook-id`, `webhook-timestamp`, `webhook-signature`; HMAC-SHA256 over `id.timestamp.body` with the decoded secret) and returns the body as text. The body must be the bytes exactly as they arrived, not re-serialized JSON. The comparison runs inside WebCrypto, in constant time.

### VerifyWebhookOptions

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `toleranceSeconds` | `number` | no | How far from now `webhook-timestamp` may be, in seconds. Defaults to 300. |
| `now` | `number` | no | The current time in milliseconds, for tests. Defaults to `Date.now()`. |

### WebhookHeaders

Type:
```ts
type WebhookHeaders = | { get(name: string): string | null | undefined } | Readonly<Record<string, string | readonly string[] | undefined>>
```

Headers as a `Headers` object, or as the plain record Node's `IncomingMessage` and most frameworks expose.

### WebhookVerificationReason

Type:
```ts
type WebhookVerificationReason = | "missing_headers" | "invalid_timestamp" | "timestamp_out_of_tolerance" | "invalid_secret" | "invalid_signature" | "invalid_payload"
```

### WebhookVerificationError

Why a delivery was refused. Treat every reason the same way: answer 4xx and do not act on the payload.

Class, extends Error:
```ts
new WebhookVerificationError(reason: WebhookVerificationReason, message: string)
```

**Properties**

| Property | Type | Description |
| --- | --- | --- |
| `name` |  |  |
| `reason` | `WebhookVerificationReason` |  |

## OAuth

What an app uses to be approved by a person: discovery, the authorization address, registration and the token exchange. These requests carry no API credential and no cookie. `client.oauth` is an `InboxOAuth` for the client's origin. See [Apps and OAuth](https://doorman.fyi/docs/oauth.md).

### InboxOAuth

Public protocol requests never carry API bearer tokens, browser cookies or automatic retries, and never follow a redirect.

Class:
```ts
new InboxOAuth(options: InboxOAuthOptions)
```

**Properties**

| Property | Type | Description |
| --- | --- | --- |
| `baseUrl` | `string` |  |

**Methods**

| Method | Description |
| --- | --- |
| `metadata(): Promise<OAuthServerMetadata>` | The authorization server's metadata: where to authorize, exchange a code and register, and what it supports. |
| `resource(): Promise<OAuthResourceMetadata>` | The protected resource metadata of the REST API: its resource identifier, its authorization server and its scopes. |
| `mcpResource(): Promise<OAuthResourceMetadata>` | The protected resource metadata of the MCP address, which is a resource of its own: a token for one is refused by the other. |
| `authorizationUrl(input: OAuthAuthorization): string` | The URL to open in the person's browser. Leave `scope` out to ask for the default agent permissions. |
| `token(input: OAuthTokenRequest): Promise<OAuthTokens>` | Single-use code exchange or refresh rotation. Never automatically retry an ambiguous result. |
| `register(input: RegisterOAuthClient): Promise<RegisteredOAuthClient>` | Dynamic client registration: a public client that registers itself and is given a client id. |

### InboxOAuthOptions

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `baseUrl` | `string` | yes | An explicitly trusted API origin. Discovery never redirects or changes this origin. |
| `fetch` | `FetchLike` | no |  |

### createPkce

Function:
```ts
createPkce(): Promise<{ verifier: string; challenge: string; method: "S256"; state: string }>
```

Store the verifier and state in your session until the callback; never send the verifier in the authorization URL.

### parseOAuthCallback

Function:
```ts
parseOAuthCallback(value: string, expected: { redirectUri: string; state: string; issuer: string }): string
```

Validate state, issuer and the registered callback before returning a code.

### OAuthProtocolError

Class, extends Error:
```ts
new OAuthProtocolError(status: number, code: string, retryAfterSeconds: number | null = null)
```

**Properties**

| Property | Type | Description |
| --- | --- | --- |
| `name` |  |  |
| `status` | `number` |  |
| `code` | `string` |  |
| `retryAfterSeconds` | `number \| null` |  |

## The transport

What every resource sends through: one attempt per call, the credential as a bearer header, and an `ApiError` for an answer of `400` or more. A program rarely uses it directly. `client.transport` is the client's own.

### Transport

Sends requests with the credential, where the operation takes one, and turns error answers into `ApiError`s.

Class:
```ts
new Transport(options: TransportOptions)
```

**Properties**

| Property | Type | Description |
| --- | --- | --- |
| `baseUrl` | `string` |  |

**Methods**

| Method | Description |
| --- | --- |
| `url(path: string, options: Pick<CallOptions, "params" \| "query"> = {}): string` | The absolute URL of a path template with its parameters and query. |
| `streamUrl(path: string): string` | The stream's URL: the same origin over ws(s), with the credential as `token`. |
| `call(operation: string, method: HttpMethod, path: string, options: CallOptions = {}): Promise<ResponseLike>` | One request. Answers of 400 and above are thrown as `ApiError`; anything else is returned as it is. |
| `json<T>(operation: string, method: HttpMethod, path: string, options: CallOptions = {}): Promise<T>` | An operation that answers JSON: the parsed body. |
| `empty(operation: string, method: HttpMethod, path: string, options: CallOptions = {}): Promise<void>` | An operation that answers without a body (204). |
| `text(operation: string, method: HttpMethod, path: string, options: CallOptions = {}): Promise<string>` | An operation that answers text, such as a message's HTML body. |
| `bytes(operation: string, method: HttpMethod, path: string, options: CallOptions = {}): Promise<Uint8Array>` | An operation that answers bytes, such as a raw message or an attachment. |

### TransportOptions

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `apiKey` | `string` | yes |  |
| `baseUrl` | `string` | yes |  |
| `fetch` | `FetchLike` | no |  |
| `accountId` | `string` | no | The account every request is meant for, named in `x-doorman-account`; see `DoormanInboxOptions.accountId`. |

### CallOptions

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `params` | `Record<string, string>` | no | Values for the `{param}` placeholders of the path, encoded for the URL. |
| `query` | `Query` | no | Query parameters; `undefined` entries are left out. |
| `body` | `unknown` | no | A JSON body. |
| `headers` | `Record<string, string>` | no | Extra headers, lowercase names. |
| `accept` | `string` | no | The `Accept` header; `application/json` by default. |
| `authenticated` | `false` | no | `false` for an operation that takes no credential and answers to a secret in its body: the request then carries no `Authorization` header. |

### FetchLike

Type:
```ts
type FetchLike = (url: string, init: RequestInitLike) => Promise<ResponseLike>
```

The shape of `fetch` the client needs: the global one, or anything with the same shape (a test harness's dispatcher, a fetch with retries, a recorder).

### RequestInitLike

What the client passes to `fetch`: always a method, headers and at most a string body. The OAuth protocol requests add the last three: a redirect is handed back instead of followed (`manual` is the one mode every runtime accepts), no cookie is sent, and the answer stays out of any HTTP cache where the runtime takes that option.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `method` | `string` | yes |  |
| `headers` | `Record<string, string>` | yes |  |
| `body` | `string` | no |  |
| `redirect` | `"manual"` | no |  |
| `credentials` | `"omit"` | no |  |
| `cache` | `"no-store"` | no |  |

### ResponseLike

What the client reads from an answer. The platform `Response` has all of it.

**Fields**

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `status` | `number` | yes |  |
| `headers` | `{ get(name: string): string \| null }` | yes |  |

**Methods**

| Method | Description |
| --- | --- |
| `text(): Promise<string>` |  |
| `arrayBuffer(): Promise<ArrayBuffer>` |  |

### Query

Type:
```ts
type Query = Record<string, QueryValue>
```

### QueryValue

Type:
```ts
type QueryValue = string | number | boolean | undefined
```

### normalizeBaseUrl

Function:
```ts
normalizeBaseUrl(value: string): string
```

The base URL as the client keeps it: an http(s) origin plus an optional path, no trailing slash, no query or fragment.

### fillPath

Function:
```ts
fillPath(template: string, params: Record<string, string> = {}): string
```

`/v1/inboxes/{inboxId}` with its placeholders filled and encoded; a missing or empty value is a programming error.

### buildQuery

Function:
```ts
buildQuery(query: Query | undefined): string
```

A query string from its parameters, with its leading `?`, or the empty string when there is none to send. An `undefined` value is left out.

### readJson

Function:
```ts
readJson<T>(operation: string, response: ResponseLike): Promise<T>
```

The JSON body of a successful answer; a body that is not JSON is an `unexpected_response`.
