@billionsend/node 0.0.0-stage → 0.1.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/dist/index.js ADDED
@@ -0,0 +1,1698 @@
1
+ // src/errors.ts
2
+ var BillionSendError = class extends Error {
3
+ statusCode;
4
+ name;
5
+ requestId;
6
+ constructor(init) {
7
+ super(init.message);
8
+ this.name = init.name ?? "application_error";
9
+ this.statusCode = init.statusCode ?? null;
10
+ this.requestId = init.requestId ?? null;
11
+ }
12
+ toJSON() {
13
+ return { statusCode: this.statusCode, name: this.name, message: this.message, requestId: this.requestId };
14
+ }
15
+ };
16
+ var ValidationError = class extends BillionSendError {
17
+ };
18
+ var AuthenticationError = class extends BillionSendError {
19
+ };
20
+ var PermissionDeniedError = class extends BillionSendError {
21
+ };
22
+ var NotFoundError = class extends BillionSendError {
23
+ };
24
+ var ConflictError = class extends BillionSendError {
25
+ };
26
+ var RateLimitError = class extends BillionSendError {
27
+ retryAfter;
28
+ constructor(init) {
29
+ super(init);
30
+ this.retryAfter = init.retryAfter ?? null;
31
+ }
32
+ };
33
+ var APIError = class extends BillionSendError {
34
+ };
35
+ var APIConnectionError = class extends BillionSendError {
36
+ constructor(message = "Connection error") {
37
+ super({ message });
38
+ }
39
+ };
40
+ var APITimeoutError = class extends APIConnectionError {
41
+ constructor(message = "Request timed out") {
42
+ super(message);
43
+ }
44
+ };
45
+ var WebhookVerificationError = class extends BillionSendError {
46
+ constructor(message) {
47
+ super({ message, name: "webhook_verification_error" });
48
+ }
49
+ };
50
+ function applicationError(message, statusCode = null) {
51
+ return new BillionSendError({ message, statusCode });
52
+ }
53
+ function isRecord(value) {
54
+ return typeof value === "object" && value !== null && !Array.isArray(value);
55
+ }
56
+ function parseRetryAfter(value, now = Date.now()) {
57
+ if (value == null || value.trim() === "") return null;
58
+ const seconds = Number(value);
59
+ if (Number.isFinite(seconds)) return Math.max(0, seconds);
60
+ const at = Date.parse(value);
61
+ return Number.isNaN(at) ? null : Math.max(0, (at - now) / 1e3);
62
+ }
63
+ function errorClass(status) {
64
+ switch (status) {
65
+ case 400:
66
+ case 422:
67
+ return ValidationError;
68
+ case 401:
69
+ return AuthenticationError;
70
+ case 403:
71
+ return PermissionDeniedError;
72
+ case 404:
73
+ return NotFoundError;
74
+ case 409:
75
+ return ConflictError;
76
+ default:
77
+ return status >= 500 ? APIError : BillionSendError;
78
+ }
79
+ }
80
+ function errorFromResponse(status, statusText, text, headers = {}) {
81
+ let body;
82
+ try {
83
+ body = text === "" ? void 0 : JSON.parse(text);
84
+ } catch {
85
+ body = void 0;
86
+ }
87
+ let name = "application_error";
88
+ let message;
89
+ if (isRecord(body) && typeof body.name === "string" && typeof body.message === "string") {
90
+ name = body.name;
91
+ message = body.message;
92
+ } else {
93
+ const detail = text.trim().slice(0, 200);
94
+ const label = `${status}${statusText ? ` ${statusText}` : ""}`;
95
+ message = detail ? `Unexpected ${label} response: ${detail}` : `Unexpected ${label} response`;
96
+ }
97
+ const init = { message, name, statusCode: status, requestId: headers["x-request-id"] ?? null };
98
+ if (status === 429)
99
+ return new RateLimitError({ ...init, retryAfter: parseRetryAfter(headers["retry-after"]) });
100
+ return new (errorClass(status))(init);
101
+ }
102
+
103
+ // src/retry.ts
104
+ var MAX_RETRY_AFTER_MS = 6e4;
105
+ var BASE_DELAY_MS = 500;
106
+ var MAX_BACKOFF_MS = 8e3;
107
+ var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);
108
+ function retryDelayMs(attempt, retryAfter, now = Date.now(), random = Math.random) {
109
+ if (retryAfter != null && retryAfter.trim() !== "") {
110
+ let ms;
111
+ const seconds = Number(retryAfter);
112
+ if (Number.isFinite(seconds)) {
113
+ ms = Math.max(0, seconds * 1e3);
114
+ } else {
115
+ const at = Date.parse(retryAfter);
116
+ if (!Number.isNaN(at)) ms = Math.max(0, at - now);
117
+ }
118
+ if (ms !== void 0) return ms > MAX_RETRY_AFTER_MS ? void 0 : Math.ceil(ms);
119
+ }
120
+ const backoff = Math.min(BASE_DELAY_MS * 2 ** attempt, MAX_BACKOFF_MS);
121
+ return Math.round(backoff * (1 - random() * 0.25));
122
+ }
123
+ function retryable(error, idempotencyKey) {
124
+ if (error instanceof APIConnectionError) return true;
125
+ const status = error.statusCode;
126
+ if (status === null) return false;
127
+ if (status === 429 || status >= 500) return true;
128
+ return idempotencyKey && status === 409 && error.name === "concurrent_idempotent_requests";
129
+ }
130
+ function newIdempotencyKey() {
131
+ const webCrypto = globalThis.crypto;
132
+ if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
133
+ const bytes = new Uint8Array(16);
134
+ if (typeof webCrypto?.getRandomValues === "function") webCrypto.getRandomValues(bytes);
135
+ else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
136
+ bytes[6] = (bytes[6] ?? 0) & 15 | 64;
137
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
138
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
139
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
140
+ }
141
+ function sleep(ms, signal) {
142
+ return new Promise((resolve) => {
143
+ if (signal?.aborted) {
144
+ resolve(false);
145
+ return;
146
+ }
147
+ const onAbort = () => {
148
+ clearTimeout(timer);
149
+ resolve(false);
150
+ };
151
+ const timer = setTimeout(() => {
152
+ signal?.removeEventListener("abort", onAbort);
153
+ resolve(true);
154
+ }, ms);
155
+ signal?.addEventListener("abort", onAbort, { once: true });
156
+ });
157
+ }
158
+
159
+ // src/version.ts
160
+ var VERSION = "0.1.0";
161
+
162
+ // src/core.ts
163
+ var DEFAULT_BASE_URL = "https://api.billionsend.com";
164
+ var DEFAULT_TIMEOUT_MS = 6e4;
165
+ var DEFAULT_MAX_RETRIES = 2;
166
+ function readEnv(name) {
167
+ const env = globalThis.process?.env;
168
+ const value = env?.[name];
169
+ return value === void 0 || value === "" ? void 0 : value;
170
+ }
171
+ function failure(error, headers = null) {
172
+ return { data: null, error, headers };
173
+ }
174
+ function headersOf(response) {
175
+ const out = {};
176
+ response.headers.forEach((value, key) => {
177
+ out[key.toLowerCase()] = value;
178
+ });
179
+ return out;
180
+ }
181
+ function describe(cause) {
182
+ if (cause instanceof Error) {
183
+ const inner = cause.cause;
184
+ return inner instanceof Error ? `${cause.message} (${inner.message})` : cause.message;
185
+ }
186
+ return String(cause);
187
+ }
188
+ function lowerCaseKeys(headers) {
189
+ const out = {};
190
+ if (!headers) return out;
191
+ for (const [key, value] of Object.entries(headers)) {
192
+ if (value !== void 0) out[key.toLowerCase()] = value;
193
+ }
194
+ return out;
195
+ }
196
+ function fillPath(template, params) {
197
+ let missing;
198
+ const filled = template.replace(/\{([^}]+)\}/g, (_, name) => {
199
+ const value = params?.[name];
200
+ if (value === void 0 || value === null || String(value) === "") {
201
+ missing ??= name;
202
+ return "";
203
+ }
204
+ return encodeURIComponent(String(value));
205
+ });
206
+ return missing === void 0 ? filled : applicationError(`Missing path parameter "${missing}"`);
207
+ }
208
+ function queryString(query) {
209
+ if (!query) return "";
210
+ const params = new URLSearchParams();
211
+ for (const [key, value] of Object.entries(query)) {
212
+ if (value === void 0 || value === null) continue;
213
+ if (Array.isArray(value)) {
214
+ params.append(key, value.map(String).join(","));
215
+ } else {
216
+ params.append(key, String(value));
217
+ }
218
+ }
219
+ const text = params.toString();
220
+ return text === "" ? "" : `?${text}`;
221
+ }
222
+ var Core = class {
223
+ baseUrl;
224
+ timeoutMs;
225
+ maxRetries;
226
+ #apiKey;
227
+ #fetch;
228
+ #headers;
229
+ constructor(options) {
230
+ this.#apiKey = options.apiKey ?? readEnv("BILLIONSEND_API_KEY");
231
+ this.baseUrl = (options.baseUrl ?? readEnv("BILLIONSEND_BASE_URL") ?? DEFAULT_BASE_URL).replace(
232
+ /\/+$/,
233
+ ""
234
+ );
235
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
236
+ this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
237
+ const fetchImpl = options.fetch ?? globalThis.fetch;
238
+ if (typeof fetchImpl !== "function") {
239
+ throw new TypeError("No fetch implementation: use Node.js 18 or later, or pass `fetch` in the options");
240
+ }
241
+ if (!(this.timeoutMs > 0)) throw new TypeError("timeoutMs must be a positive number");
242
+ if (!Number.isInteger(this.maxRetries) || this.maxRetries < 0) {
243
+ throw new TypeError("maxRetries must be a non-negative integer");
244
+ }
245
+ this.#fetch = fetchImpl;
246
+ this.#headers = lowerCaseKeys(options.headers);
247
+ }
248
+ /** Whether an API key is configured. */
249
+ get hasApiKey() {
250
+ return this.#apiKey !== void 0;
251
+ }
252
+ /** Calls one operation and parses its JSON answer. */
253
+ request(method, path, init = {}) {
254
+ return this.#execute(method, path, init, false);
255
+ }
256
+ /** Opens an event stream; the connection is timed only until the response headers arrive. */
257
+ openStream(method, path, init = {}) {
258
+ return this.#execute(method, path, init, true);
259
+ }
260
+ async #execute(lowerMethod, template, init, stream) {
261
+ const method = lowerMethod.toUpperCase();
262
+ const options = init.options ?? {};
263
+ const auth = init.auth !== false;
264
+ if (auth && this.#apiKey === void 0) {
265
+ return failure(
266
+ new AuthenticationError({
267
+ name: "missing_api_key",
268
+ message: "No API key: pass one to new BillionSend() or set BILLIONSEND_API_KEY"
269
+ })
270
+ );
271
+ }
272
+ const path = fillPath(template, init.path);
273
+ if (typeof path !== "string") return failure(path);
274
+ const url = `${this.baseUrl}${path}${queryString(init.query)}`;
275
+ const headers = {
276
+ accept: stream ? "text/event-stream" : "application/json",
277
+ "user-agent": `billionsend-node/${VERSION}`,
278
+ ...this.#headers,
279
+ ...lowerCaseKeys(options.headers),
280
+ ...lowerCaseKeys(init.headers)
281
+ };
282
+ let body;
283
+ if (init.body !== void 0) {
284
+ body = JSON.stringify(init.body);
285
+ headers["content-type"] = "application/json";
286
+ }
287
+ if (init.idempotencyKey !== void 0) headers["idempotency-key"] = init.idempotencyKey;
288
+ else if (init.idempotent && headers["idempotency-key"] === void 0) {
289
+ headers["idempotency-key"] = newIdempotencyKey();
290
+ }
291
+ if (auth) headers.authorization = `Bearer ${this.#apiKey}`;
292
+ else delete headers.authorization;
293
+ const keyed = headers["idempotency-key"] !== void 0;
294
+ const retryable2 = IDEMPOTENT_METHODS.has(method) || keyed;
295
+ const maxRetries = options.maxRetries ?? this.maxRetries;
296
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
297
+ for (let attempt = 0; ; attempt++) {
298
+ const outcome = await this.#attempt(method, url, headers, body, timeoutMs, options.signal, stream);
299
+ const error = outcome.result.error;
300
+ if (error === null || !retryable2 || attempt >= maxRetries || !retryable(error, keyed)) {
301
+ return outcome.result;
302
+ }
303
+ const delay = retryDelayMs(attempt, outcome.retryAfter);
304
+ if (delay === void 0) return outcome.result;
305
+ if (!await sleep(delay, options.signal)) return failure(applicationError("Request was aborted"));
306
+ }
307
+ }
308
+ async #attempt(method, url, headers, body, timeoutMs, signal, stream) {
309
+ const controller = new AbortController();
310
+ let timedOut = false;
311
+ const timer = setTimeout(() => {
312
+ timedOut = true;
313
+ controller.abort();
314
+ }, timeoutMs);
315
+ const onAbort = () => controller.abort();
316
+ if (signal?.aborted) controller.abort();
317
+ else signal?.addEventListener("abort", onAbort, { once: true });
318
+ const release = () => {
319
+ clearTimeout(timer);
320
+ signal?.removeEventListener("abort", onAbort);
321
+ };
322
+ try {
323
+ const response = await this.#fetch(url, { method, headers, body, signal: controller.signal });
324
+ const responseHeaders = headersOf(response);
325
+ if (stream && response.ok) {
326
+ clearTimeout(timer);
327
+ const contentType = response.headers.get("content-type") ?? "";
328
+ if (!contentType.includes("text/event-stream")) {
329
+ release();
330
+ controller.abort();
331
+ return {
332
+ result: failure(
333
+ new BillionSendError({
334
+ message: `Expected an event stream, got ${contentType || "no content type"}`,
335
+ statusCode: response.status,
336
+ requestId: responseHeaders["x-request-id"] ?? null
337
+ }),
338
+ responseHeaders
339
+ )
340
+ };
341
+ }
342
+ let closed = false;
343
+ const connection = {
344
+ response,
345
+ close: () => {
346
+ if (closed) return;
347
+ closed = true;
348
+ release();
349
+ controller.abort();
350
+ }
351
+ };
352
+ return { result: { data: connection, error: null, headers: responseHeaders } };
353
+ }
354
+ const text = await response.text();
355
+ release();
356
+ if (response.ok) {
357
+ try {
358
+ return { result: { data: JSON.parse(text), error: null, headers: responseHeaders } };
359
+ } catch {
360
+ return {
361
+ result: failure(
362
+ new BillionSendError({
363
+ message: "The response body is not valid JSON",
364
+ statusCode: response.status,
365
+ requestId: responseHeaders["x-request-id"] ?? null
366
+ }),
367
+ responseHeaders
368
+ )
369
+ };
370
+ }
371
+ }
372
+ return {
373
+ result: failure(
374
+ errorFromResponse(response.status, response.statusText, text, responseHeaders),
375
+ responseHeaders
376
+ ),
377
+ retryAfter: response.headers.get("retry-after")
378
+ };
379
+ } catch (cause) {
380
+ release();
381
+ if (signal?.aborted) return { result: failure(applicationError("Request was aborted")) };
382
+ if (timedOut)
383
+ return { result: failure(new APITimeoutError(`Request timed out after ${timeoutMs} ms`)) };
384
+ return { result: failure(new APIConnectionError(`Network error: ${describe(cause)}`)) };
385
+ }
386
+ }
387
+ };
388
+
389
+ // src/pagination.ts
390
+ async function* paginate(fetchPage, start = {}) {
391
+ const backward = start.before !== void 0 && start.before !== null;
392
+ let cursor = backward ? { before: start.before } : start.after ? { after: start.after } : {};
393
+ while (true) {
394
+ const page = await fetchPage(cursor);
395
+ if (page.error !== null) throw page.error;
396
+ const items = page.data.data;
397
+ for (const item of items) yield item;
398
+ if (!page.data.has_more || items.length === 0) return;
399
+ const edge = backward ? items[0] : items[items.length - 1];
400
+ if (edge === void 0) return;
401
+ cursor = backward ? { before: edge.id } : { after: edge.id };
402
+ }
403
+ }
404
+
405
+ // src/resource.ts
406
+ var Resource = class {
407
+ core;
408
+ constructor(core) {
409
+ this.core = core;
410
+ }
411
+ };
412
+ function idempotent(options) {
413
+ return { idempotent: true, idempotencyKey: options?.idempotencyKey, options };
414
+ }
415
+
416
+ // src/resources/account.ts
417
+ var Domains = class extends Resource {
418
+ /** `POST /domains` */
419
+ create(payload, options) {
420
+ return this.core.request("post", "/domains", { body: payload, options });
421
+ }
422
+ /** `GET /domains` */
423
+ list(params, options) {
424
+ return this.core.request("get", "/domains", { query: params, options });
425
+ }
426
+ /** Every domain, fetched page by page. */
427
+ listAll(params, options) {
428
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
429
+ }
430
+ /** `GET /domains/{id}` */
431
+ get(id, options) {
432
+ return this.core.request("get", "/domains/{id}", { path: { id }, options });
433
+ }
434
+ /** `PATCH /domains/{id}` */
435
+ update(id, payload, options) {
436
+ return this.core.request("patch", "/domains/{id}", { path: { id }, body: payload, options });
437
+ }
438
+ /** `DELETE /domains/{id}` */
439
+ delete(id, options) {
440
+ return this.core.request("delete", "/domains/{id}", { path: { id }, options });
441
+ }
442
+ /** `POST /domains/{id}/verify` */
443
+ verify(id, options) {
444
+ return this.core.request("post", "/domains/{id}/verify", { path: { id }, options });
445
+ }
446
+ };
447
+ var ApiKeys = class extends Resource {
448
+ /** `POST /api-keys`: the token is returned only in this answer. */
449
+ create(payload, options) {
450
+ return this.core.request("post", "/api-keys", { body: payload, options });
451
+ }
452
+ /** `GET /api-keys` */
453
+ list(params, options) {
454
+ return this.core.request("get", "/api-keys", { query: params, options });
455
+ }
456
+ /** Every API key, fetched page by page. */
457
+ listAll(params, options) {
458
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
459
+ }
460
+ /** `DELETE /api-keys/{id}` */
461
+ delete(id, options) {
462
+ return this.core.request("delete", "/api-keys/{id}", { path: { id }, options });
463
+ }
464
+ };
465
+ var Webhooks = class extends Resource {
466
+ /** `POST /webhooks` */
467
+ create(payload, options) {
468
+ return this.core.request("post", "/webhooks", { body: payload, options });
469
+ }
470
+ /** `GET /webhooks` */
471
+ list(params, options) {
472
+ return this.core.request("get", "/webhooks", { query: params, options });
473
+ }
474
+ /** Every webhook, fetched page by page. */
475
+ listAll(params, options) {
476
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
477
+ }
478
+ /** `GET /webhooks/{id}` */
479
+ get(id, options) {
480
+ return this.core.request("get", "/webhooks/{id}", { path: { id }, options });
481
+ }
482
+ /** `PATCH /webhooks/{id}` */
483
+ update(id, payload, options) {
484
+ return this.core.request("patch", "/webhooks/{id}", { path: { id }, body: payload, options });
485
+ }
486
+ /** `DELETE /webhooks/{id}` */
487
+ delete(id, options) {
488
+ return this.core.request("delete", "/webhooks/{id}", { path: { id }, options });
489
+ }
490
+ /** `POST /webhooks/{id}/rotate`: rotates the signing secret. */
491
+ rotate(id, payload, options) {
492
+ return this.core.request("post", "/webhooks/{id}/rotate", { path: { id }, body: payload, options });
493
+ }
494
+ };
495
+ var Usage = class extends Resource {
496
+ /** `GET /usage` */
497
+ get(options) {
498
+ return this.core.request("get", "/usage", { options });
499
+ }
500
+ };
501
+ var Deliverability = class extends Resource {
502
+ /** `GET /deliverability` */
503
+ get(options) {
504
+ return this.core.request("get", "/deliverability", { options });
505
+ }
506
+ };
507
+ var Agent = class extends Resource {
508
+ /** `POST /agent/signup`: needs no API key; the answer carries the new account's key. */
509
+ signup(payload, options) {
510
+ return this.core.request("post", "/agent/signup", { body: payload, options, auth: false });
511
+ }
512
+ /** `GET /agent/status` */
513
+ status(options) {
514
+ return this.core.request("get", "/agent/status", { options });
515
+ }
516
+ /** `POST /agent/claim-email`: sends the claim link again. */
517
+ claimEmail(options) {
518
+ return this.core.request("post", "/agent/claim-email", { options });
519
+ }
520
+ };
521
+
522
+ // src/resources/broadcasts.ts
523
+ var Broadcasts = class extends Resource {
524
+ /** `POST /broadcasts` */
525
+ create(payload, options) {
526
+ return this.core.request("post", "/broadcasts", { body: payload, options });
527
+ }
528
+ /** `GET /broadcasts` */
529
+ list(params, options) {
530
+ return this.core.request("get", "/broadcasts", { query: params, options });
531
+ }
532
+ /** Every broadcast, fetched page by page. */
533
+ listAll(params, options) {
534
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
535
+ }
536
+ /** `GET /broadcasts/{id}` */
537
+ get(id, options) {
538
+ return this.core.request("get", "/broadcasts/{id}", { path: { id }, options });
539
+ }
540
+ /** `PATCH /broadcasts/{id}` */
541
+ update(id, payload, options) {
542
+ return this.core.request("patch", "/broadcasts/{id}", { path: { id }, body: payload, options });
543
+ }
544
+ /** `DELETE /broadcasts/{id}` */
545
+ delete(id, options) {
546
+ return this.core.request("delete", "/broadcasts/{id}", { path: { id }, options });
547
+ }
548
+ /** `POST /broadcasts/{id}/send` */
549
+ send(id, payload, options) {
550
+ return this.core.request("post", "/broadcasts/{id}/send", { path: { id }, body: payload, options });
551
+ }
552
+ /** `POST /broadcasts/{id}/duplicate` */
553
+ duplicate(id, options) {
554
+ return this.core.request("post", "/broadcasts/{id}/duplicate", { path: { id }, options });
555
+ }
556
+ /** `POST /broadcasts/{id}/cancel` */
557
+ cancel(id, options) {
558
+ return this.core.request("post", "/broadcasts/{id}/cancel", { path: { id }, options });
559
+ }
560
+ };
561
+ var Templates = class extends Resource {
562
+ /** `POST /templates` */
563
+ create(payload, options) {
564
+ return this.core.request("post", "/templates", { body: payload, options });
565
+ }
566
+ /** `GET /templates` */
567
+ list(params, options) {
568
+ return this.core.request("get", "/templates", { query: params, options });
569
+ }
570
+ /** Every template, fetched page by page. */
571
+ listAll(params, options) {
572
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
573
+ }
574
+ /** `GET /templates/{id}`: `id` is the template id or its alias. */
575
+ get(id, options) {
576
+ return this.core.request("get", "/templates/{id}", { path: { id }, options });
577
+ }
578
+ /** `PATCH /templates/{id}` */
579
+ update(id, payload, options) {
580
+ return this.core.request("patch", "/templates/{id}", { path: { id }, body: payload, options });
581
+ }
582
+ /** `DELETE /templates/{id}` */
583
+ delete(id, options) {
584
+ return this.core.request("delete", "/templates/{id}", { path: { id }, options });
585
+ }
586
+ /** `POST /templates/{id}/publish` */
587
+ publish(id, options) {
588
+ return this.core.request("post", "/templates/{id}/publish", { path: { id }, options });
589
+ }
590
+ /** `POST /templates/{id}/duplicate` */
591
+ duplicate(id, options) {
592
+ return this.core.request("post", "/templates/{id}/duplicate", { path: { id }, options });
593
+ }
594
+ };
595
+
596
+ // src/resources/contacts.ts
597
+ var ContactBatch = class extends Resource {
598
+ /**
599
+ * `POST /contacts/batch`: up to 1000 contacts, each shaped like {@link Contacts.create}'s payload.
600
+ * The API document leaves the items untyped; the endpoint validates each one as a contact.
601
+ */
602
+ create(payload, params, options) {
603
+ return this.core.request("post", "/contacts/batch", {
604
+ body: payload,
605
+ query: params,
606
+ headers: { "x-batch-validation": options?.batchValidation },
607
+ options
608
+ });
609
+ }
610
+ /** `POST /contacts/batch/get` */
611
+ get(payload, options) {
612
+ return this.core.request("post", "/contacts/batch/get", { body: payload, options });
613
+ }
614
+ /** `POST /contacts/batch/remove` */
615
+ remove(payload, options) {
616
+ return this.core.request("post", "/contacts/batch/remove", { body: payload, options });
617
+ }
618
+ };
619
+ var ContactTopics = class extends Resource {
620
+ /** `GET /contacts/{id}/topics` */
621
+ list(contactId, options) {
622
+ return this.core.request("get", "/contacts/{id}/topics", { path: { id: contactId }, options });
623
+ }
624
+ /** `PATCH /contacts/{id}/topics` */
625
+ update(contactId, payload, options) {
626
+ return this.core.request("patch", "/contacts/{id}/topics", {
627
+ path: { id: contactId },
628
+ body: payload,
629
+ options
630
+ });
631
+ }
632
+ };
633
+ var ContactSegments = class extends Resource {
634
+ /** `POST /contacts/{id}/segments/{segmentId}` */
635
+ add(contactId, segmentId, options) {
636
+ return this.core.request("post", "/contacts/{id}/segments/{segmentId}", {
637
+ path: { id: contactId, segmentId },
638
+ options
639
+ });
640
+ }
641
+ /** `DELETE /contacts/{id}/segments/{segmentId}` */
642
+ remove(contactId, segmentId, options) {
643
+ return this.core.request("delete", "/contacts/{id}/segments/{segmentId}", {
644
+ path: { id: contactId, segmentId },
645
+ options
646
+ });
647
+ }
648
+ };
649
+ var Contacts = class extends Resource {
650
+ batch = new ContactBatch(this.core);
651
+ topics = new ContactTopics(this.core);
652
+ segments = new ContactSegments(this.core);
653
+ /** `POST /contacts` */
654
+ create(payload, options) {
655
+ return this.core.request("post", "/contacts", { body: payload, options });
656
+ }
657
+ /** `GET /contacts` */
658
+ list(params, options) {
659
+ return this.core.request("get", "/contacts", { query: params, options });
660
+ }
661
+ /** Every contact, fetched page by page. */
662
+ listAll(params, options) {
663
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
664
+ }
665
+ /** `GET /contacts/{id}`: `id` is the contact id or its email address. */
666
+ get(id, options) {
667
+ return this.core.request("get", "/contacts/{id}", { path: { id }, options });
668
+ }
669
+ /** `PATCH /contacts/{id}` */
670
+ update(id, payload, options) {
671
+ return this.core.request("patch", "/contacts/{id}", { path: { id }, body: payload, options });
672
+ }
673
+ /** `DELETE /contacts/{id}` */
674
+ delete(id, params, options) {
675
+ return this.core.request("delete", "/contacts/{id}", { path: { id }, query: params, options });
676
+ }
677
+ /** `POST /contacts/{id}/preferences-link` */
678
+ preferencesLink(id, options) {
679
+ return this.core.request("post", "/contacts/{id}/preferences-link", { path: { id }, options });
680
+ }
681
+ };
682
+ var AudienceContacts = class extends Resource {
683
+ /** `POST /audiences/{audienceId}/contacts` */
684
+ create(audienceId, payload, options) {
685
+ return this.core.request("post", "/audiences/{audienceId}/contacts", {
686
+ path: { audienceId },
687
+ body: payload,
688
+ options
689
+ });
690
+ }
691
+ /** `GET /audiences/{audienceId}/contacts/{id}` */
692
+ get(audienceId, id, options) {
693
+ return this.core.request("get", "/audiences/{audienceId}/contacts/{id}", {
694
+ path: { audienceId, id },
695
+ options
696
+ });
697
+ }
698
+ /** `PATCH /audiences/{audienceId}/contacts/{id}` */
699
+ update(audienceId, id, payload, options) {
700
+ return this.core.request("patch", "/audiences/{audienceId}/contacts/{id}", {
701
+ path: { audienceId, id },
702
+ body: payload,
703
+ options
704
+ });
705
+ }
706
+ /** `DELETE /audiences/{audienceId}/contacts/{id}` */
707
+ delete(audienceId, id, params, options) {
708
+ return this.core.request("delete", "/audiences/{audienceId}/contacts/{id}", {
709
+ path: { audienceId, id },
710
+ query: params,
711
+ options
712
+ });
713
+ }
714
+ };
715
+ var Audiences = class extends Resource {
716
+ contacts = new AudienceContacts(this.core);
717
+ };
718
+ var ContactProperties = class extends Resource {
719
+ /** `POST /contact-properties` */
720
+ create(payload, options) {
721
+ return this.core.request("post", "/contact-properties", { body: payload, options });
722
+ }
723
+ /** `GET /contact-properties` */
724
+ list(params, options) {
725
+ return this.core.request("get", "/contact-properties", { query: params, options });
726
+ }
727
+ /** Every contact property, fetched page by page. */
728
+ listAll(params, options) {
729
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
730
+ }
731
+ /** `GET /contact-properties/{id}` */
732
+ get(id, options) {
733
+ return this.core.request("get", "/contact-properties/{id}", { path: { id }, options });
734
+ }
735
+ /** `PATCH /contact-properties/{id}` */
736
+ update(id, payload, options) {
737
+ return this.core.request("patch", "/contact-properties/{id}", { path: { id }, body: payload, options });
738
+ }
739
+ /** `DELETE /contact-properties/{id}` */
740
+ delete(id, options) {
741
+ return this.core.request("delete", "/contact-properties/{id}", { path: { id }, options });
742
+ }
743
+ };
744
+ var SegmentContacts = class extends Resource {
745
+ /** `GET /segments/{id}/contacts` */
746
+ list(segmentId, params, options) {
747
+ return this.core.request("get", "/segments/{id}/contacts", {
748
+ path: { id: segmentId },
749
+ query: params,
750
+ options
751
+ });
752
+ }
753
+ /** Every contact the segment resolves to, fetched page by page. */
754
+ listAll(segmentId, params, options) {
755
+ return paginate((cursor) => this.list(segmentId, { ...params, ...cursor }, options), params);
756
+ }
757
+ };
758
+ var Segments = class extends Resource {
759
+ contacts = new SegmentContacts(this.core);
760
+ /** `POST /segments` */
761
+ create(payload, options) {
762
+ return this.core.request("post", "/segments", { body: payload, options });
763
+ }
764
+ /** `GET /segments` */
765
+ list(params, options) {
766
+ return this.core.request("get", "/segments", { query: params, options });
767
+ }
768
+ /** Every segment, fetched page by page. */
769
+ listAll(params, options) {
770
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
771
+ }
772
+ /** `GET /segments/{id}` */
773
+ get(id, options) {
774
+ return this.core.request("get", "/segments/{id}", { path: { id }, options });
775
+ }
776
+ /** `PATCH /segments/{id}` */
777
+ update(id, payload, options) {
778
+ return this.core.request("patch", "/segments/{id}", { path: { id }, body: payload, options });
779
+ }
780
+ /** `DELETE /segments/{id}` */
781
+ delete(id, options) {
782
+ return this.core.request("delete", "/segments/{id}", { path: { id }, options });
783
+ }
784
+ };
785
+ var Topics = class extends Resource {
786
+ /** `POST /topics` */
787
+ create(payload, options) {
788
+ return this.core.request("post", "/topics", { body: payload, options });
789
+ }
790
+ /** `GET /topics` (not paginated) */
791
+ list(options) {
792
+ return this.core.request("get", "/topics", { options });
793
+ }
794
+ /** `GET /topics/{id}` */
795
+ get(id, options) {
796
+ return this.core.request("get", "/topics/{id}", { path: { id }, options });
797
+ }
798
+ /** `PATCH /topics/{id}` */
799
+ update(id, payload, options) {
800
+ return this.core.request("patch", "/topics/{id}", { path: { id }, body: payload, options });
801
+ }
802
+ /** `DELETE /topics/{id}` */
803
+ delete(id, options) {
804
+ return this.core.request("delete", "/topics/{id}", { path: { id }, options });
805
+ }
806
+ };
807
+
808
+ // src/resources/emails.ts
809
+ var ReceivedEmailAttachments = class extends Resource {
810
+ /** `GET /emails/receiving/{email_id}/attachments` */
811
+ list(emailId, params, options) {
812
+ return this.core.request("get", "/emails/receiving/{email_id}/attachments", {
813
+ path: { email_id: emailId },
814
+ query: params,
815
+ options
816
+ });
817
+ }
818
+ /** Every attachment of a received email, fetched page by page. */
819
+ listAll(emailId, params, options) {
820
+ return paginate((cursor) => this.list(emailId, { ...params, ...cursor }, options), params);
821
+ }
822
+ /** `GET /emails/receiving/{email_id}/attachments/{id}` */
823
+ get(emailId, id, options) {
824
+ return this.core.request("get", "/emails/receiving/{email_id}/attachments/{id}", {
825
+ path: { email_id: emailId, id },
826
+ options
827
+ });
828
+ }
829
+ /** `GET /emails/receiving/{email_id}/attachments/{id}/text` */
830
+ text(emailId, id, options) {
831
+ return this.core.request("get", "/emails/receiving/{email_id}/attachments/{id}/text", {
832
+ path: { email_id: emailId, id },
833
+ options
834
+ });
835
+ }
836
+ };
837
+ var ReceivedEmails = class extends Resource {
838
+ attachments = new ReceivedEmailAttachments(this.core);
839
+ /** `GET /emails/receiving` */
840
+ list(params, options) {
841
+ return this.core.request("get", "/emails/receiving", { query: params, options });
842
+ }
843
+ /** Every received email matching `params`, fetched page by page. */
844
+ listAll(params, options) {
845
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
846
+ }
847
+ /** `GET /emails/receiving/{id}` */
848
+ get(id, params, options) {
849
+ return this.core.request("get", "/emails/receiving/{id}", { path: { id }, query: params, options });
850
+ }
851
+ /** `DELETE /emails/receiving/{id}` */
852
+ delete(id, options) {
853
+ return this.core.request("delete", "/emails/receiving/{id}", { path: { id }, options });
854
+ }
855
+ /** `POST /emails/receiving/{id}/reply` */
856
+ reply(id, payload, options) {
857
+ return this.core.request("post", "/emails/receiving/{id}/reply", {
858
+ path: { id },
859
+ body: payload,
860
+ ...idempotent(options)
861
+ });
862
+ }
863
+ /** `POST /emails/receiving/{id}/forward` */
864
+ forward(id, payload, options) {
865
+ return this.core.request("post", "/emails/receiving/{id}/forward", {
866
+ path: { id },
867
+ body: payload,
868
+ ...idempotent(options)
869
+ });
870
+ }
871
+ };
872
+ var Emails = class extends Resource {
873
+ receiving = new ReceivedEmails(this.core);
874
+ /** `POST /emails` */
875
+ send(payload, options) {
876
+ return this.core.request("post", "/emails", { body: payload, ...idempotent(options) });
877
+ }
878
+ /**
879
+ * `POST /emails/batch`: up to 100 emails, each shaped like {@link Emails.send}'s payload.
880
+ * The API document leaves the items untyped; the endpoint validates each one as a send.
881
+ */
882
+ batch(payload, options) {
883
+ return this.core.request("post", "/emails/batch", {
884
+ body: payload,
885
+ headers: { "x-batch-validation": options?.batchValidation },
886
+ ...idempotent(options)
887
+ });
888
+ }
889
+ /** `GET /emails` */
890
+ list(params, options) {
891
+ return this.core.request("get", "/emails", { query: params, options });
892
+ }
893
+ /** Every sent email, fetched page by page. */
894
+ listAll(params, options) {
895
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
896
+ }
897
+ /** `GET /emails/{id}` */
898
+ get(id, options) {
899
+ return this.core.request("get", "/emails/{id}", { path: { id }, options });
900
+ }
901
+ /** `PATCH /emails/{id}` */
902
+ update(id, payload, options) {
903
+ return this.core.request("patch", "/emails/{id}", { path: { id }, body: payload, options });
904
+ }
905
+ /** `POST /emails/{id}/cancel` */
906
+ cancel(id, options) {
907
+ return this.core.request("post", "/emails/{id}/cancel", { path: { id }, options });
908
+ }
909
+ /** `DELETE /emails/{id}` */
910
+ delete(id, options) {
911
+ return this.core.request("delete", "/emails/{id}", { path: { id }, options });
912
+ }
913
+ /** `GET /emails/{id}/insights` */
914
+ insights(id, options) {
915
+ return this.core.request("get", "/emails/{id}/insights", { path: { id }, options });
916
+ }
917
+ /** `GET /emails/metrics` */
918
+ metrics(params, options) {
919
+ return this.core.request("get", "/emails/metrics", { query: params, options });
920
+ }
921
+ };
922
+
923
+ // src/sse.ts
924
+ var STREAM_GAP_EVENT = "stream.gap";
925
+ var LINE_BREAK = /\r\n|\r|\n/;
926
+ async function* parseEventStream(body, hooks = { onRetry() {
927
+ } }, initialId = null) {
928
+ const reader = body.getReader();
929
+ const decoder = new TextDecoder("utf-8");
930
+ let buffer = "";
931
+ let first = true;
932
+ let lastId = initialId;
933
+ let eventName = "";
934
+ let dataLines = [];
935
+ let hasData = false;
936
+ function* takeLines(final) {
937
+ while (true) {
938
+ const match = LINE_BREAK.exec(buffer);
939
+ if (!match) return;
940
+ if (!final && match[0] === "\r" && match.index === buffer.length - 1) return;
941
+ const line = buffer.slice(0, match.index);
942
+ buffer = buffer.slice(match.index + match[0].length);
943
+ yield line;
944
+ }
945
+ }
946
+ function processLine(line) {
947
+ if (line === "") {
948
+ if (!hasData) {
949
+ eventName = "";
950
+ return void 0;
951
+ }
952
+ const raw = dataLines.join("\n");
953
+ let data = raw;
954
+ try {
955
+ data = JSON.parse(raw);
956
+ } catch {
957
+ data = raw;
958
+ }
959
+ const event = { id: lastId, event: eventName || "message", data, raw };
960
+ eventName = "";
961
+ dataLines = [];
962
+ hasData = false;
963
+ return event;
964
+ }
965
+ if (line.startsWith(":")) return void 0;
966
+ const colon = line.indexOf(":");
967
+ const field = colon === -1 ? line : line.slice(0, colon);
968
+ let value = colon === -1 ? "" : line.slice(colon + 1);
969
+ if (value.startsWith(" ")) value = value.slice(1);
970
+ switch (field) {
971
+ case "event":
972
+ eventName = value;
973
+ break;
974
+ case "data":
975
+ dataLines.push(value);
976
+ hasData = true;
977
+ break;
978
+ case "id":
979
+ if (!value.includes("\0")) lastId = value;
980
+ break;
981
+ case "retry":
982
+ if (/^\d+$/.test(value)) hooks.onRetry(Number(value));
983
+ break;
984
+ }
985
+ return void 0;
986
+ }
987
+ try {
988
+ while (true) {
989
+ const { done, value } = await reader.read();
990
+ if (done) {
991
+ buffer += decoder.decode();
992
+ for (const line of takeLines(true)) {
993
+ const event = processLine(line);
994
+ if (event) yield event;
995
+ }
996
+ return;
997
+ }
998
+ buffer += decoder.decode(value, { stream: true });
999
+ if (first && buffer.length > 0) {
1000
+ if (buffer.charCodeAt(0) === 65279) buffer = buffer.slice(1);
1001
+ first = false;
1002
+ }
1003
+ for (const line of takeLines(false)) {
1004
+ const event = processLine(line);
1005
+ if (event) yield event;
1006
+ }
1007
+ }
1008
+ } finally {
1009
+ reader.releaseLock();
1010
+ }
1011
+ }
1012
+ var EventStream = class {
1013
+ #connection;
1014
+ #connect;
1015
+ #options;
1016
+ #lastEventId;
1017
+ #delayMs;
1018
+ #closed = false;
1019
+ #started = false;
1020
+ #onAbort = () => this.close();
1021
+ #endsOn;
1022
+ /**
1023
+ * @param endsOn event names after which the stream is over: one inbox's
1024
+ * stream ends with that inbox's `inbox.deleted` or `inbox.expired` (the
1025
+ * server closes it, and a reconnect would answer 404).
1026
+ */
1027
+ constructor(connection, connect, options = {}, endsOn = []) {
1028
+ this.#endsOn = new Set(endsOn);
1029
+ this.#connection = connection;
1030
+ this.#connect = connect;
1031
+ this.#options = options;
1032
+ this.#lastEventId = options.lastEventId ?? null;
1033
+ this.#delayMs = options.reconnectDelayMs ?? 1e3;
1034
+ options.signal?.addEventListener("abort", this.#onAbort, { once: true });
1035
+ }
1036
+ /** The id of the last event received: pass it as `lastEventId` to resume later. */
1037
+ get lastEventId() {
1038
+ return this.#lastEventId;
1039
+ }
1040
+ /** The response of the current connection. */
1041
+ get response() {
1042
+ return this.#connection?.response ?? null;
1043
+ }
1044
+ /** Closes the connection; a running loop ends without an error. */
1045
+ close() {
1046
+ if (this.#closed) return;
1047
+ this.#closed = true;
1048
+ this.#options.signal?.removeEventListener("abort", this.#onAbort);
1049
+ this.#connection?.close();
1050
+ this.#connection = null;
1051
+ }
1052
+ [Symbol.asyncIterator]() {
1053
+ if (this.#started) throw new TypeError("An EventStream can be iterated only once");
1054
+ this.#started = true;
1055
+ return this.#events();
1056
+ }
1057
+ async *#events() {
1058
+ const reconnect = this.#options.reconnect !== false;
1059
+ const maxReconnects = this.#options.maxReconnects ?? 5;
1060
+ let failures = 0;
1061
+ let gapAt;
1062
+ try {
1063
+ while (!this.#closed) {
1064
+ const connection = this.#connection;
1065
+ if (connection !== null && connection.response.body !== null) {
1066
+ try {
1067
+ const events = parseEventStream(
1068
+ connection.response.body,
1069
+ { onRetry: (ms) => this.#delayMs = ms },
1070
+ this.#lastEventId
1071
+ );
1072
+ for await (const event of events) {
1073
+ failures = 0;
1074
+ if (event.event === STREAM_GAP_EVENT) {
1075
+ if (gapAt === this.#lastEventId) continue;
1076
+ gapAt = this.#lastEventId;
1077
+ yield { id: null, event: STREAM_GAP_EVENT, data: event.data };
1078
+ continue;
1079
+ }
1080
+ this.#lastEventId = event.id;
1081
+ yield {
1082
+ id: event.id ?? "",
1083
+ event: event.event,
1084
+ data: event.data
1085
+ };
1086
+ if (this.#endsOn.has(event.event)) return;
1087
+ }
1088
+ } catch {
1089
+ }
1090
+ connection.close();
1091
+ this.#connection = null;
1092
+ }
1093
+ if (this.#closed || !reconnect) return;
1094
+ failures++;
1095
+ if (failures > maxReconnects) {
1096
+ throw new APIConnectionError(
1097
+ `The event stream disconnected; gave up after ${maxReconnects} reconnects`
1098
+ );
1099
+ }
1100
+ if (!await sleep(this.#delayMs, this.#options.signal) || this.#closed) return;
1101
+ const next = await this.#connect(this.#lastEventId);
1102
+ if (this.#closed) {
1103
+ next.data?.close();
1104
+ return;
1105
+ }
1106
+ if (next.error !== null) {
1107
+ if (!retryable(next.error, false)) throw next.error;
1108
+ continue;
1109
+ }
1110
+ this.#connection = next.data;
1111
+ }
1112
+ } finally {
1113
+ this.close();
1114
+ }
1115
+ }
1116
+ };
1117
+
1118
+ // src/resources/inboxes.ts
1119
+ var InboxAgentSettings = class extends Resource {
1120
+ /** `GET /inboxes/{inbox_id}/agent` */
1121
+ get(inboxId, options) {
1122
+ return this.core.request("get", "/inboxes/{inbox_id}/agent", { path: { inbox_id: inboxId }, options });
1123
+ }
1124
+ };
1125
+ var InboxSafety = class extends Resource {
1126
+ /** `GET /inboxes/{inbox_id}/safety` */
1127
+ get(inboxId, options) {
1128
+ return this.core.request("get", "/inboxes/{inbox_id}/safety", { path: { inbox_id: inboxId }, options });
1129
+ }
1130
+ /** `PATCH /inboxes/{inbox_id}/safety` */
1131
+ update(inboxId, payload, options) {
1132
+ return this.core.request("patch", "/inboxes/{inbox_id}/safety", {
1133
+ path: { inbox_id: inboxId },
1134
+ body: payload,
1135
+ options
1136
+ });
1137
+ }
1138
+ };
1139
+ var InboxLabels = class extends Resource {
1140
+ /** `GET /inboxes/{inbox_id}/labels` */
1141
+ list(inboxId, options) {
1142
+ return this.core.request("get", "/inboxes/{inbox_id}/labels", { path: { inbox_id: inboxId }, options });
1143
+ }
1144
+ /** `POST /inboxes/{inbox_id}/labels` */
1145
+ create(inboxId, payload, options) {
1146
+ return this.core.request("post", "/inboxes/{inbox_id}/labels", {
1147
+ path: { inbox_id: inboxId },
1148
+ body: payload,
1149
+ options
1150
+ });
1151
+ }
1152
+ /** `PATCH /inboxes/{inbox_id}/labels/{label_id}` */
1153
+ update(inboxId, labelId, payload, options) {
1154
+ return this.core.request("patch", "/inboxes/{inbox_id}/labels/{label_id}", {
1155
+ path: { inbox_id: inboxId, label_id: labelId },
1156
+ body: payload,
1157
+ options
1158
+ });
1159
+ }
1160
+ /** `DELETE /inboxes/{inbox_id}/labels/{label_id}` */
1161
+ delete(inboxId, labelId, options) {
1162
+ return this.core.request("delete", "/inboxes/{inbox_id}/labels/{label_id}", {
1163
+ path: { inbox_id: inboxId, label_id: labelId },
1164
+ options
1165
+ });
1166
+ }
1167
+ };
1168
+ var ThreadLabels = class extends Resource {
1169
+ /** `POST /inboxes/{inbox_id}/threads/{thread_id}/labels`: adds labels. */
1170
+ add(inboxId, threadId, payload, options) {
1171
+ return this.core.request("post", "/inboxes/{inbox_id}/threads/{thread_id}/labels", {
1172
+ path: { inbox_id: inboxId, thread_id: threadId },
1173
+ body: payload,
1174
+ options
1175
+ });
1176
+ }
1177
+ /** `PUT /inboxes/{inbox_id}/threads/{thread_id}/labels`: replaces the labels. */
1178
+ set(inboxId, threadId, payload, options) {
1179
+ return this.core.request("put", "/inboxes/{inbox_id}/threads/{thread_id}/labels", {
1180
+ path: { inbox_id: inboxId, thread_id: threadId },
1181
+ body: payload,
1182
+ options
1183
+ });
1184
+ }
1185
+ /** `DELETE /inboxes/{inbox_id}/threads/{thread_id}/labels/{label_id}` */
1186
+ remove(inboxId, threadId, labelId, options) {
1187
+ return this.core.request("delete", "/inboxes/{inbox_id}/threads/{thread_id}/labels/{label_id}", {
1188
+ path: { inbox_id: inboxId, thread_id: threadId, label_id: labelId },
1189
+ options
1190
+ });
1191
+ }
1192
+ };
1193
+ var ThreadEmails = class extends Resource {
1194
+ /** `GET /inboxes/{inbox_id}/threads/{thread_id}/emails` */
1195
+ list(inboxId, threadId, params, options) {
1196
+ return this.core.request("get", "/inboxes/{inbox_id}/threads/{thread_id}/emails", {
1197
+ path: { inbox_id: inboxId, thread_id: threadId },
1198
+ query: params,
1199
+ options
1200
+ });
1201
+ }
1202
+ /** Every email of a thread, fetched page by page. */
1203
+ listAll(inboxId, threadId, params, options) {
1204
+ return paginate((cursor) => this.list(inboxId, threadId, { ...params, ...cursor }, options), params);
1205
+ }
1206
+ /** `GET /inboxes/{inbox_id}/threads/{thread_id}/emails/{email_id}` */
1207
+ get(inboxId, threadId, emailId, params, options) {
1208
+ return this.core.request("get", "/inboxes/{inbox_id}/threads/{thread_id}/emails/{email_id}", {
1209
+ path: { inbox_id: inboxId, thread_id: threadId, email_id: emailId },
1210
+ query: params,
1211
+ options
1212
+ });
1213
+ }
1214
+ /** `POST .../emails/{email_id}/reply`: answers the sent email, or (202) the draft the inbox's rules held. */
1215
+ reply(inboxId, threadId, emailId, payload, options) {
1216
+ return this.core.request("post", "/inboxes/{inbox_id}/threads/{thread_id}/emails/{email_id}/reply", {
1217
+ path: { inbox_id: inboxId, thread_id: threadId, email_id: emailId },
1218
+ body: payload,
1219
+ ...idempotent(options)
1220
+ });
1221
+ }
1222
+ /** `POST .../emails/{email_id}/forward`: answers the sent email, or (202) the draft the inbox's rules held. */
1223
+ forward(inboxId, threadId, emailId, payload, options) {
1224
+ return this.core.request("post", "/inboxes/{inbox_id}/threads/{thread_id}/emails/{email_id}/forward", {
1225
+ path: { inbox_id: inboxId, thread_id: threadId, email_id: emailId },
1226
+ body: payload,
1227
+ ...idempotent(options)
1228
+ });
1229
+ }
1230
+ };
1231
+ var InboxThreads = class extends Resource {
1232
+ labels = new ThreadLabels(this.core);
1233
+ emails = new ThreadEmails(this.core);
1234
+ /** `GET /inboxes/{inbox_id}/threads` */
1235
+ list(inboxId, params, options) {
1236
+ return this.core.request("get", "/inboxes/{inbox_id}/threads", {
1237
+ path: { inbox_id: inboxId },
1238
+ query: params,
1239
+ options
1240
+ });
1241
+ }
1242
+ /** Every thread matching `params`, fetched page by page. */
1243
+ listAll(inboxId, params, options) {
1244
+ return paginate((cursor) => this.list(inboxId, { ...params, ...cursor }, options), params);
1245
+ }
1246
+ /** `GET /inboxes/{inbox_id}/threads/search` */
1247
+ search(inboxId, params, options) {
1248
+ return this.core.request("get", "/inboxes/{inbox_id}/threads/search", {
1249
+ path: { inbox_id: inboxId },
1250
+ query: params,
1251
+ options
1252
+ });
1253
+ }
1254
+ /** Every thread a search finds, fetched page by page. */
1255
+ searchAll(inboxId, params, options) {
1256
+ return paginate((cursor) => this.search(inboxId, { ...params, ...cursor }, options), params);
1257
+ }
1258
+ /** `GET /inboxes/{inbox_id}/threads/{thread_id}` */
1259
+ get(inboxId, threadId, options) {
1260
+ return this.core.request("get", "/inboxes/{inbox_id}/threads/{thread_id}", {
1261
+ path: { inbox_id: inboxId, thread_id: threadId },
1262
+ options
1263
+ });
1264
+ }
1265
+ /** `PATCH /inboxes/{inbox_id}/threads/{thread_id}` */
1266
+ update(inboxId, threadId, payload, options) {
1267
+ return this.core.request("patch", "/inboxes/{inbox_id}/threads/{thread_id}", {
1268
+ path: { inbox_id: inboxId, thread_id: threadId },
1269
+ body: payload,
1270
+ options
1271
+ });
1272
+ }
1273
+ /** `DELETE /inboxes/{inbox_id}/threads/{thread_id}` */
1274
+ delete(inboxId, threadId, options) {
1275
+ return this.core.request("delete", "/inboxes/{inbox_id}/threads/{thread_id}", {
1276
+ path: { inbox_id: inboxId, thread_id: threadId },
1277
+ options
1278
+ });
1279
+ }
1280
+ };
1281
+ var InboxQuarantine = class extends Resource {
1282
+ /** `GET /inboxes/{inbox_id}/quarantine` */
1283
+ list(inboxId, params, options) {
1284
+ return this.core.request("get", "/inboxes/{inbox_id}/quarantine", {
1285
+ path: { inbox_id: inboxId },
1286
+ query: params,
1287
+ options
1288
+ });
1289
+ }
1290
+ /** Every held email of an inbox, fetched page by page. */
1291
+ listAll(inboxId, params, options) {
1292
+ return paginate((cursor) => this.list(inboxId, { ...params, ...cursor }, options), params);
1293
+ }
1294
+ /** `POST /inboxes/{inbox_id}/quarantine/{email_id}/release` (the body is optional) */
1295
+ release(inboxId, emailId, payload, options) {
1296
+ return this.core.request("post", "/inboxes/{inbox_id}/quarantine/{email_id}/release", {
1297
+ path: { inbox_id: inboxId, email_id: emailId },
1298
+ body: payload,
1299
+ options
1300
+ });
1301
+ }
1302
+ };
1303
+ var InboxCodes = class extends Resource {
1304
+ /** `GET /inboxes/{inbox_id}/codes/latest`: the newest verification code, optionally waiting for one. */
1305
+ latest(inboxId, params, options) {
1306
+ return this.core.request("get", "/inboxes/{inbox_id}/codes/latest", {
1307
+ path: { inbox_id: inboxId },
1308
+ query: params,
1309
+ options
1310
+ });
1311
+ }
1312
+ };
1313
+ var InboxDrafts = class extends Resource {
1314
+ /** `POST /inboxes/{inbox_id}/drafts` */
1315
+ create(inboxId, payload, options) {
1316
+ return this.core.request("post", "/inboxes/{inbox_id}/drafts", {
1317
+ path: { inbox_id: inboxId },
1318
+ body: payload,
1319
+ options
1320
+ });
1321
+ }
1322
+ /** `GET /inboxes/{inbox_id}/drafts` */
1323
+ list(inboxId, params, options) {
1324
+ return this.core.request("get", "/inboxes/{inbox_id}/drafts", {
1325
+ path: { inbox_id: inboxId },
1326
+ query: params,
1327
+ options
1328
+ });
1329
+ }
1330
+ /** Every draft of an inbox, fetched page by page. */
1331
+ listAll(inboxId, params, options) {
1332
+ return paginate((cursor) => this.list(inboxId, { ...params, ...cursor }, options), params);
1333
+ }
1334
+ /** `GET /inboxes/{inbox_id}/drafts/{draft_id}` */
1335
+ get(inboxId, draftId, options) {
1336
+ return this.core.request("get", "/inboxes/{inbox_id}/drafts/{draft_id}", {
1337
+ path: { inbox_id: inboxId, draft_id: draftId },
1338
+ options
1339
+ });
1340
+ }
1341
+ /** `PATCH /inboxes/{inbox_id}/drafts/{draft_id}` */
1342
+ update(inboxId, draftId, payload, options) {
1343
+ return this.core.request("patch", "/inboxes/{inbox_id}/drafts/{draft_id}", {
1344
+ path: { inbox_id: inboxId, draft_id: draftId },
1345
+ body: payload,
1346
+ options
1347
+ });
1348
+ }
1349
+ /** `DELETE /inboxes/{inbox_id}/drafts/{draft_id}` */
1350
+ delete(inboxId, draftId, options) {
1351
+ return this.core.request("delete", "/inboxes/{inbox_id}/drafts/{draft_id}", {
1352
+ path: { inbox_id: inboxId, draft_id: draftId },
1353
+ options
1354
+ });
1355
+ }
1356
+ /** `POST /inboxes/{inbox_id}/drafts/{draft_id}/send` */
1357
+ send(inboxId, draftId, options) {
1358
+ return this.core.request("post", "/inboxes/{inbox_id}/drafts/{draft_id}/send", {
1359
+ path: { inbox_id: inboxId, draft_id: draftId },
1360
+ ...idempotent(options)
1361
+ });
1362
+ }
1363
+ /** `POST /inboxes/{inbox_id}/drafts/{draft_id}/reject` */
1364
+ reject(inboxId, draftId, options) {
1365
+ return this.core.request("post", "/inboxes/{inbox_id}/drafts/{draft_id}/reject", {
1366
+ path: { inbox_id: inboxId, draft_id: draftId },
1367
+ options
1368
+ });
1369
+ }
1370
+ };
1371
+ function lastEventIdHeader(id) {
1372
+ return { "last-event-id": id ?? void 0 };
1373
+ }
1374
+ function connectOptions(options, retries) {
1375
+ return {
1376
+ signal: options.signal,
1377
+ headers: options.headers,
1378
+ timeoutMs: options.timeoutMs,
1379
+ maxRetries: retries
1380
+ };
1381
+ }
1382
+ var INBOX_GONE_EVENTS = ["inbox.deleted", "inbox.expired"];
1383
+ function wrap(first, connect, options, endsOn = []) {
1384
+ if (first.error !== null) return first;
1385
+ return { data: new EventStream(first.data, connect, options, endsOn), error: null, headers: first.headers };
1386
+ }
1387
+ var InboxEvents = class extends Resource {
1388
+ /**
1389
+ * `GET /inboxes/events`: every inbox event of the team as a live stream.
1390
+ * Resolves once the stream is open (or with the error that refused it).
1391
+ */
1392
+ async stream(params, options = {}) {
1393
+ const connect = (lastEventId) => this.core.openStream("get", "/inboxes/events", {
1394
+ query: params,
1395
+ headers: lastEventIdHeader(lastEventId),
1396
+ options: connectOptions(options, 0)
1397
+ });
1398
+ const first = await this.core.openStream("get", "/inboxes/events", {
1399
+ query: params,
1400
+ headers: lastEventIdHeader(options.lastEventId),
1401
+ options: connectOptions(options, options.maxRetries)
1402
+ });
1403
+ return wrap(first, connect, options);
1404
+ }
1405
+ /**
1406
+ * `GET /inboxes/{inbox_id}/events`: one inbox's events as a live stream. It ends
1407
+ * (the loop finishes) after that inbox's `inbox.deleted` or `inbox.expired`.
1408
+ */
1409
+ async streamInbox(inboxId, params, options = {}) {
1410
+ const connect = (lastEventId) => this.core.openStream("get", "/inboxes/{inbox_id}/events", {
1411
+ path: { inbox_id: inboxId },
1412
+ query: params,
1413
+ headers: lastEventIdHeader(lastEventId),
1414
+ options: connectOptions(options, 0)
1415
+ });
1416
+ const first = await this.core.openStream("get", "/inboxes/{inbox_id}/events", {
1417
+ path: { inbox_id: inboxId },
1418
+ query: params,
1419
+ headers: lastEventIdHeader(options.lastEventId),
1420
+ options: connectOptions(options, options.maxRetries)
1421
+ });
1422
+ return wrap(first, connect, options, INBOX_GONE_EVENTS);
1423
+ }
1424
+ };
1425
+ var Inboxes = class extends Resource {
1426
+ agent = new InboxAgentSettings(this.core);
1427
+ safety = new InboxSafety(this.core);
1428
+ labels = new InboxLabels(this.core);
1429
+ threads = new InboxThreads(this.core);
1430
+ quarantine = new InboxQuarantine(this.core);
1431
+ codes = new InboxCodes(this.core);
1432
+ drafts = new InboxDrafts(this.core);
1433
+ events = new InboxEvents(this.core);
1434
+ /** `POST /inboxes` */
1435
+ create(payload, options) {
1436
+ return this.core.request("post", "/inboxes", { body: payload, options });
1437
+ }
1438
+ /** `GET /inboxes` */
1439
+ list(params, options) {
1440
+ return this.core.request("get", "/inboxes", { query: params, options });
1441
+ }
1442
+ /** Every inbox, fetched page by page. */
1443
+ listAll(params, options) {
1444
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
1445
+ }
1446
+ /** `GET /inboxes/{inbox_id}`: `inboxId` is the inbox id or its email address. */
1447
+ get(inboxId, options) {
1448
+ return this.core.request("get", "/inboxes/{inbox_id}", { path: { inbox_id: inboxId }, options });
1449
+ }
1450
+ /** `PATCH /inboxes/{inbox_id}` */
1451
+ update(inboxId, payload, options) {
1452
+ return this.core.request("patch", "/inboxes/{inbox_id}", {
1453
+ path: { inbox_id: inboxId },
1454
+ body: payload,
1455
+ options
1456
+ });
1457
+ }
1458
+ /** `DELETE /inboxes/{inbox_id}` */
1459
+ delete(inboxId, options) {
1460
+ return this.core.request("delete", "/inboxes/{inbox_id}", { path: { inbox_id: inboxId }, options });
1461
+ }
1462
+ /** `POST /inboxes/{inbox_id}/emails`: starts a conversation; answers the sent email or (202) a held draft. */
1463
+ send(inboxId, payload, options) {
1464
+ return this.core.request("post", "/inboxes/{inbox_id}/emails", {
1465
+ path: { inbox_id: inboxId },
1466
+ body: payload,
1467
+ ...idempotent(options)
1468
+ });
1469
+ }
1470
+ };
1471
+
1472
+ // src/resources/lists.ts
1473
+ var SuppressionBatch = class extends Resource {
1474
+ /** `POST /suppressions/batch/add` */
1475
+ add(payload, options) {
1476
+ return this.core.request("post", "/suppressions/batch/add", { body: payload, options });
1477
+ }
1478
+ /** `POST /suppressions/batch/remove` */
1479
+ remove(payload, options) {
1480
+ return this.core.request("post", "/suppressions/batch/remove", { body: payload, options });
1481
+ }
1482
+ };
1483
+ var Suppressions = class extends Resource {
1484
+ batch = new SuppressionBatch(this.core);
1485
+ /** `POST /suppressions` */
1486
+ create(payload, options) {
1487
+ return this.core.request("post", "/suppressions", { body: payload, options });
1488
+ }
1489
+ /** `GET /suppressions` */
1490
+ list(params, options) {
1491
+ return this.core.request("get", "/suppressions", { query: params, options });
1492
+ }
1493
+ /** Every suppression, fetched page by page. */
1494
+ listAll(params, options) {
1495
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
1496
+ }
1497
+ /** `GET /suppressions/{id}` */
1498
+ get(id, options) {
1499
+ return this.core.request("get", "/suppressions/{id}", { path: { id }, options });
1500
+ }
1501
+ /** `DELETE /suppressions/{id}` */
1502
+ delete(id, options) {
1503
+ return this.core.request("delete", "/suppressions/{id}", { path: { id }, options });
1504
+ }
1505
+ };
1506
+ var Unsubscribes = class extends Resource {
1507
+ /** `POST /unsubscribes` */
1508
+ create(payload, options) {
1509
+ return this.core.request("post", "/unsubscribes", { body: payload, options });
1510
+ }
1511
+ /** `GET /unsubscribes` */
1512
+ list(params, options) {
1513
+ return this.core.request("get", "/unsubscribes", { query: params, options });
1514
+ }
1515
+ /** Every opt-out, fetched page by page. */
1516
+ listAll(params, options) {
1517
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
1518
+ }
1519
+ /** `DELETE /unsubscribes/{id}` */
1520
+ delete(id, options) {
1521
+ return this.core.request("delete", "/unsubscribes/{id}", { path: { id }, options });
1522
+ }
1523
+ };
1524
+ var Verifications = class extends Resource {
1525
+ /** `GET /verifications/availability` */
1526
+ availability(options) {
1527
+ return this.core.request("get", "/verifications/availability", { options });
1528
+ }
1529
+ /** `POST /verifications/estimate` */
1530
+ estimate(payload, options) {
1531
+ return this.core.request("post", "/verifications/estimate", { body: payload, options });
1532
+ }
1533
+ /** `POST /verifications`: starts a verification run. */
1534
+ create(payload, options) {
1535
+ return this.core.request("post", "/verifications", { body: payload, options });
1536
+ }
1537
+ /** `GET /verifications` */
1538
+ list(params, options) {
1539
+ return this.core.request("get", "/verifications", { query: params, options });
1540
+ }
1541
+ /** Every verification run, fetched page by page. */
1542
+ listAll(params, options) {
1543
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
1544
+ }
1545
+ /** `GET /verifications/{id}` */
1546
+ get(id, options) {
1547
+ return this.core.request("get", "/verifications/{id}", { path: { id }, options });
1548
+ }
1549
+ };
1550
+
1551
+ // src/client.ts
1552
+ var BillionSend = class {
1553
+ emails;
1554
+ domains;
1555
+ apiKeys;
1556
+ contacts;
1557
+ audiences;
1558
+ contactProperties;
1559
+ segments;
1560
+ topics;
1561
+ broadcasts;
1562
+ templates;
1563
+ webhooks;
1564
+ suppressions;
1565
+ unsubscribes;
1566
+ verifications;
1567
+ usage;
1568
+ deliverability;
1569
+ inboxes;
1570
+ agent;
1571
+ #core;
1572
+ /**
1573
+ * @param apiKeyOrOptions An API key (`bs_...`), or options. Without a key the
1574
+ * client reads `BILLIONSEND_API_KEY`; only `agent.signup` works with no key at all.
1575
+ */
1576
+ constructor(apiKeyOrOptions) {
1577
+ const options = typeof apiKeyOrOptions === "string" ? { apiKey: apiKeyOrOptions } : { ...apiKeyOrOptions };
1578
+ const core = new Core(options);
1579
+ this.#core = core;
1580
+ this.emails = new Emails(core);
1581
+ this.domains = new Domains(core);
1582
+ this.apiKeys = new ApiKeys(core);
1583
+ this.contacts = new Contacts(core);
1584
+ this.audiences = new Audiences(core);
1585
+ this.contactProperties = new ContactProperties(core);
1586
+ this.segments = new Segments(core);
1587
+ this.topics = new Topics(core);
1588
+ this.broadcasts = new Broadcasts(core);
1589
+ this.templates = new Templates(core);
1590
+ this.webhooks = new Webhooks(core);
1591
+ this.suppressions = new Suppressions(core);
1592
+ this.unsubscribes = new Unsubscribes(core);
1593
+ this.verifications = new Verifications(core);
1594
+ this.usage = new Usage(core);
1595
+ this.deliverability = new Deliverability(core);
1596
+ this.inboxes = new Inboxes(core);
1597
+ this.agent = new Agent(core);
1598
+ }
1599
+ /** The API base URL this client calls. */
1600
+ get baseUrl() {
1601
+ return this.#core.baseUrl;
1602
+ }
1603
+ };
1604
+
1605
+ // src/webhooks.ts
1606
+ var WEBHOOK_TOLERANCE_SECONDS = 300;
1607
+ var SECRET_PREFIX = "whsec_";
1608
+ var SECRET_MIN_BYTES = 24;
1609
+ var SECRET_MAX_BYTES = 64;
1610
+ function header(headers, name) {
1611
+ if (typeof headers.get === "function" && typeof headers.forEach === "function") {
1612
+ return headers.get(name) ?? void 0;
1613
+ }
1614
+ for (const [key, value] of Object.entries(headers)) {
1615
+ if (key.toLowerCase() !== name) continue;
1616
+ return Array.isArray(value) ? value[0] : value;
1617
+ }
1618
+ return void 0;
1619
+ }
1620
+ function decodeBase64(text) {
1621
+ try {
1622
+ const binary = atob(text);
1623
+ return Uint8Array.from(binary, (c) => c.charCodeAt(0));
1624
+ } catch {
1625
+ return null;
1626
+ }
1627
+ }
1628
+ function encodeBase64(bytes) {
1629
+ let binary = "";
1630
+ for (const byte of bytes) binary += String.fromCharCode(byte);
1631
+ return btoa(binary);
1632
+ }
1633
+ function secretKey(secret) {
1634
+ const encoded = secret.startsWith(SECRET_PREFIX) ? secret.slice(SECRET_PREFIX.length) : null;
1635
+ const key = encoded === null ? null : decodeBase64(encoded);
1636
+ if (encoded === null || key === null || key.length < SECRET_MIN_BYTES || key.length > SECRET_MAX_BYTES || encodeBase64(key) !== encoded) {
1637
+ throw new WebhookVerificationError("The webhook secret is not a whsec_ secret");
1638
+ }
1639
+ return key;
1640
+ }
1641
+ async function subtleCrypto() {
1642
+ const subtle = globalThis.crypto?.subtle;
1643
+ if (subtle) return subtle;
1644
+ const nodeCrypto = await import('crypto');
1645
+ return nodeCrypto.webcrypto.subtle;
1646
+ }
1647
+ function bytesOf(payload) {
1648
+ if (typeof payload === "string") return new TextEncoder().encode(payload);
1649
+ return payload instanceof Uint8Array ? payload : new Uint8Array(payload);
1650
+ }
1651
+ function equal(a, b) {
1652
+ if (a.length !== b.length) return false;
1653
+ let diff = 0;
1654
+ for (let i = 0; i < a.length; i++) diff |= (a[i] ?? 0) ^ (b[i] ?? 0);
1655
+ return diff === 0;
1656
+ }
1657
+ async function verifyWebhook(payload, headers, secret, options = {}) {
1658
+ const id = header(headers, "webhook-id");
1659
+ const timestamp = header(headers, "webhook-timestamp");
1660
+ const signature = header(headers, "webhook-signature");
1661
+ if (!id || !timestamp || !signature) {
1662
+ throw new WebhookVerificationError(
1663
+ "Missing the webhook-id, webhook-timestamp or webhook-signature header"
1664
+ );
1665
+ }
1666
+ if (!/^\d+$/.test(timestamp)) throw new WebhookVerificationError("Invalid webhook-timestamp header");
1667
+ const tolerance = options.tolerance ?? WEBHOOK_TOLERANCE_SECONDS;
1668
+ const now = Math.floor((options.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
1669
+ const seconds = Number(timestamp);
1670
+ if (now - seconds > tolerance) throw new WebhookVerificationError("The webhook timestamp is too old");
1671
+ if (seconds - now > tolerance) throw new WebhookVerificationError("The webhook timestamp is too new");
1672
+ const body = bytesOf(payload);
1673
+ const subtle = await subtleCrypto();
1674
+ const key = await subtle.importKey("raw", secretKey(secret), { name: "HMAC", hash: "SHA-256" }, false, [
1675
+ "sign"
1676
+ ]);
1677
+ const prefix = new TextEncoder().encode(`${id}.${timestamp}.`);
1678
+ const signed = new Uint8Array(prefix.length + body.length);
1679
+ signed.set(prefix);
1680
+ signed.set(body, prefix.length);
1681
+ const expected = new Uint8Array(await subtle.sign("HMAC", key, signed));
1682
+ const matched = signature.split(" ").some((candidate) => {
1683
+ const comma = candidate.indexOf(",");
1684
+ if (comma === -1 || candidate.slice(0, comma) !== "v1") return false;
1685
+ const given = decodeBase64(candidate.slice(comma + 1));
1686
+ return given !== null && equal(given, expected);
1687
+ });
1688
+ if (!matched) throw new WebhookVerificationError("No webhook signature matches");
1689
+ try {
1690
+ return JSON.parse(new TextDecoder().decode(body));
1691
+ } catch {
1692
+ throw new WebhookVerificationError("The webhook body is not JSON");
1693
+ }
1694
+ }
1695
+
1696
+ export { APIConnectionError, APIError, APITimeoutError, AuthenticationError, BillionSend, BillionSendError, ConflictError, DEFAULT_BASE_URL, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT_MS, EventStream, NotFoundError, PermissionDeniedError, RateLimitError, STREAM_GAP_EVENT, VERSION, ValidationError, WEBHOOK_TOLERANCE_SECONDS, WebhookVerificationError, paginate, verifyWebhook };
1697
+ //# sourceMappingURL=index.js.map
1698
+ //# sourceMappingURL=index.js.map