@terreno/comms 57.0.0 → 57.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/dist/adapters/sendgrid.d.ts +27 -0
- package/dist/adapters/sendgrid.js +234 -0
- package/dist/commsService.d.ts +26 -1
- package/dist/commsService.js +792 -111
- package/dist/index.d.ts +2 -2
- package/dist/modelTypes.d.ts +42 -1
- package/dist/models/commsMessage.js +200 -4
- package/dist/types.d.ts +50 -14
- package/package.json +21 -4
- package/src/adapters/sendgrid.test.ts +307 -0
- package/src/adapters/sendgrid.ts +224 -0
- package/src/commsService.test.ts +747 -24
- package/src/commsService.ts +684 -76
- package/src/index.ts +6 -0
- package/src/modelTypes.ts +43 -1
- package/src/models/commsMessage.test.ts +56 -0
- package/src/models/commsMessage.ts +150 -2
- package/src/tests/bunSetup.ts +1 -0
- package/src/types.test.ts +56 -0
- package/src/types.ts +57 -16
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import {describe, it, spyOn} from "bun:test";
|
|
2
|
+
import {logger} from "@terreno/api";
|
|
3
|
+
import {assert} from "chai";
|
|
4
|
+
|
|
5
|
+
import {CommsService} from "../commsService";
|
|
6
|
+
import type {SendResult} from "../types";
|
|
7
|
+
import {SendGridMailProvider} from "./sendgrid";
|
|
8
|
+
|
|
9
|
+
interface MockClientCall {
|
|
10
|
+
message: Record<string, unknown>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const createMockClient = (
|
|
14
|
+
behavior: (message: Record<string, unknown>) => Promise<
|
|
15
|
+
[
|
|
16
|
+
{
|
|
17
|
+
body?: unknown;
|
|
18
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
19
|
+
statusCode?: number;
|
|
20
|
+
},
|
|
21
|
+
Record<string, unknown>,
|
|
22
|
+
]
|
|
23
|
+
>
|
|
24
|
+
): {
|
|
25
|
+
calls: MockClientCall[];
|
|
26
|
+
send: (message: Record<string, unknown>) => Promise<
|
|
27
|
+
[
|
|
28
|
+
{
|
|
29
|
+
body?: unknown;
|
|
30
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
31
|
+
statusCode?: number;
|
|
32
|
+
},
|
|
33
|
+
Record<string, unknown>,
|
|
34
|
+
]
|
|
35
|
+
>;
|
|
36
|
+
} => {
|
|
37
|
+
const calls: MockClientCall[] = [];
|
|
38
|
+
return {
|
|
39
|
+
calls,
|
|
40
|
+
send: async (message: Record<string, unknown>) => {
|
|
41
|
+
calls.push({message});
|
|
42
|
+
return behavior(message);
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const sendGridError = ({
|
|
48
|
+
body,
|
|
49
|
+
statusCode,
|
|
50
|
+
}: {
|
|
51
|
+
body: unknown;
|
|
52
|
+
statusCode: number;
|
|
53
|
+
}): Error & {code: number; response: {body: unknown; statusCode: number}} => {
|
|
54
|
+
const error = new Error(`SendGrid status ${statusCode}`) as Error & {
|
|
55
|
+
code: number;
|
|
56
|
+
response: {body: unknown; statusCode: number};
|
|
57
|
+
};
|
|
58
|
+
error.code = statusCode;
|
|
59
|
+
error.response = {body, statusCode};
|
|
60
|
+
return error;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
describe("SendGridMailProvider", () => {
|
|
64
|
+
it("fails fast when no API key is configured", (): void => {
|
|
65
|
+
Reflect.deleteProperty(process.env, "SENDGRID_API_KEY");
|
|
66
|
+
assert.throws(
|
|
67
|
+
(): SendGridMailProvider => new SendGridMailProvider(),
|
|
68
|
+
/SENDGRID_API_KEY or an apiKey constructor option/
|
|
69
|
+
);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it("sends text and html mail with from-address fallback and sandbox mode under test", async (): Promise<void> => {
|
|
73
|
+
const client = createMockClient(async () => [
|
|
74
|
+
{
|
|
75
|
+
headers: {"x-message-id": "sg-msg-1"},
|
|
76
|
+
statusCode: 202,
|
|
77
|
+
},
|
|
78
|
+
{},
|
|
79
|
+
]);
|
|
80
|
+
const provider = new SendGridMailProvider({
|
|
81
|
+
apiKey: "sg-test-key",
|
|
82
|
+
client,
|
|
83
|
+
fromEmail: "noreply@example.com",
|
|
84
|
+
fromName: "Terreno",
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const result = await provider.sendMail({
|
|
88
|
+
html: "<p>Hello</p>",
|
|
89
|
+
subject: "Welcome",
|
|
90
|
+
text: "Hello",
|
|
91
|
+
to: "person@example.com",
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
assert.isTrue(result.accepted);
|
|
95
|
+
assert.equal(result.providerMessageId, "sg-msg-1");
|
|
96
|
+
assert.include(String(result.metadata?.consoleUrl), "sg-msg-1");
|
|
97
|
+
assert.equal(client.calls.length, 1);
|
|
98
|
+
assert.deepEqual(client.calls[0]?.message.from, {
|
|
99
|
+
email: "noreply@example.com",
|
|
100
|
+
name: "Terreno",
|
|
101
|
+
});
|
|
102
|
+
assert.equal(client.calls[0]?.message.html, "<p>Hello</p>");
|
|
103
|
+
assert.equal(client.calls[0]?.message.text, "Hello");
|
|
104
|
+
assert.deepEqual(client.calls[0]?.message.mailSettings, {
|
|
105
|
+
sandboxMode: {enable: true},
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("passes templateId and dynamicTemplateData through to SendGrid", async (): Promise<void> => {
|
|
110
|
+
const client = createMockClient(async () => [
|
|
111
|
+
{headers: {"x-message-id": "sg-tmpl-1"}, statusCode: 202},
|
|
112
|
+
{},
|
|
113
|
+
]);
|
|
114
|
+
const provider = new SendGridMailProvider({
|
|
115
|
+
apiKey: "sg-test-key",
|
|
116
|
+
client,
|
|
117
|
+
fromEmail: "noreply@example.com",
|
|
118
|
+
sandboxMode: false,
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
await provider.sendMail({
|
|
122
|
+
dynamicTemplateData: {name: "Ada"},
|
|
123
|
+
subject: "Welcome",
|
|
124
|
+
templateId: "d-template-123",
|
|
125
|
+
to: ["a@example.com", "b@example.com"],
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
assert.equal(client.calls[0]?.message.templateId, "d-template-123");
|
|
129
|
+
assert.deepEqual(client.calls[0]?.message.dynamicTemplateData, {name: "Ada"});
|
|
130
|
+
assert.isUndefined(client.calls[0]?.message.mailSettings);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it("classifies bad address as permanent and never throws", async (): Promise<void> => {
|
|
134
|
+
const client = createMockClient(async () => {
|
|
135
|
+
throw sendGridError({
|
|
136
|
+
body: {errors: [{message: "The to address is invalid"}]},
|
|
137
|
+
statusCode: 400,
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
const provider = new SendGridMailProvider({
|
|
141
|
+
apiKey: "sg-test-key",
|
|
142
|
+
client,
|
|
143
|
+
fromEmail: "noreply@example.com",
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
const result = await provider.sendMail({
|
|
147
|
+
subject: "Welcome",
|
|
148
|
+
text: "Hello",
|
|
149
|
+
to: "not-an-email",
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
assert.isFalse(result.accepted);
|
|
153
|
+
assert.equal(result.error, "The to address is invalid");
|
|
154
|
+
assert.equal(result.errorCode, "sendgrid-400");
|
|
155
|
+
assert.equal(result.errorClass, "permanent");
|
|
156
|
+
assert.isTrue(result.isPermanentFailure);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it("classifies network transport failures as transient", async (): Promise<void> => {
|
|
160
|
+
const client = createMockClient(async () => {
|
|
161
|
+
const error = new Error("socket hang up") as Error & {code: string};
|
|
162
|
+
error.code = "ECONNRESET";
|
|
163
|
+
throw error;
|
|
164
|
+
});
|
|
165
|
+
const provider = new SendGridMailProvider({
|
|
166
|
+
apiKey: "sg-test-key",
|
|
167
|
+
client,
|
|
168
|
+
fromEmail: "noreply@example.com",
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
const result = await provider.sendMail({
|
|
172
|
+
subject: "Welcome",
|
|
173
|
+
text: "Hello",
|
|
174
|
+
to: "person@example.com",
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
assert.isFalse(result.accepted);
|
|
178
|
+
assert.equal(result.errorClass, "transient");
|
|
179
|
+
assert.equal(result.errorCode, "sendgrid-500");
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
it("classifies 401/403 as config and logs an error", async (): Promise<void> => {
|
|
183
|
+
const errorSpy = spyOn(logger, "error").mockImplementation(() => undefined);
|
|
184
|
+
try {
|
|
185
|
+
const client = createMockClient(async () => {
|
|
186
|
+
throw sendGridError({
|
|
187
|
+
body: {errors: [{message: "Unauthorized"}]},
|
|
188
|
+
statusCode: 401,
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
const provider = new SendGridMailProvider({
|
|
192
|
+
apiKey: "bad-key",
|
|
193
|
+
client,
|
|
194
|
+
fromEmail: "noreply@example.com",
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
const result = await provider.sendMail({
|
|
198
|
+
subject: "Welcome",
|
|
199
|
+
text: "Hello",
|
|
200
|
+
to: "person@example.com",
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
assert.isFalse(result.accepted);
|
|
204
|
+
assert.equal(result.errorClass, "config");
|
|
205
|
+
assert.equal(result.errorCode, "sendgrid-401");
|
|
206
|
+
assert.isTrue(errorSpy.mock.calls.some((call) => String(call[0]).includes("sendgrid-401")));
|
|
207
|
+
} finally {
|
|
208
|
+
errorSpy.mockRestore();
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it("classifies 429 as transient so the facade retries once", async (): Promise<void> => {
|
|
213
|
+
let attempts = 0;
|
|
214
|
+
const client = createMockClient(async () => {
|
|
215
|
+
attempts += 1;
|
|
216
|
+
if (attempts === 1) {
|
|
217
|
+
throw sendGridError({
|
|
218
|
+
body: {errors: [{message: "Too Many Requests"}]},
|
|
219
|
+
statusCode: 429,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
return [{headers: {"x-message-id": "sg-retry-ok"}, statusCode: 202}, {}];
|
|
223
|
+
});
|
|
224
|
+
const provider = new SendGridMailProvider({
|
|
225
|
+
apiKey: "sg-test-key",
|
|
226
|
+
client,
|
|
227
|
+
fromEmail: "noreply@example.com",
|
|
228
|
+
});
|
|
229
|
+
const onErrorCalls: SendResult[] = [];
|
|
230
|
+
const onRetryCalls: SendResult[] = [];
|
|
231
|
+
const retryAttempts: number[] = [];
|
|
232
|
+
const service = new CommsService({
|
|
233
|
+
mail: provider,
|
|
234
|
+
onError: async (_context, result): Promise<void> => {
|
|
235
|
+
onErrorCalls.push(result);
|
|
236
|
+
},
|
|
237
|
+
onRetry: async (context, result): Promise<void> => {
|
|
238
|
+
retryAttempts.push(context.attempt);
|
|
239
|
+
onRetryCalls.push(result);
|
|
240
|
+
},
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
const result = await service.sendMail({
|
|
244
|
+
subject: "Welcome",
|
|
245
|
+
text: "Hello",
|
|
246
|
+
to: "person@example.com",
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
assert.isTrue(result.accepted);
|
|
250
|
+
assert.equal(attempts, 2);
|
|
251
|
+
assert.deepEqual(retryAttempts, [2]);
|
|
252
|
+
assert.equal(onRetryCalls[0]?.errorClass, "transient");
|
|
253
|
+
assert.equal(onErrorCalls.length, 0);
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
it("fires onError with the classified result when the send finally fails", async (): Promise<void> => {
|
|
257
|
+
const client = createMockClient(async () => {
|
|
258
|
+
throw sendGridError({
|
|
259
|
+
body: {errors: [{message: "The to address is invalid"}]},
|
|
260
|
+
statusCode: 400,
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
const provider = new SendGridMailProvider({
|
|
264
|
+
apiKey: "sg-test-key",
|
|
265
|
+
client,
|
|
266
|
+
fromEmail: "noreply@example.com",
|
|
267
|
+
});
|
|
268
|
+
const onErrorCalls: SendResult[] = [];
|
|
269
|
+
const service = new CommsService({
|
|
270
|
+
mail: provider,
|
|
271
|
+
onError: async (_context, result): Promise<void> => {
|
|
272
|
+
onErrorCalls.push(result);
|
|
273
|
+
},
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
const result = await service.sendMail({
|
|
277
|
+
subject: "Welcome",
|
|
278
|
+
text: "Hello",
|
|
279
|
+
to: "not-an-email",
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
assert.isFalse(result.accepted);
|
|
283
|
+
assert.equal(onErrorCalls.length, 1);
|
|
284
|
+
assert.equal(onErrorCalls[0]?.errorClass, "permanent");
|
|
285
|
+
assert.equal(onErrorCalls[0]?.errorCode, "sendgrid-400");
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
it("uses MailMessage.from when constructor fromEmail is omitted", async (): Promise<void> => {
|
|
289
|
+
const client = createMockClient(async () => [
|
|
290
|
+
{headers: {"x-message-id": "sg-from-msg"}, statusCode: 202},
|
|
291
|
+
{},
|
|
292
|
+
]);
|
|
293
|
+
const provider = new SendGridMailProvider({
|
|
294
|
+
apiKey: "sg-test-key",
|
|
295
|
+
client,
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
await provider.sendMail({
|
|
299
|
+
from: "fallback@example.com",
|
|
300
|
+
subject: "Welcome",
|
|
301
|
+
text: "Hello",
|
|
302
|
+
to: "person@example.com",
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
assert.equal(client.calls[0]?.message.from, "fallback@example.com");
|
|
306
|
+
});
|
|
307
|
+
});
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import {createRequire} from "node:module";
|
|
2
|
+
import {logger} from "@terreno/api";
|
|
3
|
+
|
|
4
|
+
import type {CommsErrorClass, MailMessage, MailProvider, SendResult} from "../types";
|
|
5
|
+
|
|
6
|
+
const nodeRequire = createRequire(__filename);
|
|
7
|
+
|
|
8
|
+
interface SendGridResponse {
|
|
9
|
+
body?: unknown;
|
|
10
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
11
|
+
statusCode?: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
interface SendGridClient {
|
|
15
|
+
send: (message: Record<string, unknown>) => Promise<[SendGridResponse, Record<string, unknown>]>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface SendGridMailModule {
|
|
19
|
+
send: SendGridClient["send"];
|
|
20
|
+
setApiKey: (apiKey: string) => void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface SendGridMailProviderOptions {
|
|
24
|
+
apiKey?: string;
|
|
25
|
+
/** Injected client for tests. Production wiring loads `@sendgrid/mail`. */
|
|
26
|
+
client?: SendGridClient;
|
|
27
|
+
fromEmail?: string;
|
|
28
|
+
fromName?: string;
|
|
29
|
+
sandboxMode?: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const EMAIL_ACTIVITY_BASE = "https://app.sendgrid.com/email_activity";
|
|
33
|
+
|
|
34
|
+
const resolveApiKey = (options?: SendGridMailProviderOptions): string => {
|
|
35
|
+
const apiKey = options?.apiKey ?? process.env.SENDGRID_API_KEY;
|
|
36
|
+
if (!apiKey) {
|
|
37
|
+
throw new Error(
|
|
38
|
+
"SendGridMailProvider requires SENDGRID_API_KEY or an apiKey constructor option"
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
return apiKey;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const loadSendGridMail = (): SendGridMailModule => {
|
|
45
|
+
try {
|
|
46
|
+
// Optional peer — keep `@sendgrid/mail` out of core dependencies.
|
|
47
|
+
return nodeRequire("@sendgrid/mail") as SendGridMailModule;
|
|
48
|
+
} catch {
|
|
49
|
+
throw new Error(
|
|
50
|
+
"SendGridMailProvider requires optional peer dependency @sendgrid/mail. " +
|
|
51
|
+
"Install it with: bun add @sendgrid/mail"
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const headerValue = (
|
|
57
|
+
headers: Record<string, string | string[] | undefined> | undefined,
|
|
58
|
+
name: string
|
|
59
|
+
): string | undefined => {
|
|
60
|
+
if (!headers) {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
const value = headers[name] ?? headers[name.toLowerCase()];
|
|
64
|
+
if (Array.isArray(value)) {
|
|
65
|
+
return value[0];
|
|
66
|
+
}
|
|
67
|
+
return value;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const emailActivityUrl = (messageId: string): string => {
|
|
71
|
+
const filters = encodeURIComponent(
|
|
72
|
+
JSON.stringify([
|
|
73
|
+
{
|
|
74
|
+
comparisonType: "Contains",
|
|
75
|
+
selectedFieldName: "msg_id",
|
|
76
|
+
val: [messageId],
|
|
77
|
+
},
|
|
78
|
+
])
|
|
79
|
+
);
|
|
80
|
+
return `${EMAIL_ACTIVITY_BASE}?filters=${filters}`;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const firstSendGridErrorMessage = (body: unknown): string | undefined => {
|
|
84
|
+
if (!body || typeof body !== "object") {
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
const errors = (body as {errors?: Array<{message?: string}>}).errors;
|
|
88
|
+
if (!Array.isArray(errors) || errors.length === 0) {
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
return errors[0]?.message;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const classifyHttpStatus = (
|
|
95
|
+
statusCode: number
|
|
96
|
+
): {errorClass: CommsErrorClass; errorCode: string} => {
|
|
97
|
+
if (statusCode === 401 || statusCode === 403) {
|
|
98
|
+
return {errorClass: "config", errorCode: `sendgrid-${statusCode}`};
|
|
99
|
+
}
|
|
100
|
+
if (statusCode === 429 || statusCode >= 500) {
|
|
101
|
+
return {errorClass: "transient", errorCode: `sendgrid-${statusCode}`};
|
|
102
|
+
}
|
|
103
|
+
return {errorClass: "permanent", errorCode: `sendgrid-${statusCode}`};
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const failedResult = ({
|
|
107
|
+
body,
|
|
108
|
+
error,
|
|
109
|
+
errorClass,
|
|
110
|
+
errorCode,
|
|
111
|
+
}: {
|
|
112
|
+
body?: unknown;
|
|
113
|
+
error: string;
|
|
114
|
+
errorClass: CommsErrorClass;
|
|
115
|
+
errorCode: string;
|
|
116
|
+
}): SendResult => {
|
|
117
|
+
if (errorClass === "config") {
|
|
118
|
+
logger.error(`[comms:sendgrid] ${errorCode}: ${error}`);
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
accepted: false,
|
|
122
|
+
error,
|
|
123
|
+
errorClass,
|
|
124
|
+
errorCode,
|
|
125
|
+
isPermanentFailure: errorClass === "permanent",
|
|
126
|
+
metadata: body === undefined ? undefined : {sendGridResponse: body},
|
|
127
|
+
};
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const statusFromError = (error: unknown): number | undefined => {
|
|
131
|
+
if (!error || typeof error !== "object") {
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
const withCode = error as {code?: unknown; response?: {statusCode?: unknown}};
|
|
135
|
+
const responseStatus = withCode.response?.statusCode;
|
|
136
|
+
if (typeof responseStatus === "number") {
|
|
137
|
+
return responseStatus;
|
|
138
|
+
}
|
|
139
|
+
if (typeof withCode.code === "number") {
|
|
140
|
+
return withCode.code;
|
|
141
|
+
}
|
|
142
|
+
return undefined;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const bodyFromError = (error: unknown): unknown => {
|
|
146
|
+
if (!error || typeof error !== "object") {
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
return (error as {response?: {body?: unknown}}).response?.body;
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
export class SendGridMailProvider implements MailProvider {
|
|
153
|
+
readonly id = "sendgrid";
|
|
154
|
+
private readonly client: SendGridClient;
|
|
155
|
+
private readonly fromEmail?: string;
|
|
156
|
+
private readonly fromName?: string;
|
|
157
|
+
private readonly sandboxMode: boolean;
|
|
158
|
+
|
|
159
|
+
constructor(options?: SendGridMailProviderOptions) {
|
|
160
|
+
const apiKey = resolveApiKey(options);
|
|
161
|
+
this.fromEmail = options?.fromEmail;
|
|
162
|
+
this.fromName = options?.fromName;
|
|
163
|
+
this.sandboxMode = options?.sandboxMode ?? process.env.NODE_ENV === "test";
|
|
164
|
+
|
|
165
|
+
if (options?.client) {
|
|
166
|
+
this.client = options.client;
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const sgMail = loadSendGridMail();
|
|
171
|
+
sgMail.setApiKey(apiKey);
|
|
172
|
+
this.client = sgMail;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async sendMail(message: MailMessage): Promise<SendResult> {
|
|
176
|
+
const fromEmail = this.fromEmail ?? message.from;
|
|
177
|
+
if (!fromEmail) {
|
|
178
|
+
return failedResult({
|
|
179
|
+
error: "SendGridMailProvider requires fromEmail or MailMessage.from",
|
|
180
|
+
errorClass: "config",
|
|
181
|
+
errorCode: "sendgrid-missing-from",
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const payload: Record<string, unknown> = {
|
|
186
|
+
from: this.fromName ? {email: fromEmail, name: this.fromName} : fromEmail,
|
|
187
|
+
subject: message.subject,
|
|
188
|
+
to: message.to,
|
|
189
|
+
...(message.html ? {html: message.html} : {}),
|
|
190
|
+
...(message.text ? {text: message.text} : {}),
|
|
191
|
+
...(message.replyTo ? {replyTo: message.replyTo} : {}),
|
|
192
|
+
...(message.templateId
|
|
193
|
+
? {
|
|
194
|
+
dynamicTemplateData: message.dynamicTemplateData ?? {},
|
|
195
|
+
templateId: message.templateId,
|
|
196
|
+
}
|
|
197
|
+
: {}),
|
|
198
|
+
...(this.sandboxMode ? {mailSettings: {sandboxMode: {enable: true}}} : {}),
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
try {
|
|
202
|
+
const [response] = await this.client.send(payload);
|
|
203
|
+
const providerMessageId = headerValue(response.headers, "x-message-id");
|
|
204
|
+
return {
|
|
205
|
+
accepted: true,
|
|
206
|
+
metadata: providerMessageId ? {consoleUrl: emailActivityUrl(providerMessageId)} : undefined,
|
|
207
|
+
providerMessageId,
|
|
208
|
+
};
|
|
209
|
+
} catch (error: unknown) {
|
|
210
|
+
const statusCode = statusFromError(error) ?? 500;
|
|
211
|
+
const body = bodyFromError(error);
|
|
212
|
+
const {errorClass, errorCode} = classifyHttpStatus(statusCode);
|
|
213
|
+
const errorMessage =
|
|
214
|
+
firstSendGridErrorMessage(body) ??
|
|
215
|
+
(error instanceof Error ? error.message : "SendGrid send failed");
|
|
216
|
+
return failedResult({
|
|
217
|
+
body,
|
|
218
|
+
error: errorMessage,
|
|
219
|
+
errorClass,
|
|
220
|
+
errorCode,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|