delivrie 0.1.1 → 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/README.md CHANGED
@@ -33,6 +33,19 @@ const Delivrie = require("delivrie");
33
33
  const delivrie = new Delivrie("dlv_...");
34
34
  ```
35
35
 
36
+ ## React Email
37
+
38
+ Pass a [React Email](https://react.email) component and the SDK renders it to HTML and text (install `@react-email/render` alongside React Email):
39
+
40
+ ```tsx
41
+ await delivrie.emails.send({
42
+ from: "Acme <hello@mail.acme.com>",
43
+ to: "ada@example.com",
44
+ subject: "Welcome",
45
+ react: <Welcome name="Ada" />,
46
+ });
47
+ ```
48
+
36
49
  ## Results and errors
37
50
 
38
51
  Every call resolves to `{ data, error }`, and exactly one of them is `null`. API errors never throw, so you don't need `try`/`catch`:
@@ -1,8 +1,41 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
36
  exports.Delivrie = exports.VERSION = void 0;
4
37
  const webhooks_js_1 = require("./webhooks.cjs");
5
- exports.VERSION = "0.1.1";
38
+ exports.VERSION = "0.2.0";
6
39
  const DEFAULT_BASE_URL = "https://delivrie.io/api";
7
40
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
8
41
  const enc = encodeURIComponent;
@@ -12,6 +45,39 @@ function toBase64(bytes) {
12
45
  s += String.fromCharCode.apply(null, Array.from(bytes.subarray(i, i + 0x8000)));
13
46
  return btoa(s);
14
47
  }
48
+ // React Email: render a component to HTML and text with @react-email/render, which the app installs alongside
49
+ // React Email (it's an optional peer dependency, so the SDK itself stays dependency-free). The specifier is
50
+ // left for the runtime to resolve, so bundlers don't fail for apps that never send React components.
51
+ async function renderReact(node) {
52
+ let mod;
53
+ try {
54
+ const specifier = "@react-email/render";
55
+ mod = await Promise.resolve(`${specifier}`).then(s => __importStar(require(s)));
56
+ }
57
+ catch {
58
+ throw new ReactRenderError("To send React Email components, install @react-email/render: npm install @react-email/render");
59
+ }
60
+ try {
61
+ return { html: await mod.render(node), text: await mod.render(node, { plainText: true }) };
62
+ }
63
+ catch (e) {
64
+ throw new ReactRenderError(`Couldn't render the React component: ${e?.message || e}`);
65
+ }
66
+ }
67
+ class ReactRenderError extends Error {
68
+ }
69
+ async function prepareEmail(e) {
70
+ const out = normalizeEmail(e);
71
+ if (e.react !== undefined && e.react !== null) {
72
+ const { html, text } = await renderReact(e.react);
73
+ if (out.html === undefined)
74
+ out.html = html;
75
+ if (out.text === undefined)
76
+ out.text = text;
77
+ }
78
+ delete out.react;
79
+ return out;
80
+ }
15
81
  function normalizeEmail(e) {
16
82
  const { replyTo, scheduledAt, attachments, ...rest } = e;
17
83
  const out = { ...rest };
@@ -38,9 +104,27 @@ class Delivrie {
38
104
  // ---------------------------------------------------------------- resources
39
105
  this.emails = {
40
106
  /** Send one email. Returns its id straight away; delivery events arrive through webhooks. */
41
- send: (email, opts) => this.request("POST", "/emails", normalizeEmail(email), opts),
107
+ send: async (email, opts) => {
108
+ try {
109
+ return await this.request("POST", "/emails", await prepareEmail(email), opts);
110
+ }
111
+ catch (e) {
112
+ if (e instanceof ReactRenderError)
113
+ return renderFailure(e);
114
+ throw e;
115
+ }
116
+ },
42
117
  /** Send up to 100 emails in one request (no attachments or scheduling). */
43
- batch: (emails, opts) => this.request("POST", "/emails/batch", emails.map(normalizeEmail), opts),
118
+ batch: async (emails, opts) => {
119
+ try {
120
+ return await this.request("POST", "/emails/batch", await Promise.all(emails.map(prepareEmail)), opts);
121
+ }
122
+ catch (e) {
123
+ if (e instanceof ReactRenderError)
124
+ return renderFailure(e);
125
+ throw e;
126
+ }
127
+ },
44
128
  get: (id) => this.request("GET", `/emails/${enc(id)}`),
45
129
  list: (params = {}) => this.request("GET", "/emails", undefined, { query: { ...params } }),
46
130
  /** Received (inbound) emails. */
@@ -230,6 +314,9 @@ class Delivrie {
230
314
  }
231
315
  }
232
316
  exports.Delivrie = Delivrie;
317
+ function renderFailure(e) {
318
+ return { data: null, error: { statusCode: 0, name: "react_render_error", message: e.message } };
319
+ }
233
320
  function backoff(attempt) {
234
321
  return Math.min(8000, 500 * 2 ** attempt) + Math.floor(Math.random() * 250);
235
322
  }
@@ -1,6 +1,6 @@
1
1
  import type { ApiKey, Automation, Broadcast, Contact, CreateApiKeyRequest, CreateApiKeyResponse, CreateBroadcastRequest, CreateContactRequest, CreateDomainRequest, CreateEmailResponse, CreateTemplateRequest, CreateWebhookRequest, CreateWebhookResponse, Domain, Email, EmailSummary, ForwardEmailRequest, InboxThread, List, ListContactsParams, ListEmailsParams, Log, LogSummary, Metrics, Pagination, ReplyToThreadRequest, RequestOptions, Result, Segment, SendEmailRequest, SendEventRequest, Suppression, Template, Topic, UpdateContactRequest, UpdateDomainRequest, Usage, Webhook, WebhookDelivery, Deleted, BroadcastRecipientCount } from "./types.cjs";
2
2
  import { type VerifyWebhookOptions } from "./webhooks.cjs";
3
- export declare const VERSION = "0.1.1";
3
+ export declare const VERSION = "0.2.0";
4
4
  export interface DelivrieOptions {
5
5
  /** Defaults to `https://delivrie.io/api`. */
6
6
  baseUrl?: string;
@@ -58,6 +58,11 @@ export interface SendEmailRequest {
58
58
  html?: string;
59
59
  /** Generated from `html` when omitted. */
60
60
  text?: string;
61
+ /**
62
+ * A React Email component, like `<Welcome name="Ada" />`. The SDK renders it to `html` and `text` with
63
+ * `@react-email/render`, which you install alongside React Email. Ignored if you also pass `html`.
64
+ */
65
+ react?: unknown;
61
66
  cc?: string | string[];
62
67
  bcc?: string | string[];
63
68
  reply_to?: string | string[];
@@ -1,6 +1,6 @@
1
1
  import type { ApiKey, Automation, Broadcast, Contact, CreateApiKeyRequest, CreateApiKeyResponse, CreateBroadcastRequest, CreateContactRequest, CreateDomainRequest, CreateEmailResponse, CreateTemplateRequest, CreateWebhookRequest, CreateWebhookResponse, Domain, Email, EmailSummary, ForwardEmailRequest, InboxThread, List, ListContactsParams, ListEmailsParams, Log, LogSummary, Metrics, Pagination, ReplyToThreadRequest, RequestOptions, Result, Segment, SendEmailRequest, SendEventRequest, Suppression, Template, Topic, UpdateContactRequest, UpdateDomainRequest, Usage, Webhook, WebhookDelivery, Deleted, BroadcastRecipientCount } from "./types.js";
2
2
  import { type VerifyWebhookOptions } from "./webhooks.js";
3
- export declare const VERSION = "0.1.1";
3
+ export declare const VERSION = "0.2.0";
4
4
  export interface DelivrieOptions {
5
5
  /** Defaults to `https://delivrie.io/api`. */
6
6
  baseUrl?: string;
@@ -1,5 +1,5 @@
1
1
  import { verifyWebhook } from "./webhooks.js";
2
- export const VERSION = "0.1.1";
2
+ export const VERSION = "0.2.0";
3
3
  const DEFAULT_BASE_URL = "https://delivrie.io/api";
4
4
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
5
5
  const enc = encodeURIComponent;
@@ -9,6 +9,39 @@ function toBase64(bytes) {
9
9
  s += String.fromCharCode.apply(null, Array.from(bytes.subarray(i, i + 0x8000)));
10
10
  return btoa(s);
11
11
  }
12
+ // React Email: render a component to HTML and text with @react-email/render, which the app installs alongside
13
+ // React Email (it's an optional peer dependency, so the SDK itself stays dependency-free). The specifier is
14
+ // left for the runtime to resolve, so bundlers don't fail for apps that never send React components.
15
+ async function renderReact(node) {
16
+ let mod;
17
+ try {
18
+ const specifier = "@react-email/render";
19
+ mod = await import(/* webpackIgnore: true */ /* @vite-ignore */ specifier);
20
+ }
21
+ catch {
22
+ throw new ReactRenderError("To send React Email components, install @react-email/render: npm install @react-email/render");
23
+ }
24
+ try {
25
+ return { html: await mod.render(node), text: await mod.render(node, { plainText: true }) };
26
+ }
27
+ catch (e) {
28
+ throw new ReactRenderError(`Couldn't render the React component: ${e?.message || e}`);
29
+ }
30
+ }
31
+ class ReactRenderError extends Error {
32
+ }
33
+ async function prepareEmail(e) {
34
+ const out = normalizeEmail(e);
35
+ if (e.react !== undefined && e.react !== null) {
36
+ const { html, text } = await renderReact(e.react);
37
+ if (out.html === undefined)
38
+ out.html = html;
39
+ if (out.text === undefined)
40
+ out.text = text;
41
+ }
42
+ delete out.react;
43
+ return out;
44
+ }
12
45
  function normalizeEmail(e) {
13
46
  const { replyTo, scheduledAt, attachments, ...rest } = e;
14
47
  const out = { ...rest };
@@ -35,9 +68,27 @@ export class Delivrie {
35
68
  // ---------------------------------------------------------------- resources
36
69
  this.emails = {
37
70
  /** Send one email. Returns its id straight away; delivery events arrive through webhooks. */
38
- send: (email, opts) => this.request("POST", "/emails", normalizeEmail(email), opts),
71
+ send: async (email, opts) => {
72
+ try {
73
+ return await this.request("POST", "/emails", await prepareEmail(email), opts);
74
+ }
75
+ catch (e) {
76
+ if (e instanceof ReactRenderError)
77
+ return renderFailure(e);
78
+ throw e;
79
+ }
80
+ },
39
81
  /** Send up to 100 emails in one request (no attachments or scheduling). */
40
- batch: (emails, opts) => this.request("POST", "/emails/batch", emails.map(normalizeEmail), opts),
82
+ batch: async (emails, opts) => {
83
+ try {
84
+ return await this.request("POST", "/emails/batch", await Promise.all(emails.map(prepareEmail)), opts);
85
+ }
86
+ catch (e) {
87
+ if (e instanceof ReactRenderError)
88
+ return renderFailure(e);
89
+ throw e;
90
+ }
91
+ },
41
92
  get: (id) => this.request("GET", `/emails/${enc(id)}`),
42
93
  list: (params = {}) => this.request("GET", "/emails", undefined, { query: { ...params } }),
43
94
  /** Received (inbound) emails. */
@@ -226,6 +277,9 @@ export class Delivrie {
226
277
  }
227
278
  }
228
279
  }
280
+ function renderFailure(e) {
281
+ return { data: null, error: { statusCode: 0, name: "react_render_error", message: e.message } };
282
+ }
229
283
  function backoff(attempt) {
230
284
  return Math.min(8000, 500 * 2 ** attempt) + Math.floor(Math.random() * 250);
231
285
  }
@@ -58,6 +58,11 @@ export interface SendEmailRequest {
58
58
  html?: string;
59
59
  /** Generated from `html` when omitted. */
60
60
  text?: string;
61
+ /**
62
+ * A React Email component, like `<Welcome name="Ada" />`. The SDK renders it to `html` and `text` with
63
+ * `@react-email/render`, which you install alongside React Email. Ignored if you also pass `html`.
64
+ */
65
+ react?: unknown;
61
66
  cc?: string | string[];
62
67
  bcc?: string | string[];
63
68
  reply_to?: string | string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "delivrie",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Official Node.js and TypeScript SDK for the Delivrie email API: send transactional email, manage domains, contacts, broadcasts and templates, and verify webhooks.",
5
5
  "keywords": ["delivrie", "email", "email-api", "transactional-email", "smtp", "resend-alternative", "webhooks", "nigeria", "naira"],
6
6
  "homepage": "https://delivrie.io/docs/sdks",
@@ -21,6 +21,8 @@
21
21
  },
22
22
  "files": ["dist", "README.md", "LICENSE"],
23
23
  "sideEffects": false,
24
+ "peerDependencies": { "@react-email/render": ">=0.0.7" },
25
+ "peerDependenciesMeta": { "@react-email/render": { "optional": true } },
24
26
  "engines": { "node": ">=18" },
25
27
  "scripts": {
26
28
  "build": "node scripts/build.mjs",