@hogsend/plugin-resend 0.0.1
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/LICENSE +93 -0
- package/README.md +9 -0
- package/package.json +44 -0
- package/src/__tests__/send.test.ts +198 -0
- package/src/__tests__/webhooks.test.ts +79 -0
- package/src/client.ts +5 -0
- package/src/index.ts +32 -0
- package/src/provider.ts +62 -0
- package/src/send.ts +215 -0
- package/src/types.ts +138 -0
- package/src/webhooks.ts +86 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Elastic License 2.0 (ELv2)
|
|
2
|
+
|
|
3
|
+
Copyright 2025 Doug Silkstone and Hogsend contributors
|
|
4
|
+
|
|
5
|
+
## Acceptance
|
|
6
|
+
|
|
7
|
+
By using the software, you agree to all of the terms and conditions below.
|
|
8
|
+
|
|
9
|
+
## Copyright License
|
|
10
|
+
|
|
11
|
+
The licensor grants you a non-exclusive, royalty-free, worldwide,
|
|
12
|
+
non-sublicensable, non-transferable license to use, copy, distribute, make
|
|
13
|
+
available, and prepare derivative works of the software, in each case subject to
|
|
14
|
+
the limitations and conditions below.
|
|
15
|
+
|
|
16
|
+
## Limitations
|
|
17
|
+
|
|
18
|
+
You may not provide the software to third parties as a hosted or managed
|
|
19
|
+
service, where the service provides users with access to any substantial set of
|
|
20
|
+
the features or functionality of the software.
|
|
21
|
+
|
|
22
|
+
You may not move, change, disable, or circumvent the license key functionality
|
|
23
|
+
in the software, and you may not remove or obscure any functionality in the
|
|
24
|
+
software that is protected by the license key.
|
|
25
|
+
|
|
26
|
+
You may not alter, remove, or obscure any licensing, copyright, or other notices
|
|
27
|
+
of the licensor in the software. Any use of the licensor's trademarks is subject
|
|
28
|
+
to applicable law.
|
|
29
|
+
|
|
30
|
+
## Patents
|
|
31
|
+
|
|
32
|
+
The licensor grants you a license, under any patent claims the licensor can
|
|
33
|
+
license, or becomes able to license, to make, have made, use, sell, offer for
|
|
34
|
+
sale, import and have imported the software, in each case subject to the
|
|
35
|
+
limitations and conditions in this license. This license does not cover any
|
|
36
|
+
patent claims that you cause to be infringed by modifications or additions to
|
|
37
|
+
the software. If you or your company make any written claim that the software
|
|
38
|
+
infringes or contributes to infringement of any patent, your patent license for
|
|
39
|
+
the software granted under these terms ends immediately. If your company makes
|
|
40
|
+
such a claim, your patent license ends immediately for work on behalf of your
|
|
41
|
+
company.
|
|
42
|
+
|
|
43
|
+
## Notices
|
|
44
|
+
|
|
45
|
+
You must ensure that anyone who gets a copy of any part of the software from you
|
|
46
|
+
also gets a copy of these terms.
|
|
47
|
+
|
|
48
|
+
If you modify the software, you must include in any modified copies of the
|
|
49
|
+
software prominent notices stating that you have modified the software.
|
|
50
|
+
|
|
51
|
+
## No Other Rights
|
|
52
|
+
|
|
53
|
+
These terms do not imply any licenses other than those expressly granted in
|
|
54
|
+
these terms.
|
|
55
|
+
|
|
56
|
+
## Termination
|
|
57
|
+
|
|
58
|
+
If you use the software in violation of these terms, such use is not licensed,
|
|
59
|
+
and your licenses will automatically terminate. If the licensor provides you
|
|
60
|
+
with a notice of your violation, and you cease all violation of this license no
|
|
61
|
+
later than 30 days after you receive that notice, your licenses will be
|
|
62
|
+
reinstated retroactively. However, if you violate these terms after such
|
|
63
|
+
reinstatement, any additional violation of these terms will cause your licenses
|
|
64
|
+
to terminate automatically and permanently.
|
|
65
|
+
|
|
66
|
+
## No Liability
|
|
67
|
+
|
|
68
|
+
*As far as the law allows, the software comes as is, without any warranty or
|
|
69
|
+
condition, and the licensor will not be liable to you for any damages arising out
|
|
70
|
+
of these terms or the use or nature of the software, under any kind of legal
|
|
71
|
+
claim.*
|
|
72
|
+
|
|
73
|
+
## Definitions
|
|
74
|
+
|
|
75
|
+
The **licensor** is the entity offering these terms, and the **software** is the
|
|
76
|
+
software the licensor makes available under these terms, including any portion
|
|
77
|
+
of it.
|
|
78
|
+
|
|
79
|
+
**you** refers to the individual or entity agreeing to these terms.
|
|
80
|
+
|
|
81
|
+
**your company** is any legal entity, sole proprietorship, or other kind of
|
|
82
|
+
organization that you work for, plus all organizations that have control over,
|
|
83
|
+
are under the control of, or are under common control with that organization.
|
|
84
|
+
**control** means ownership of substantially all the assets of an entity, or the
|
|
85
|
+
power to direct its management and policies by vote, contract, or otherwise.
|
|
86
|
+
Control can be direct or indirect.
|
|
87
|
+
|
|
88
|
+
**your licenses** are all the licenses granted to you for the software under
|
|
89
|
+
these terms.
|
|
90
|
+
|
|
91
|
+
**use** means anything you do with the software requiring one of your licenses.
|
|
92
|
+
|
|
93
|
+
**trademark** means trademarks, service marks, and similar rights.
|
package/README.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# @hogsend/plugin-resend
|
|
2
|
+
|
|
3
|
+
Resend email delivery for [Hogsend](https://github.com/dougwithseismic/hogsend):
|
|
4
|
+
single + batch sends, tracked sends, webhook parsing/verification, and an email
|
|
5
|
+
service with bounce tracking.
|
|
6
|
+
|
|
7
|
+
This package ships raw TypeScript source; consumers bundle it via their own build
|
|
8
|
+
(tsup `noExternal`). See the
|
|
9
|
+
[release model](https://github.com/dougwithseismic/hogsend/blob/main/docs/RELEASING.md).
|
package/package.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@hogsend/plugin-resend",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/dougwithseismic/hogsend.git",
|
|
9
|
+
"directory": "packages/plugin-resend"
|
|
10
|
+
},
|
|
11
|
+
"sideEffects": false,
|
|
12
|
+
"main": "./src/index.ts",
|
|
13
|
+
"types": "./src/index.ts",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": "./src/index.ts"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"src",
|
|
19
|
+
"README.md"
|
|
20
|
+
],
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"resend": "^6.12.3",
|
|
26
|
+
"svix": "^1.94.0",
|
|
27
|
+
"@hogsend/email": "^0.0.1"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@types/node": "^22.0.0",
|
|
31
|
+
"@types/react": "^19.0.0",
|
|
32
|
+
"react": "^19.0.0",
|
|
33
|
+
"tsup": "^8.0.0",
|
|
34
|
+
"typescript": "^5.7.0",
|
|
35
|
+
"vitest": "^4.1.7",
|
|
36
|
+
"@repo/typescript-config": "^0.0.0"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "tsup",
|
|
40
|
+
"check-types": "tsc --noEmit",
|
|
41
|
+
"test": "vitest run",
|
|
42
|
+
"test:watch": "vitest watch"
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { EmailSendError } from "@hogsend/email";
|
|
2
|
+
import { createElement } from "react";
|
|
3
|
+
import type { Resend } from "resend";
|
|
4
|
+
import { describe, expect, it, vi } from "vitest";
|
|
5
|
+
import { sendBatchEmails, sendEmail } from "../send.js";
|
|
6
|
+
|
|
7
|
+
function mockResendClient(overrides?: {
|
|
8
|
+
sendFn?: () => Promise<unknown>;
|
|
9
|
+
batchFn?: () => Promise<unknown>;
|
|
10
|
+
}) {
|
|
11
|
+
return {
|
|
12
|
+
emails: {
|
|
13
|
+
send:
|
|
14
|
+
overrides?.sendFn ??
|
|
15
|
+
vi.fn().mockResolvedValue({
|
|
16
|
+
data: { id: "resend_123" },
|
|
17
|
+
error: null,
|
|
18
|
+
}),
|
|
19
|
+
},
|
|
20
|
+
batch: {
|
|
21
|
+
send:
|
|
22
|
+
overrides?.batchFn ??
|
|
23
|
+
vi.fn().mockResolvedValue({
|
|
24
|
+
data: { data: [{ id: "batch_1" }, { id: "batch_2" }] },
|
|
25
|
+
error: null,
|
|
26
|
+
}),
|
|
27
|
+
},
|
|
28
|
+
} as unknown as Resend;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function dummyElement() {
|
|
32
|
+
return createElement("div", null, "test");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
describe("sendEmail", () => {
|
|
36
|
+
it("sends successfully and returns id", async () => {
|
|
37
|
+
const client = mockResendClient();
|
|
38
|
+
const result = await sendEmail({
|
|
39
|
+
client,
|
|
40
|
+
options: {
|
|
41
|
+
from: "test@hogsend.com",
|
|
42
|
+
to: "user@example.com",
|
|
43
|
+
subject: "Test",
|
|
44
|
+
react: dummyElement(),
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
expect(result.id).toBe("resend_123");
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("normalizes string recipient to array", async () => {
|
|
51
|
+
const sendFn = vi.fn().mockResolvedValue({
|
|
52
|
+
data: { id: "resend_123" },
|
|
53
|
+
error: null,
|
|
54
|
+
});
|
|
55
|
+
const client = mockResendClient({ sendFn });
|
|
56
|
+
|
|
57
|
+
await sendEmail({
|
|
58
|
+
client,
|
|
59
|
+
options: {
|
|
60
|
+
from: "test@hogsend.com",
|
|
61
|
+
to: "user@example.com",
|
|
62
|
+
subject: "Test",
|
|
63
|
+
react: dummyElement(),
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
expect(sendFn).toHaveBeenCalledWith(
|
|
68
|
+
expect.objectContaining({ to: ["user@example.com"] }),
|
|
69
|
+
);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it("throws EmailSendError on API error", async () => {
|
|
73
|
+
const client = mockResendClient({
|
|
74
|
+
sendFn: vi.fn().mockResolvedValue({
|
|
75
|
+
data: null,
|
|
76
|
+
error: { message: "Invalid API key" },
|
|
77
|
+
}),
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
await expect(
|
|
81
|
+
sendEmail({
|
|
82
|
+
client,
|
|
83
|
+
options: {
|
|
84
|
+
from: "test@hogsend.com",
|
|
85
|
+
to: "user@example.com",
|
|
86
|
+
subject: "Test",
|
|
87
|
+
react: dummyElement(),
|
|
88
|
+
},
|
|
89
|
+
retryOptions: { maxRetries: 0 },
|
|
90
|
+
}),
|
|
91
|
+
).rejects.toThrow(EmailSendError);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it("retries on transient errors", async () => {
|
|
95
|
+
let attempt = 0;
|
|
96
|
+
const sendFn = vi.fn().mockImplementation(async () => {
|
|
97
|
+
attempt++;
|
|
98
|
+
if (attempt < 3) {
|
|
99
|
+
return {
|
|
100
|
+
data: null,
|
|
101
|
+
error: { message: "rate limit exceeded", statusCode: 429 },
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
return { data: { id: "resend_success" }, error: null };
|
|
105
|
+
});
|
|
106
|
+
const client = mockResendClient({ sendFn });
|
|
107
|
+
|
|
108
|
+
const result = await sendEmail({
|
|
109
|
+
client,
|
|
110
|
+
options: {
|
|
111
|
+
from: "test@hogsend.com",
|
|
112
|
+
to: "user@example.com",
|
|
113
|
+
subject: "Test",
|
|
114
|
+
react: dummyElement(),
|
|
115
|
+
},
|
|
116
|
+
retryOptions: { maxRetries: 3, baseDelayMs: 10, maxDelayMs: 50 },
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
expect(result.id).toBe("resend_success");
|
|
120
|
+
expect(sendFn).toHaveBeenCalledTimes(3);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it("does not retry non-retryable errors", async () => {
|
|
124
|
+
const sendFn = vi.fn().mockResolvedValue({
|
|
125
|
+
data: null,
|
|
126
|
+
error: { message: "Invalid email address", statusCode: 422 },
|
|
127
|
+
});
|
|
128
|
+
const client = mockResendClient({ sendFn });
|
|
129
|
+
|
|
130
|
+
await expect(
|
|
131
|
+
sendEmail({
|
|
132
|
+
client,
|
|
133
|
+
options: {
|
|
134
|
+
from: "test@hogsend.com",
|
|
135
|
+
to: "user@example.com",
|
|
136
|
+
subject: "Test",
|
|
137
|
+
react: dummyElement(),
|
|
138
|
+
},
|
|
139
|
+
retryOptions: { maxRetries: 3, baseDelayMs: 10 },
|
|
140
|
+
}),
|
|
141
|
+
).rejects.toThrow(EmailSendError);
|
|
142
|
+
|
|
143
|
+
expect(sendFn).toHaveBeenCalledTimes(1);
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
describe("sendBatchEmails", () => {
|
|
148
|
+
it("returns empty array for empty input", async () => {
|
|
149
|
+
const client = mockResendClient();
|
|
150
|
+
const result = await sendBatchEmails({ client, emails: [] });
|
|
151
|
+
expect(result).toEqual([]);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it("sends a batch and returns ids", async () => {
|
|
155
|
+
const client = mockResendClient();
|
|
156
|
+
const result = await sendBatchEmails({
|
|
157
|
+
client,
|
|
158
|
+
emails: [
|
|
159
|
+
{
|
|
160
|
+
from: "a@hogsend.com",
|
|
161
|
+
to: "b@example.com",
|
|
162
|
+
subject: "A",
|
|
163
|
+
react: dummyElement(),
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
from: "a@hogsend.com",
|
|
167
|
+
to: "c@example.com",
|
|
168
|
+
subject: "B",
|
|
169
|
+
react: dummyElement(),
|
|
170
|
+
},
|
|
171
|
+
],
|
|
172
|
+
});
|
|
173
|
+
expect(result).toEqual([{ id: "batch_1" }, { id: "batch_2" }]);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it("auto-chunks lists larger than 100", async () => {
|
|
177
|
+
const batchFn = vi.fn().mockResolvedValue({
|
|
178
|
+
data: { data: Array.from({ length: 50 }, (_, i) => ({ id: `id_${i}` })) },
|
|
179
|
+
error: null,
|
|
180
|
+
});
|
|
181
|
+
const client = mockResendClient({ batchFn });
|
|
182
|
+
|
|
183
|
+
const emails = Array.from({ length: 150 }, (_, i) => ({
|
|
184
|
+
from: "a@hogsend.com",
|
|
185
|
+
to: `user${i}@example.com`,
|
|
186
|
+
subject: `Email ${i}`,
|
|
187
|
+
react: dummyElement(),
|
|
188
|
+
}));
|
|
189
|
+
|
|
190
|
+
await sendBatchEmails({ client, emails });
|
|
191
|
+
|
|
192
|
+
expect(batchFn).toHaveBeenCalledTimes(2);
|
|
193
|
+
const firstCallArgs = batchFn.mock.calls[0]?.[0] as unknown[];
|
|
194
|
+
const secondCallArgs = batchFn.mock.calls[1]?.[0] as unknown[];
|
|
195
|
+
expect(firstCallArgs).toHaveLength(100);
|
|
196
|
+
expect(secondCallArgs).toHaveLength(50);
|
|
197
|
+
});
|
|
198
|
+
});
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { WebhookVerificationError } from "@hogsend/email";
|
|
2
|
+
import { describe, expect, it } from "vitest";
|
|
3
|
+
import type { EmailSentEvent } from "../types.js";
|
|
4
|
+
import { createWebhookHandler, parseWebhookEvent } from "../webhooks.js";
|
|
5
|
+
|
|
6
|
+
function makeSentEvent(): EmailSentEvent {
|
|
7
|
+
return {
|
|
8
|
+
type: "email.sent",
|
|
9
|
+
created_at: "2024-01-01T00:00:00Z",
|
|
10
|
+
data: {
|
|
11
|
+
email_id: "email_123",
|
|
12
|
+
from: "test@hogsend.com",
|
|
13
|
+
to: ["user@example.com"],
|
|
14
|
+
subject: "Test",
|
|
15
|
+
created_at: "2024-01-01T00:00:00Z",
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
describe("parseWebhookEvent", () => {
|
|
21
|
+
it("parses a valid sent event", () => {
|
|
22
|
+
const event = makeSentEvent();
|
|
23
|
+
const parsed = parseWebhookEvent(JSON.stringify(event));
|
|
24
|
+
expect(parsed.type).toBe("email.sent");
|
|
25
|
+
expect(parsed.data.email_id).toBe("email_123");
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it("parses a valid bounced event", () => {
|
|
29
|
+
const event = {
|
|
30
|
+
type: "email.bounced",
|
|
31
|
+
created_at: "2024-01-01T00:00:00Z",
|
|
32
|
+
data: {
|
|
33
|
+
email_id: "email_456",
|
|
34
|
+
from: "test@hogsend.com",
|
|
35
|
+
to: ["user@example.com"],
|
|
36
|
+
subject: "Test",
|
|
37
|
+
created_at: "2024-01-01T00:00:00Z",
|
|
38
|
+
bounce: { message: "Mailbox not found", type: "hard" },
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
const parsed = parseWebhookEvent(JSON.stringify(event));
|
|
42
|
+
expect(parsed.type).toBe("email.bounced");
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it("throws on unknown event type", () => {
|
|
46
|
+
const event = { type: "email.unknown", data: {} };
|
|
47
|
+
expect(() => parseWebhookEvent(JSON.stringify(event))).toThrow(
|
|
48
|
+
WebhookVerificationError,
|
|
49
|
+
);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("throws on invalid JSON", () => {
|
|
53
|
+
expect(() => parseWebhookEvent("not json")).toThrow();
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
describe("createWebhookHandler", () => {
|
|
58
|
+
it("requires valid svix headers", async () => {
|
|
59
|
+
const handler = createWebhookHandler({
|
|
60
|
+
signingSecret: "whsec_test",
|
|
61
|
+
handlers: {},
|
|
62
|
+
});
|
|
63
|
+
await expect(handler(JSON.stringify(makeSentEvent()), {})).rejects.toThrow(
|
|
64
|
+
WebhookVerificationError,
|
|
65
|
+
);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("requires svix headers to be present", async () => {
|
|
69
|
+
const handler = createWebhookHandler({
|
|
70
|
+
signingSecret: "whsec_test",
|
|
71
|
+
handlers: {},
|
|
72
|
+
});
|
|
73
|
+
await expect(
|
|
74
|
+
handler(JSON.stringify(makeSentEvent()), {
|
|
75
|
+
"svix-id": "msg_123",
|
|
76
|
+
}),
|
|
77
|
+
).rejects.toThrow("Missing required Svix headers");
|
|
78
|
+
});
|
|
79
|
+
});
|
package/src/client.ts
ADDED
package/src/index.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Client
|
|
2
|
+
export { createResendClient } from "./client.js";
|
|
3
|
+
// EmailProvider (the provider contract + Resend implementation)
|
|
4
|
+
export {
|
|
5
|
+
createResendProvider,
|
|
6
|
+
type ResendProviderConfig,
|
|
7
|
+
} from "./provider.js";
|
|
8
|
+
// Sending (with retry + auto-chunking)
|
|
9
|
+
export { sendBatchEmails, sendEmail } from "./send.js";
|
|
10
|
+
// Types
|
|
11
|
+
export type {
|
|
12
|
+
BatchEmailItem,
|
|
13
|
+
EmailBouncedEvent,
|
|
14
|
+
EmailClickedEvent,
|
|
15
|
+
EmailComplainedEvent,
|
|
16
|
+
EmailDeliveredEvent,
|
|
17
|
+
EmailDeliveryDelayedEvent,
|
|
18
|
+
EmailOpenedEvent,
|
|
19
|
+
EmailProvider,
|
|
20
|
+
EmailSentEvent,
|
|
21
|
+
SendEmailOptions,
|
|
22
|
+
SendResult,
|
|
23
|
+
WebhookEvent,
|
|
24
|
+
WebhookEventType,
|
|
25
|
+
WebhookHandlerMap,
|
|
26
|
+
} from "./types.js";
|
|
27
|
+
// Webhooks
|
|
28
|
+
export {
|
|
29
|
+
createWebhookHandler,
|
|
30
|
+
parseWebhookEvent,
|
|
31
|
+
verifyWebhook,
|
|
32
|
+
} from "./webhooks.js";
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { RetryOptions } from "@hogsend/email";
|
|
2
|
+
import { createResendClient } from "./client.js";
|
|
3
|
+
import { sendBatchEmails, sendEmail } from "./send.js";
|
|
4
|
+
import type {
|
|
5
|
+
BatchEmailItem,
|
|
6
|
+
EmailProvider,
|
|
7
|
+
SendEmailOptions,
|
|
8
|
+
SendResult,
|
|
9
|
+
WebhookEvent,
|
|
10
|
+
} from "./types.js";
|
|
11
|
+
import { parseWebhookEvent, verifyWebhook } from "./webhooks.js";
|
|
12
|
+
|
|
13
|
+
export interface ResendProviderConfig {
|
|
14
|
+
apiKey: string;
|
|
15
|
+
webhookSecret?: string;
|
|
16
|
+
retryOptions?: RetryOptions;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The Resend implementation of the engine's {@link EmailProvider} contract: a dumb
|
|
21
|
+
* delivery + webhook parse/verify layer. All tracking, DB, preference, and
|
|
22
|
+
* render logic lives in the engine's `createTrackedMailer`, not here.
|
|
23
|
+
*/
|
|
24
|
+
export function createResendProvider(
|
|
25
|
+
config: ResendProviderConfig,
|
|
26
|
+
): EmailProvider {
|
|
27
|
+
const client = createResendClient({ apiKey: config.apiKey });
|
|
28
|
+
const retryOptions = config.retryOptions;
|
|
29
|
+
|
|
30
|
+
return {
|
|
31
|
+
async send(options: SendEmailOptions): Promise<SendResult> {
|
|
32
|
+
return sendEmail({ client, options, retryOptions });
|
|
33
|
+
},
|
|
34
|
+
|
|
35
|
+
async sendBatch(
|
|
36
|
+
emails: BatchEmailItem[],
|
|
37
|
+
): Promise<{ results: SendResult[] }> {
|
|
38
|
+
const results = await sendBatchEmails({ client, emails, retryOptions });
|
|
39
|
+
return { results };
|
|
40
|
+
},
|
|
41
|
+
|
|
42
|
+
verifyWebhook(opts: {
|
|
43
|
+
payload: string;
|
|
44
|
+
headers: Record<string, string>;
|
|
45
|
+
}): WebhookEvent {
|
|
46
|
+
if (!config.webhookSecret) {
|
|
47
|
+
throw new Error(
|
|
48
|
+
"webhookSecret is required on the provider to verify webhooks",
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
return verifyWebhook({
|
|
52
|
+
payload: opts.payload,
|
|
53
|
+
headers: opts.headers,
|
|
54
|
+
signingSecret: config.webhookSecret,
|
|
55
|
+
});
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
parseWebhook(payload: string): WebhookEvent {
|
|
59
|
+
return parseWebhookEvent(payload);
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
package/src/send.ts
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_RETRY_OPTIONS,
|
|
3
|
+
EmailSendError,
|
|
4
|
+
type RetryOptions,
|
|
5
|
+
} from "@hogsend/email";
|
|
6
|
+
import type { Resend } from "resend";
|
|
7
|
+
import type { BatchEmailItem, SendEmailOptions, SendResult } from "./types.js";
|
|
8
|
+
|
|
9
|
+
const BATCH_CHUNK_SIZE = 100;
|
|
10
|
+
|
|
11
|
+
function normalizeRecipients(to: string | string[]): string[] {
|
|
12
|
+
return Array.isArray(to) ? to : [to];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function isRetryableStatusCode(statusCode: number): boolean {
|
|
16
|
+
return statusCode === 429 || statusCode >= 500;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function classifyError(error: unknown): EmailSendError {
|
|
20
|
+
if (error instanceof EmailSendError) return error;
|
|
21
|
+
|
|
22
|
+
const message =
|
|
23
|
+
error instanceof Error ? error.message : "Unknown email send error";
|
|
24
|
+
|
|
25
|
+
if (
|
|
26
|
+
typeof error === "object" &&
|
|
27
|
+
error !== null &&
|
|
28
|
+
"statusCode" in error &&
|
|
29
|
+
typeof (error as { statusCode: unknown }).statusCode === "number"
|
|
30
|
+
) {
|
|
31
|
+
const statusCode = (error as { statusCode: number }).statusCode;
|
|
32
|
+
return new EmailSendError(message, {
|
|
33
|
+
retryable: isRetryableStatusCode(statusCode),
|
|
34
|
+
statusCode,
|
|
35
|
+
cause: error,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const lowerMessage = message.toLowerCase();
|
|
40
|
+
const retryable =
|
|
41
|
+
lowerMessage.includes("rate limit") ||
|
|
42
|
+
lowerMessage.includes("timeout") ||
|
|
43
|
+
lowerMessage.includes("econnreset") ||
|
|
44
|
+
lowerMessage.includes("econnrefused") ||
|
|
45
|
+
lowerMessage.includes("network");
|
|
46
|
+
|
|
47
|
+
return new EmailSendError(message, { retryable, cause: error });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function sleep(ms: number): Promise<void> {
|
|
51
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function getBackoffDelay(
|
|
55
|
+
attempt: number,
|
|
56
|
+
baseDelayMs: number,
|
|
57
|
+
maxDelayMs: number,
|
|
58
|
+
): number {
|
|
59
|
+
const exponentialDelay = baseDelayMs * 2 ** attempt;
|
|
60
|
+
const jitter = Math.random() * baseDelayMs;
|
|
61
|
+
return Math.min(exponentialDelay + jitter, maxDelayMs);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function withRetry<T>(
|
|
65
|
+
fn: () => Promise<T>,
|
|
66
|
+
options: Required<RetryOptions>,
|
|
67
|
+
): Promise<T> {
|
|
68
|
+
let lastError: EmailSendError | undefined;
|
|
69
|
+
|
|
70
|
+
for (let attempt = 0; attempt <= options.maxRetries; attempt++) {
|
|
71
|
+
try {
|
|
72
|
+
return await fn();
|
|
73
|
+
} catch (error) {
|
|
74
|
+
lastError = classifyError(error);
|
|
75
|
+
|
|
76
|
+
if (!lastError.retryable || attempt === options.maxRetries) {
|
|
77
|
+
throw lastError;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const delay = getBackoffDelay(
|
|
81
|
+
attempt,
|
|
82
|
+
options.baseDelayMs,
|
|
83
|
+
options.maxDelayMs,
|
|
84
|
+
);
|
|
85
|
+
await sleep(delay);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
throw (
|
|
90
|
+
lastError ?? new EmailSendError("Retry exhausted", { retryable: false })
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function sendEmail(args: {
|
|
95
|
+
client: Resend;
|
|
96
|
+
options: SendEmailOptions;
|
|
97
|
+
retryOptions?: RetryOptions;
|
|
98
|
+
}): Promise<SendResult> {
|
|
99
|
+
const { client, options, retryOptions } = args;
|
|
100
|
+
const opts = { ...DEFAULT_RETRY_OPTIONS, ...retryOptions };
|
|
101
|
+
|
|
102
|
+
return withRetry(async () => {
|
|
103
|
+
const { data, error } = await client.emails.send({
|
|
104
|
+
from: options.from,
|
|
105
|
+
to: normalizeRecipients(options.to),
|
|
106
|
+
subject: options.subject,
|
|
107
|
+
...(options.html ? { html: options.html } : { react: options.react }),
|
|
108
|
+
replyTo: options.replyTo,
|
|
109
|
+
cc: options.cc,
|
|
110
|
+
bcc: options.bcc,
|
|
111
|
+
scheduledAt: options.scheduledAt,
|
|
112
|
+
tags: options.tags,
|
|
113
|
+
headers: options.headers,
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
if (error) {
|
|
117
|
+
throw new EmailSendError(`Failed to send email: ${error.message}`, {
|
|
118
|
+
retryable:
|
|
119
|
+
"statusCode" in error &&
|
|
120
|
+
typeof (error as { statusCode: unknown }).statusCode === "number"
|
|
121
|
+
? isRetryableStatusCode(
|
|
122
|
+
(error as { statusCode: number }).statusCode,
|
|
123
|
+
)
|
|
124
|
+
: false,
|
|
125
|
+
statusCode:
|
|
126
|
+
"statusCode" in error
|
|
127
|
+
? ((error as { statusCode: unknown }).statusCode as number)
|
|
128
|
+
: undefined,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (!data) {
|
|
133
|
+
throw new EmailSendError("Failed to send email: no data returned", {
|
|
134
|
+
retryable: true,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return { id: data.id };
|
|
139
|
+
}, opts);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function sendBatchEmails(args: {
|
|
143
|
+
client: Resend;
|
|
144
|
+
emails: BatchEmailItem[];
|
|
145
|
+
retryOptions?: RetryOptions;
|
|
146
|
+
}): Promise<SendResult[]> {
|
|
147
|
+
const { client, emails, retryOptions } = args;
|
|
148
|
+
if (emails.length === 0) return [];
|
|
149
|
+
|
|
150
|
+
const chunks: BatchEmailItem[][] = [];
|
|
151
|
+
for (let i = 0; i < emails.length; i += BATCH_CHUNK_SIZE) {
|
|
152
|
+
chunks.push(emails.slice(i, i + BATCH_CHUNK_SIZE));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const allResults: SendResult[] = [];
|
|
156
|
+
|
|
157
|
+
for (const chunk of chunks) {
|
|
158
|
+
const results = await sendBatchChunk(client, chunk, retryOptions);
|
|
159
|
+
allResults.push(...results);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return allResults;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function sendBatchChunk(
|
|
166
|
+
client: Resend,
|
|
167
|
+
emails: BatchEmailItem[],
|
|
168
|
+
retryOptions?: RetryOptions,
|
|
169
|
+
): Promise<SendResult[]> {
|
|
170
|
+
const opts = { ...DEFAULT_RETRY_OPTIONS, ...retryOptions };
|
|
171
|
+
|
|
172
|
+
return withRetry(async () => {
|
|
173
|
+
const { data, error } = await client.batch.send(
|
|
174
|
+
emails.map((email) => ({
|
|
175
|
+
from: email.from,
|
|
176
|
+
to: normalizeRecipients(email.to),
|
|
177
|
+
subject: email.subject,
|
|
178
|
+
react: email.react,
|
|
179
|
+
replyTo: email.replyTo,
|
|
180
|
+
cc: email.cc,
|
|
181
|
+
bcc: email.bcc,
|
|
182
|
+
tags: email.tags,
|
|
183
|
+
headers: email.headers,
|
|
184
|
+
})),
|
|
185
|
+
);
|
|
186
|
+
|
|
187
|
+
if (error) {
|
|
188
|
+
throw new EmailSendError(
|
|
189
|
+
`Failed to send batch emails: ${error.message}`,
|
|
190
|
+
{
|
|
191
|
+
retryable:
|
|
192
|
+
"statusCode" in error &&
|
|
193
|
+
typeof (error as { statusCode: unknown }).statusCode === "number"
|
|
194
|
+
? isRetryableStatusCode(
|
|
195
|
+
(error as { statusCode: number }).statusCode,
|
|
196
|
+
)
|
|
197
|
+
: false,
|
|
198
|
+
statusCode:
|
|
199
|
+
"statusCode" in error
|
|
200
|
+
? ((error as { statusCode: unknown }).statusCode as number)
|
|
201
|
+
: undefined,
|
|
202
|
+
},
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (!data) {
|
|
207
|
+
throw new EmailSendError(
|
|
208
|
+
"Failed to send batch emails: no data returned",
|
|
209
|
+
{ retryable: true },
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return data.data.map((item: { id: string }) => ({ id: item.id }));
|
|
214
|
+
}, opts);
|
|
215
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import type { ReactElement } from "react";
|
|
2
|
+
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
// Send options
|
|
5
|
+
// ---------------------------------------------------------------------------
|
|
6
|
+
|
|
7
|
+
export interface SendEmailOptions {
|
|
8
|
+
from: string;
|
|
9
|
+
to: string | string[];
|
|
10
|
+
subject: string;
|
|
11
|
+
react?: ReactElement;
|
|
12
|
+
html?: string;
|
|
13
|
+
replyTo?: string | string[];
|
|
14
|
+
cc?: string | string[];
|
|
15
|
+
bcc?: string | string[];
|
|
16
|
+
scheduledAt?: string;
|
|
17
|
+
tags?: Array<{ name: string; value: string }>;
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface BatchEmailItem {
|
|
22
|
+
from: string;
|
|
23
|
+
to: string | string[];
|
|
24
|
+
subject: string;
|
|
25
|
+
react: ReactElement;
|
|
26
|
+
replyTo?: string | string[];
|
|
27
|
+
cc?: string | string[];
|
|
28
|
+
bcc?: string | string[];
|
|
29
|
+
tags?: Array<{ name: string; value: string }>;
|
|
30
|
+
headers?: Record<string, string>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface SendResult {
|
|
34
|
+
id: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
// Webhook events
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
interface WebhookEventBase {
|
|
42
|
+
created_at: string;
|
|
43
|
+
data: {
|
|
44
|
+
email_id: string;
|
|
45
|
+
from: string;
|
|
46
|
+
to: string[];
|
|
47
|
+
subject: string;
|
|
48
|
+
created_at: string;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface EmailSentEvent extends WebhookEventBase {
|
|
53
|
+
type: "email.sent";
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface EmailDeliveredEvent extends WebhookEventBase {
|
|
57
|
+
type: "email.delivered";
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface EmailBouncedEvent extends WebhookEventBase {
|
|
61
|
+
type: "email.bounced";
|
|
62
|
+
data: WebhookEventBase["data"] & {
|
|
63
|
+
bounce: {
|
|
64
|
+
message: string;
|
|
65
|
+
type: string;
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface EmailComplainedEvent extends WebhookEventBase {
|
|
71
|
+
type: "email.complained";
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface EmailDeliveryDelayedEvent extends WebhookEventBase {
|
|
75
|
+
type: "email.delivery_delayed";
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface EmailOpenedEvent extends WebhookEventBase {
|
|
79
|
+
type: "email.opened";
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface EmailClickedEvent extends WebhookEventBase {
|
|
83
|
+
type: "email.clicked";
|
|
84
|
+
data: WebhookEventBase["data"] & {
|
|
85
|
+
click: {
|
|
86
|
+
link: string;
|
|
87
|
+
timestamp: string;
|
|
88
|
+
ipAddress: string;
|
|
89
|
+
userAgent: string;
|
|
90
|
+
};
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export type WebhookEvent =
|
|
95
|
+
| EmailSentEvent
|
|
96
|
+
| EmailDeliveredEvent
|
|
97
|
+
| EmailBouncedEvent
|
|
98
|
+
| EmailComplainedEvent
|
|
99
|
+
| EmailDeliveryDelayedEvent
|
|
100
|
+
| EmailOpenedEvent
|
|
101
|
+
| EmailClickedEvent;
|
|
102
|
+
|
|
103
|
+
export type WebhookEventType = WebhookEvent["type"];
|
|
104
|
+
|
|
105
|
+
export type WebhookHandlerMap = {
|
|
106
|
+
[K in WebhookEventType]?: (
|
|
107
|
+
event: Extract<WebhookEvent, { type: K }>,
|
|
108
|
+
) => void | Promise<void>;
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// ---------------------------------------------------------------------------
|
|
112
|
+
// EmailProvider contract (the entire provider surface)
|
|
113
|
+
// ---------------------------------------------------------------------------
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* The dumb delivery + webhook parse/verify contract every email provider
|
|
117
|
+
* implements (Resend, Postmark, SES, …). All tracking, DB, preference, and
|
|
118
|
+
* render logic lives in the engine's `createTrackedMailer`, never here.
|
|
119
|
+
*/
|
|
120
|
+
export interface EmailProvider {
|
|
121
|
+
/** Deliver a single message. Returns the provider message id. */
|
|
122
|
+
send(options: SendEmailOptions): Promise<SendResult>;
|
|
123
|
+
|
|
124
|
+
/** Deliver a batch of messages. */
|
|
125
|
+
sendBatch(emails: BatchEmailItem[]): Promise<{ results: SendResult[] }>;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Verify a provider webhook signature and return the parsed event. Throws
|
|
129
|
+
* if the signature is missing/invalid.
|
|
130
|
+
*/
|
|
131
|
+
verifyWebhook(opts: {
|
|
132
|
+
payload: string;
|
|
133
|
+
headers: Record<string, string>;
|
|
134
|
+
}): WebhookEvent;
|
|
135
|
+
|
|
136
|
+
/** Parse an unsigned webhook payload (used in trusted contexts/tests). */
|
|
137
|
+
parseWebhook(payload: string): WebhookEvent;
|
|
138
|
+
}
|
package/src/webhooks.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { WebhookVerificationError } from "@hogsend/email";
|
|
2
|
+
import { Webhook } from "svix";
|
|
3
|
+
import type {
|
|
4
|
+
WebhookEvent,
|
|
5
|
+
WebhookEventType,
|
|
6
|
+
WebhookHandlerMap,
|
|
7
|
+
} from "./types.js";
|
|
8
|
+
|
|
9
|
+
export function verifyWebhook(opts: {
|
|
10
|
+
payload: string;
|
|
11
|
+
headers: Record<string, string>;
|
|
12
|
+
signingSecret: string;
|
|
13
|
+
}): WebhookEvent {
|
|
14
|
+
const svixId = opts.headers["svix-id"];
|
|
15
|
+
const svixTimestamp = opts.headers["svix-timestamp"];
|
|
16
|
+
const svixSignature = opts.headers["svix-signature"];
|
|
17
|
+
|
|
18
|
+
if (!svixId || !svixTimestamp || !svixSignature) {
|
|
19
|
+
throw new WebhookVerificationError(
|
|
20
|
+
"Missing required Svix headers: svix-id, svix-timestamp, svix-signature",
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
try {
|
|
25
|
+
const wh = new Webhook(opts.signingSecret);
|
|
26
|
+
const event = wh.verify(opts.payload, {
|
|
27
|
+
"svix-id": svixId,
|
|
28
|
+
"svix-timestamp": svixTimestamp,
|
|
29
|
+
"svix-signature": svixSignature,
|
|
30
|
+
}) as WebhookEvent;
|
|
31
|
+
|
|
32
|
+
return event;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
throw new WebhookVerificationError(
|
|
35
|
+
`Webhook verification failed: ${error instanceof Error ? error.message : "unknown error"}`,
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function createWebhookHandler(opts: {
|
|
41
|
+
signingSecret: string;
|
|
42
|
+
handlers: WebhookHandlerMap;
|
|
43
|
+
}) {
|
|
44
|
+
return async (
|
|
45
|
+
payload: string,
|
|
46
|
+
headers: Record<string, string>,
|
|
47
|
+
): Promise<{ type: WebhookEventType; handled: boolean }> => {
|
|
48
|
+
const event = verifyWebhook({
|
|
49
|
+
payload,
|
|
50
|
+
headers,
|
|
51
|
+
signingSecret: opts.signingSecret,
|
|
52
|
+
});
|
|
53
|
+
const handler = opts.handlers[event.type] as
|
|
54
|
+
| ((event: WebhookEvent) => void | Promise<void>)
|
|
55
|
+
| undefined;
|
|
56
|
+
|
|
57
|
+
if (handler) {
|
|
58
|
+
await handler(event);
|
|
59
|
+
return { type: event.type, handled: true };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return { type: event.type, handled: false };
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function parseWebhookEvent(payload: string): WebhookEvent {
|
|
67
|
+
const parsed = JSON.parse(payload) as WebhookEvent;
|
|
68
|
+
|
|
69
|
+
const validTypes: WebhookEventType[] = [
|
|
70
|
+
"email.sent",
|
|
71
|
+
"email.delivered",
|
|
72
|
+
"email.bounced",
|
|
73
|
+
"email.complained",
|
|
74
|
+
"email.delivery_delayed",
|
|
75
|
+
"email.opened",
|
|
76
|
+
"email.clicked",
|
|
77
|
+
];
|
|
78
|
+
|
|
79
|
+
if (!validTypes.includes(parsed.type)) {
|
|
80
|
+
throw new WebhookVerificationError(
|
|
81
|
+
`Unknown webhook event type: ${parsed.type}`,
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return parsed;
|
|
86
|
+
}
|