@billionsend/node 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,12 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 (2026-11-19)
4
+
5
+ The OpenAPI snapshot is now the document the API publishes (it had fallen behind), and the SDK follows it. `usage.get()` answers the new report (`emails.daily`, `emails.monthly`, `contacts`, `domains`, …) instead of `limits.emails_per_day`.
6
+
7
+ - Removed: `webhooks.rotate` (the API no longer has `POST /webhooks/{id}/rotate`; use `webhooks.rotateSigningSecret`, `POST /webhooks/{id}/signing-secret/rotate`) and `unsubscribes.delete` (a recipient's opt-out can no longer be deleted by the customer).
8
+ - New operations, named after their `operationId`: `automations` (`list`, `get`, `create`, `update`, `remove`, `validate`, `duplicate`, `simulate`, `stop`, `metrics`, `runs.list`, `runs.get`, `runs.cancel`), `events` (`list`, `get`, `create`, `update`, `remove`, `send`), `contacts.imports` (`list`, `get`, `create`), `contacts.segments.list`, `domains.claims` (`create`, `get`, `verify`), `emails.share` and `emails.unshare`, `emails.attachments` (`list`, `get`), `emails.metrics.links`, `emails.metrics.countries` and `emails.metrics.clients` (`emails.metrics(params)` stays the time series), `broadcasts.recipients` and `broadcasts.clickedLinks`, `logs` (`list`, `get`), `oauthGrants` (`list`, `revoke`), `webhooks.events` (`list`, `get`, `replay`, `attempts.list`), `webhooks.rotateSigningSecret`, `apiKeys.update` and `inboxes.agent.update`. Every cursor list has its `listAll` iterator (`recipientsAll`, `clickedLinksAll` for the two broadcast lists).
9
+ - `contacts.imports.create` uploads a CSV as `multipart/form-data`: pass `file` (a string, `Blob` or `File`) with `column_map`, `segments` and `topics` as objects; the SDK JSON-encodes them. The client's request layer takes a `FormData` body for such operations.
10
+ - `emails.send` and `emails.batch` follow the new request schema (`from` and `subject` are optional, for a send that names a template); the batch bodies of `emails.batch` and `contacts.batch.create` are typed from the document now.
11
+ - The inbox stream's `InboxEventType` is derived from the webhook event enum, so it includes `inbox.thread.assigned` and `inbox.thread.unassigned`.
12
+ - The changed request and response schemas (contacts, domains, broadcasts, webhooks, templates, inboxes, usage) are regenerated; their types in `@billionsend/node` follow the document.
13
+ - An inbox event stream drops a connection that delivered nothing (not even the server's 15-second keep-alive comment) for `idleTimeoutMs` (default 45 seconds, `0` turns it off) and reconnects from the last event id; a connection that died silently no longer hangs the loop.
14
+ - `verifyWebhook` accepts a secret and header values with surrounding whitespace (a secret read from a file keeps its trailing newline).
15
+ - An empty list in a query parameter is left out instead of sent as `key=`; a call whose `signal` is already aborted makes no request, whatever the `fetch` does with the signal.
16
+ - An inbox event stream resumes from the position the server opens it at: a new stream starts with a block that carries only an `id`, and the stream now keeps it, so a connection the server closes on schedule (about every ten minutes) before its first event reconnects with that `Last-Event-ID` and loses nothing that arrived in between.
17
+ - A successful reply with no body (a 204, an empty 200) comes back as `data: null` with no error, instead of a "not valid JSON" error.
18
+ - A path parameter of `.` or `..` is refused before any request (a URL folds it into another route: `emails.get("..")` would have called `GET /`).
19
+ - A `429` is retried for every request, a POST or PATCH without an `Idempotency-Key` included (the API answers it before it writes anything), waiting as `Retry-After` asks (seconds or an HTTP date; over a minute: the error is returned); `5xx`, timeouts and network errors are still retried only for requests safe to repeat.
20
+ - A header value HTTP cannot carry (non-ASCII or a control character, for example `Idempotency-Key: welcome/订单-1` or a key with a newline in it) fails the call at once with a `BillionSendError` named `invalid_header` that names the header and never the value; nothing is sent and nothing is retried (it used to surface as a network error, and a keyed send was retried).
21
+ - An API key is read without the whitespace around it (a key read from a file or the environment ends in a newline, which would otherwise break the `Authorization` header); a blank key counts as none, so the environment's key is used, and without one the call fails with `missing_api_key` before any request.
22
+ - `pnpm test:coverage` (at least 95% lines and branches of the hand-written code) and `pnpm test:e2e` (the live suite) are new; the contract mock now checks the answers a test queues against the document too.
23
+ - `pnpm openapi:check` compares the snapshot with the published document and fails when they differ; CI runs it on every push and pull request and once a day.
24
+
25
+ ## 0.1.1 (2026-11-17)
26
+
27
+ - An inbox event stream counts only the reconnects that fail in a row toward `maxReconnects`: each reconnect that opens the stream resets the count. A quiet inbox, whose stream the server closes every ten minutes or so with only keep-alive comments in between, no longer gives up after an hour.
28
+ - A reconnect the API refuses with a `Retry-After` (a 429, a 5xx) waits that long instead of the reconnect delay; one longer than 60 seconds throws that error at once. When the reconnects run out, the last one's error is thrown as its own class (`RateLimitError`, `APIError`, …) when the API answered; `APIConnectionError` ("gave up after N reconnects") only when it could not be reached.
29
+ - `APIError` carries the server's `Retry-After` too: `retryAfter`, in seconds, `null` without one.
30
+ - The `listAll` / `searchAll` iterators and `paginate()` throw a `BillionSendError` named `application_error` on an answer that is not a list page (no `data` array), and, after handing out the page, when the item to continue from has no `id` (missing, empty or not a string), instead of a `TypeError` or fetching the same page forever.
31
+
3
32
  ## 0.1.0 (2026-11-17)
4
33
 
5
34
  - First version of the BillionSend SDK for Node.js and TypeScript: every operation of the BillionSend API, grouped by resource and named after each operation's `operationId`, with request and response types generated from the OpenAPI document.
6
35
  - Results as `{ data, error, headers }`; methods never throw.
7
36
  - Errors as classes: `ValidationError`, `AuthenticationError`, `PermissionDeniedError`, `NotFoundError`, `ConflictError`, `RateLimitError` (with `retryAfter`), `APIError`, `APIConnectionError` and `APITimeoutError`, all `BillionSendError`s with `statusCode`, `name`, `message` and `requestId` (the answer's `x-request-id`). The iterators throw the same instances.
8
37
  - The sending operations always carry an `Idempotency-Key`: the caller's, or a new one per call that its retries reuse.
9
- - Retries for 429, 5xx, timeouts, network failures and `409 concurrent_idempotent_requests`, on requests safe to repeat; `retry-after` honoured, exponential backoff otherwise; per-attempt timeouts; injectable `fetch`.
38
+ - Retries for 429, 5xx, timeouts, network failures and `409 concurrent_idempotent_requests`, on requests safe to repeat (a 429 on any request: see 0.2.0); `retry-after` honoured, exponential backoff otherwise; per-attempt timeouts; injectable `fetch`.
10
39
  - List query parameters go comma-separated in one key, as the document declares them.
11
40
  - `listAll` / `searchAll` async iterators over cursor-paginated lists.
12
41
  - Inbox event streams (server-sent events) as async iterators of typed events, resuming with `Last-Event-ID` after a dropped connection; `stream.gap` handed out once per position; one inbox's stream ends after its `inbox.deleted` or `inbox.expired`.
package/README.md CHANGED
@@ -46,13 +46,13 @@ if (error) {
46
46
  }
47
47
  ```
48
48
 
49
- **Idempotency.** The sending operations (`emails.send`, `emails.batch`, `emails.receiving.reply` / `forward`, `inboxes.send`, `inboxes.drafts.send`, `inboxes.threads.emails.reply` / `forward`) always send an `Idempotency-Key` header. Without your own, each call gets a new random key and that call's retries reuse it, so a retry after a timeout cannot send twice. Pass your own key to make a send safe across calls and processes too; a repeat with the same key and payload returns the first result:
49
+ **Idempotency.** The sending operations (`emails.send`, `emails.batch`, `events.send`, `emails.receiving.reply` / `forward`, `inboxes.send`, `inboxes.drafts.send`, `inboxes.threads.emails.reply` / `forward`) always send an `Idempotency-Key` header. Without your own, each call gets a new random key and that call's retries reuse it, so a retry after a timeout cannot send twice. Pass your own key to make a send safe across calls and processes too; a repeat with the same key and payload returns the first result:
50
50
 
51
51
  ```ts
52
52
  await bs.emails.send(message, { idempotencyKey: `welcome/${user.id}` });
53
53
  ```
54
54
 
55
- **Retries.** Failures worth retrying are retried up to `maxRetries` times (default 2): `429`, `5xx`, timeouts and network errors, and the `409 concurrent_idempotent_requests` the API answers while the first attempt with the same key is still running. Only requests safe to repeat are retried: `GET`, `PUT`, `DELETE` and the sending operations above. The client waits as `retry-after` asks, or backs off exponentially (0.5 s, 1 s, 2 s … up to 8 s, with jitter); a `retry-after` over a minute is not waited for, and the error comes back instead.
55
+ **Retries.** Failures worth retrying are retried up to `maxRetries` times (default 2): `429`, `5xx`, timeouts and network errors, and the `409 concurrent_idempotent_requests` the API answers while the first attempt with the same key is still running. A `429` is retried for every request, because the API answers it before it writes anything; the other failures (`5xx`, timeouts, network errors, the `409`) only for requests safe to repeat: `GET`, `PUT`, `DELETE` and the sending operations above. The client waits as `retry-after` asks, or backs off exponentially (0.5 s, 1 s, 2 s … up to 8 s, with jitter); a `retry-after` over a minute is not waited for, and the error comes back instead.
56
56
 
57
57
  ```ts
58
58
  const bs = new BillionSend({ apiKey: "bs_...", maxRetries: 4 });
@@ -122,6 +122,8 @@ for await (const item of opened.data) {
122
122
  // Resumed from too far back: events may be missing. Re-read the threads.
123
123
  continue;
124
124
  }
125
+ // `types` does not filter `inbox.deleted` and `inbox.expired`: they always arrive, without a thread.
126
+ if (item.event !== "inbox.email.received") continue;
125
127
  const { thread_id, email_id } = item.data.data;
126
128
  if (!thread_id || !email_id) continue;
127
129
 
@@ -153,7 +155,7 @@ const { data: code } = await bs.inboxes.codes.latest("support@acme.dev", { from:
153
155
  - `InboxStreamEvent`: `{ id, event, data }`, where `event` is the webhook event name (`inbox.email.received`, `inbox.thread.created`, `inbox.draft.sent`, `email.received`, …) and `data` is `{ type, created_at, inbox_id, data }`, the webhook payload's metadata with the ids to read next (`thread_id`, `email_id`, `draft_id`).
154
156
  - `StreamGapEvent`: `{ id: null, event: "stream.gap", data: { reason } }` when the stream resumed from further back than the server keeps (24 hours): events may be missing, so read the lists again. One stream hands it out once per position.
155
157
 
156
- When the connection drops (the server also closes every stream about every ten minutes), the stream reconnects with `Last-Event-ID` and replays what it missed before the live events. It gives up after `maxReconnects` failures in a row (default 5) with an `APIConnectionError`; a refusal a retry cannot fix (a revoked key) is thrown as its own class. One inbox's stream ends after that inbox's `inbox.deleted` or `inbox.expired`.
158
+ When the connection drops (the server also closes every stream about every ten minutes), the stream reconnects with `Last-Event-ID` and replays what it missed before the live events. A connection that delivers nothing, not even the server's keep-alive comment (sent every 15 seconds), for `idleTimeoutMs` (default 45 seconds, `0` turns it off) counts as dropped, so a connection that died silently cannot hang the loop. `maxReconnects` (default 5) bounds the reconnects that fail in a row; one that opens the stream resets the count. A reconnect the API refuses with a `Retry-After` waits that long (longer than 60 seconds: that error is thrown at once). When the reconnects run out, the last one's error is thrown: the API's answer as its own class (`RateLimitError`, `APIError`), or an `APIConnectionError` when the API could not be reached; a refusal a retry cannot fix (a revoked key) is thrown at once. One inbox's stream ends after that inbox's `inbox.deleted` or `inbox.expired`.
157
159
 
158
160
  ```ts
159
161
  const opened = await bs.inboxes.events.stream({ types: "inbox.email.received,inbox.thread.created" }, {
@@ -161,14 +163,14 @@ const opened = await bs.inboxes.events.stream({ types: "inbox.email.received,inb
161
163
  });
162
164
  if (opened.error) throw opened.error;
163
165
  for await (const item of opened.data) {
164
- saved = opened.data.lastEventId;
166
+ saved = opened.data.lastEventId ?? undefined;
165
167
  // break, or opened.data.close(), ends the stream
166
168
  }
167
169
  ```
168
170
 
169
171
  ## Verify webhooks
170
172
 
171
- Every webhook delivery is signed with the endpoint's `whsec_` secret (shown when you create the endpoint, and by `webhooks.rotate`). `verifyWebhook` checks the signature and the timestamp (within 5 minutes by default, so a captured delivery cannot be replayed) and returns the parsed event; anything wrong throws a `WebhookVerificationError`. Pass the body exactly as it arrived, before any JSON parsing:
173
+ Every webhook delivery is signed with the endpoint's `whsec_` secret (shown when you create the endpoint, and by `webhooks.rotateSigningSecret`). `verifyWebhook` checks the signature and the timestamp (within 5 minutes by default, so a captured delivery cannot be replayed) and returns the parsed event; anything wrong throws a `WebhookVerificationError`. Pass the body exactly as it arrived, before any JSON parsing:
172
174
 
173
175
  ```ts
174
176
  import express from "express";
@@ -192,6 +194,21 @@ app.post("/webhooks/billionsend", express.raw({ type: "application/json" }), asy
192
194
 
193
195
  With the Fetch API (Next.js route handlers, Hono, Bun, Deno, workers) it is `await verifyWebhook(await request.text(), request.headers, secret)`. During a secret rotation a delivery carries a signature for each live secret, and either secret verifies it.
194
196
 
197
+ ## Import contacts from a CSV
198
+
199
+ `contacts.imports.create` uploads a CSV (a string, a `Blob` or a `File`) and imports it in the background; poll the import for its `status` and `counts`. `column_map`, `segments` and `topics` are objects here; the SDK sends them as the JSON text the endpoint expects.
200
+
201
+ ```ts
202
+ const started = await bs.contacts.imports.create({
203
+ file: csvText, // "Email,First Name\nana@acme.dev,Ana\n"
204
+ column_map: { email: "Email", first_name: "First Name" },
205
+ on_conflict: "skip",
206
+ });
207
+ if (started.error) throw started.error;
208
+
209
+ const done = await bs.contacts.imports.get(started.data.id); // status: queued, in_progress, completed or failed
210
+ ```
211
+
195
212
  ## Agent sign-up
196
213
 
197
214
  An agent can create its own account with no API key; the answer carries the new key and inbox.
@@ -229,21 +246,25 @@ Every method takes a last `options` argument with `signal`, `headers`, `timeoutM
229
246
 
230
247
  | Property | Covers |
231
248
  | --- | --- |
232
- | `emails` | send, batch, list, get, update, cancel, delete, insights, metrics |
249
+ | `emails` | send, batch, list, get, update, cancel, delete, insights, share, unshare, `metrics` (the time series; `metrics.links`, `metrics.countries`, `metrics.clients`), `attachments` (list, get) |
233
250
  | `emails.receiving` | received mail: list, get, delete, reply, forward, `attachments` (list, get, text) |
234
- | `domains` | create, list, get, update, delete, verify |
235
- | `apiKeys` | create, list, delete |
236
- | `contacts` | create, list, get, update, delete, preferences link, `batch`, `topics`, `segments` |
251
+ | `domains` | create, list, get, update, delete, verify, `claims` (create, get, verify) |
252
+ | `apiKeys` | create, list, update, delete |
253
+ | `contacts` | create, list, get, update, delete, preferences link, `batch`, `imports` (create, list, get), `topics`, `segments` (list, add, remove) |
237
254
  | `audiences.contacts` | contacts addressed through an audience |
238
255
  | `contactProperties`, `segments`, `topics` | create, list, get, update, delete (segment contacts under `segments.contacts`) |
239
- | `broadcasts` | create, list, get, update, delete, send, duplicate, cancel |
256
+ | `broadcasts` | create, list, get, update, delete, send, duplicate, cancel, recipients, clickedLinks |
240
257
  | `templates` | create, list, get, update, delete, publish, duplicate |
241
- | `webhooks` | create, list, get, update, delete, rotate |
258
+ | `webhooks` | create, list, get, update, delete, rotateSigningSecret, `events` (list, get, replay, `attempts.list`) |
242
259
  | `suppressions` | create, list, get, delete, `batch` add / remove |
243
- | `unsubscribes` | create, list, delete |
260
+ | `unsubscribes` | create, list |
244
261
  | `verifications` | availability, estimate, create, list, get |
245
262
  | `usage`, `deliverability` | get |
246
- | `inboxes` | create, list, get, update, delete, send, `agent`, `safety`, `labels`, `threads` (search, labels, emails, reply, forward), `quarantine`, `codes`, `drafts`, `events` |
263
+ | `events` | custom events: create, list, get, update, remove, send |
264
+ | `automations` | create, list, get, update, remove, validate, duplicate, simulate, stop, metrics, `runs` (list, get, cancel) |
265
+ | `logs` | list, get |
266
+ | `oauthGrants` | list, revoke |
267
+ | `inboxes` | create, list, get, update, delete, send, `agent` (get, update), `safety`, `labels`, `threads` (search, labels, emails, reply, forward), `quarantine`, `codes`, `drafts`, `events` |
247
268
  | `agent` | signup, status, claimEmail |
248
269
 
249
270
  Method names are camelCase; request and response fields keep the API's snake_case names. All request and response types are exported, named after the API's schemas (`SendEmailRequest`, `Inbox`, …).
@@ -252,16 +273,19 @@ Method names are camelCase; request and response fields keep the API's snake_cas
252
273
 
253
274
  ```bash
254
275
  pnpm install
255
- pnpm typecheck && pnpm lint && pnpm test
276
+ pnpm typecheck && pnpm lint && pnpm test:coverage # fails below 95% lines and branches of the hand-written code
256
277
  pnpm build && pnpm test:smoke
257
278
  ```
258
279
 
280
+ `pnpm test:e2e` runs the SDK against the live API, as a developer would (it needs `BILLIONSEND_E2E_API_KEY`, never runs in CI, and checks every real answer against the published OpenAPI document). It creates only objects named `sdk-e2e-node-…`, sends only to the simulator's success address and deletes what it made.
281
+
259
282
  The contract is `openapi/api.openapi.json`, a snapshot of the published OpenAPI document; its descriptions become the doc comments of the generated types. The tests run every SDK method against a local mock that validates each request and answers from that snapshot, and fail when an operation has no SDK method. When the API changes:
260
283
 
261
284
  ```bash
262
285
  pnpm openapi:sync # or: pnpm openapi:sync --from path/to/api.openapi.json
263
286
  pnpm generate # regenerates src/generated/openapi.ts
264
287
  pnpm test # what fails is what the SDK has to follow
288
+ pnpm openapi:check # fails when the snapshot differs from the published document (CI runs it on every push and daily)
265
289
  ```
266
290
 
267
291
  ## Releasing