@adatechnology/email-provider 0.1.0-rc.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/README.md ADDED
@@ -0,0 +1,45 @@
1
+ # @adatechnology/email-provider
2
+
3
+ E-mail por **SMTP**, **Resend** ou **SES** atrás de uma porta só, mais os parsers de recibo
4
+ (bounce e complaint) de cada um. Stateless.
5
+
6
+ ## Instalação
7
+
8
+ ```bash
9
+ bun add @adatechnology/email-provider
10
+ ```
11
+
12
+ `nodemailer`, `resend` e `@aws-sdk/client-sesv2` são peers **opcionais** — instala-se só o do
13
+ provedor em uso.
14
+
15
+ ## Uso
16
+
17
+ ```ts
18
+ import { createEmailProvider } from '@adatechnology/email-provider'
19
+
20
+ const email = createEmailProvider({ driver: 'smtp', host, port, auth })
21
+ // ou 'resend' / 'ses'
22
+ ```
23
+
24
+ Diretos: `createSmtpEmailProvider`, `createResendEmailProvider`, `createSesEmailProvider`.
25
+
26
+ ## Recibos são metade do pacote
27
+
28
+ Enviar é a parte fácil. O que faz e-mail funcionar a longo prazo é **processar o retorno**: cada
29
+ provedor avisa bounce e complaint num formato próprio, e ignorar isso queima a reputação do
30
+ domínio até a entrega cair para todo mundo.
31
+
32
+ ```ts
33
+ const receipt = email.parseReceipt(webhookPayload)
34
+ // { type: 'bounce' | 'complaint' | 'delivered', target, isPermanent, reason }
35
+ ```
36
+
37
+ O módulo transforma bounce permanente e complaint em **supressão**, e para de tentar. Bounce
38
+ temporário (caixa cheia) não suprime — reenfileira.
39
+
40
+ A chave de supressão é o **hash HMAC** do endereço, nunca o endereço em claro: a lista existe para
41
+ não enviar, não para virar um cadastro de e-mails (`security.md` §1).
42
+
43
+ ## Licença
44
+
45
+ MIT © Ada Technology
package/dist/index.cjs ADDED
@@ -0,0 +1,408 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var index_exports = {};
33
+ __export(index_exports, {
34
+ createEmailProvider: () => createEmailProvider,
35
+ createResendEmailProvider: () => createResendEmailProvider,
36
+ createSesEmailProvider: () => createSesEmailProvider,
37
+ createSmtpEmailProvider: () => createSmtpEmailProvider,
38
+ parseResendWebhook: () => parseResendWebhook,
39
+ parseSesNotification: () => parseSesNotification
40
+ });
41
+ module.exports = __toCommonJS(index_exports);
42
+
43
+ // src/SmtpEmailProvider.ts
44
+ var import_notification_contracts = require("@adatechnology/notification-contracts");
45
+
46
+ // src/SmtpTransportClient.ts
47
+ function isSmtpError(error) {
48
+ return typeof error === "object" && error !== null;
49
+ }
50
+ __name(isSmtpError, "isSmtpError");
51
+
52
+ // src/SmtpEmailProvider.ts
53
+ var INVALID_TARGET_CODES = /* @__PURE__ */ new Set([
54
+ 550,
55
+ 551,
56
+ 553
57
+ ]);
58
+ function classifySmtpError(error) {
59
+ const responseCode = isSmtpError(error) ? error.responseCode : void 0;
60
+ if (responseCode === void 0) return {
61
+ outcome: "retriable",
62
+ errorCode: "smtp_unknown"
63
+ };
64
+ if (INVALID_TARGET_CODES.has(responseCode)) return {
65
+ outcome: "invalid_target",
66
+ errorCode: `smtp_${responseCode}`
67
+ };
68
+ if (responseCode >= 500) return {
69
+ outcome: "permanent",
70
+ errorCode: `smtp_${responseCode}`
71
+ };
72
+ if (responseCode >= 400) return {
73
+ outcome: "retriable",
74
+ errorCode: `smtp_${responseCode}`
75
+ };
76
+ return {
77
+ outcome: "permanent",
78
+ errorCode: `smtp_${responseCode}`
79
+ };
80
+ }
81
+ __name(classifySmtpError, "classifySmtpError");
82
+ async function initNodemailerTransport(config) {
83
+ if (!config.smtpUrl) throw new import_notification_contracts.ConfigMissingError("smtpUrl");
84
+ const nodemailer = await import("nodemailer");
85
+ return nodemailer.createTransport(config.smtpUrl);
86
+ }
87
+ __name(initNodemailerTransport, "initNodemailerTransport");
88
+ function createSmtpEmailProvider(config) {
89
+ let clientPromise;
90
+ function resolveClient() {
91
+ if (config.transportClient) return Promise.resolve(config.transportClient);
92
+ clientPromise ??= initNodemailerTransport(config);
93
+ return clientPromise;
94
+ }
95
+ __name(resolveClient, "resolveClient");
96
+ return {
97
+ driver: import_notification_contracts.EMAIL_DRIVER.SMTP,
98
+ async send(params) {
99
+ const client = await resolveClient();
100
+ try {
101
+ const result = await client.sendMail({
102
+ from: config.from,
103
+ to: params.to,
104
+ subject: params.subject,
105
+ html: params.html,
106
+ text: params.text,
107
+ replyTo: params.replyTo
108
+ });
109
+ if (result.accepted.length === 0 && result.rejected.length > 0) {
110
+ return {
111
+ outcome: "invalid_target",
112
+ errorCode: "smtp_rejected"
113
+ };
114
+ }
115
+ return {
116
+ outcome: "sent",
117
+ providerMessageId: result.messageId
118
+ };
119
+ } catch (error) {
120
+ return classifySmtpError(error);
121
+ }
122
+ }
123
+ };
124
+ }
125
+ __name(createSmtpEmailProvider, "createSmtpEmailProvider");
126
+
127
+ // src/ResendEmailProvider.ts
128
+ var import_notification_contracts2 = require("@adatechnology/notification-contracts");
129
+ var RETRIABLE_NAMES = /* @__PURE__ */ new Set([
130
+ "rate_limit_exceeded",
131
+ "monthly_quota_exceeded",
132
+ "daily_quota_exceeded",
133
+ "internal_server_error",
134
+ "application_error"
135
+ ]);
136
+ function classifyResendError(error) {
137
+ if (error.statusCode === 429 || error.statusCode !== null && error.statusCode >= 500) {
138
+ return {
139
+ outcome: "retriable",
140
+ errorCode: error.name
141
+ };
142
+ }
143
+ if (RETRIABLE_NAMES.has(error.name)) return {
144
+ outcome: "retriable",
145
+ errorCode: error.name
146
+ };
147
+ return {
148
+ outcome: "permanent",
149
+ errorCode: error.name
150
+ };
151
+ }
152
+ __name(classifyResendError, "classifyResendError");
153
+ async function initResendClient(config) {
154
+ if (!config.apiKey) throw new import_notification_contracts2.ConfigMissingError("apiKey");
155
+ const { Resend } = await import("resend");
156
+ return new Resend(config.apiKey);
157
+ }
158
+ __name(initResendClient, "initResendClient");
159
+ function createResendEmailProvider(config) {
160
+ let clientPromise;
161
+ function resolveClient() {
162
+ if (config.client) return Promise.resolve(config.client);
163
+ clientPromise ??= initResendClient(config);
164
+ return clientPromise;
165
+ }
166
+ __name(resolveClient, "resolveClient");
167
+ return {
168
+ driver: import_notification_contracts2.EMAIL_DRIVER.RESEND,
169
+ async send(params) {
170
+ const client = await resolveClient();
171
+ const result = await client.emails.send({
172
+ from: config.from,
173
+ to: params.to,
174
+ subject: params.subject,
175
+ html: params.html,
176
+ text: params.text,
177
+ replyTo: params.replyTo
178
+ });
179
+ if (result.error) return classifyResendError(result.error);
180
+ return {
181
+ outcome: "sent",
182
+ providerMessageId: result.data?.id
183
+ };
184
+ }
185
+ };
186
+ }
187
+ __name(createResendEmailProvider, "createResendEmailProvider");
188
+
189
+ // src/SesEmailProvider.ts
190
+ var import_notification_contracts3 = require("@adatechnology/notification-contracts");
191
+
192
+ // src/SesSendClient.ts
193
+ function isSesError(error) {
194
+ return typeof error === "object" && error !== null && "name" in error && typeof error.name === "string";
195
+ }
196
+ __name(isSesError, "isSesError");
197
+
198
+ // src/SesEmailProvider.ts
199
+ var RETRIABLE_NAMES2 = /* @__PURE__ */ new Set([
200
+ "TooManyRequestsException",
201
+ "LimitExceededException",
202
+ "InternalServiceErrorException",
203
+ "ConcurrentModificationException"
204
+ ]);
205
+ function classifySesError(error) {
206
+ if (!isSesError(error)) return {
207
+ outcome: "retriable",
208
+ errorCode: "ses_unknown"
209
+ };
210
+ if (RETRIABLE_NAMES2.has(error.name)) return {
211
+ outcome: "retriable",
212
+ errorCode: error.name
213
+ };
214
+ return {
215
+ outcome: "permanent",
216
+ errorCode: error.name
217
+ };
218
+ }
219
+ __name(classifySesError, "classifySesError");
220
+ async function initSesClient(config) {
221
+ if (!config.region) throw new import_notification_contracts3.ConfigMissingError("region");
222
+ const { SESv2Client, SendEmailCommand } = await import("@aws-sdk/client-sesv2");
223
+ const sesClient = new SESv2Client({
224
+ region: config.region
225
+ });
226
+ return {
227
+ async sendEmail(params) {
228
+ const response = await sesClient.send(new SendEmailCommand({
229
+ FromEmailAddress: params.from,
230
+ Destination: {
231
+ ToAddresses: [
232
+ params.to
233
+ ]
234
+ },
235
+ ReplyToAddresses: params.replyTo ? [
236
+ params.replyTo
237
+ ] : void 0,
238
+ Content: {
239
+ Simple: {
240
+ Subject: {
241
+ Data: params.subject
242
+ },
243
+ Body: {
244
+ Html: {
245
+ Data: params.html
246
+ },
247
+ Text: {
248
+ Data: params.text
249
+ }
250
+ }
251
+ }
252
+ }
253
+ }));
254
+ return {
255
+ messageId: response.MessageId
256
+ };
257
+ }
258
+ };
259
+ }
260
+ __name(initSesClient, "initSesClient");
261
+ function createSesEmailProvider(config) {
262
+ let clientPromise;
263
+ function resolveClient() {
264
+ if (config.client) return Promise.resolve(config.client);
265
+ clientPromise ??= initSesClient(config);
266
+ return clientPromise;
267
+ }
268
+ __name(resolveClient, "resolveClient");
269
+ return {
270
+ driver: import_notification_contracts3.EMAIL_DRIVER.SES,
271
+ async send(params) {
272
+ const client = await resolveClient();
273
+ try {
274
+ const result = await client.sendEmail({
275
+ from: config.from,
276
+ to: params.to,
277
+ subject: params.subject,
278
+ html: params.html,
279
+ text: params.text,
280
+ replyTo: params.replyTo
281
+ });
282
+ return {
283
+ outcome: "sent",
284
+ providerMessageId: result.messageId
285
+ };
286
+ } catch (error) {
287
+ return classifySesError(error);
288
+ }
289
+ }
290
+ };
291
+ }
292
+ __name(createSesEmailProvider, "createSesEmailProvider");
293
+
294
+ // src/EmailProviderFactory.ts
295
+ var import_notification_contracts4 = require("@adatechnology/notification-contracts");
296
+ function createEmailProvider(params) {
297
+ if (params.driver === import_notification_contracts4.EMAIL_DRIVER.SMTP) return createSmtpEmailProvider(params);
298
+ if (params.driver === import_notification_contracts4.EMAIL_DRIVER.RESEND) return createResendEmailProvider(params);
299
+ if (params.driver === import_notification_contracts4.EMAIL_DRIVER.SES) return createSesEmailProvider(params);
300
+ const _exhaustive = params;
301
+ throw new Error(`Driver de e-mail desconhecido: ${String(_exhaustive.driver)}`);
302
+ }
303
+ __name(createEmailProvider, "createEmailProvider");
304
+
305
+ // src/receipts/parseResendWebhook.ts
306
+ var import_notification_contracts5 = require("@adatechnology/notification-contracts");
307
+ function isResendWebhookPayload(value) {
308
+ if (typeof value !== "object" || value === null) return false;
309
+ const candidate = value;
310
+ if (typeof candidate.type !== "string" || typeof candidate.created_at !== "string") return false;
311
+ const data = candidate.data;
312
+ return typeof data?.email_id === "string";
313
+ }
314
+ __name(isResendWebhookPayload, "isResendWebhookPayload");
315
+ function parseResendWebhook(payload) {
316
+ if (!isResendWebhookPayload(payload)) return void 0;
317
+ const occurredAt = new Date(payload.created_at);
318
+ const providerMessageId = payload.data.email_id;
319
+ if (payload.type === "email.delivered") {
320
+ return {
321
+ providerMessageId,
322
+ status: "delivered",
323
+ occurredAt
324
+ };
325
+ }
326
+ if (payload.type === "email.bounced") {
327
+ const errorCode = payload.data.bounce?.subType ?? payload.data.bounce?.type;
328
+ return {
329
+ providerMessageId,
330
+ status: "bounced",
331
+ suppressionReason: import_notification_contracts5.SUPPRESSION_REASON.BOUNCE,
332
+ errorCode,
333
+ occurredAt
334
+ };
335
+ }
336
+ if (payload.type === "email.complained") {
337
+ return {
338
+ providerMessageId,
339
+ status: "failed",
340
+ suppressionReason: import_notification_contracts5.SUPPRESSION_REASON.COMPLAINT,
341
+ occurredAt
342
+ };
343
+ }
344
+ return void 0;
345
+ }
346
+ __name(parseResendWebhook, "parseResendWebhook");
347
+
348
+ // src/receipts/parseSesNotification.ts
349
+ var import_notification_contracts6 = require("@adatechnology/notification-contracts");
350
+ function parseJson(text) {
351
+ try {
352
+ return JSON.parse(text);
353
+ } catch {
354
+ return void 0;
355
+ }
356
+ }
357
+ __name(parseJson, "parseJson");
358
+ function isSesEventMessage(value) {
359
+ if (typeof value !== "object" || value === null) return false;
360
+ const candidate = value;
361
+ const mail = candidate.mail;
362
+ return (candidate.notificationType === "Bounce" || candidate.notificationType === "Complaint" || candidate.notificationType === "Delivery") && typeof mail?.messageId === "string";
363
+ }
364
+ __name(isSesEventMessage, "isSesEventMessage");
365
+ function parseSesNotification(rawBody) {
366
+ const envelope = parseJson(rawBody);
367
+ if (envelope?.Type !== "Notification" || typeof envelope.Message !== "string") return void 0;
368
+ const event = parseJson(envelope.Message);
369
+ if (!isSesEventMessage(event)) return void 0;
370
+ const providerMessageId = event.mail.messageId;
371
+ if (event.notificationType === "Delivery" && event.delivery) {
372
+ return {
373
+ providerMessageId,
374
+ status: "delivered",
375
+ occurredAt: new Date(event.delivery.timestamp)
376
+ };
377
+ }
378
+ if (event.notificationType === "Bounce" && event.bounce) {
379
+ return {
380
+ providerMessageId,
381
+ status: "bounced",
382
+ suppressionReason: import_notification_contracts6.SUPPRESSION_REASON.BOUNCE,
383
+ errorCode: `${event.bounce.bounceType}/${event.bounce.bounceSubType}`,
384
+ occurredAt: new Date(event.bounce.timestamp)
385
+ };
386
+ }
387
+ if (event.notificationType === "Complaint" && event.complaint) {
388
+ return {
389
+ providerMessageId,
390
+ status: "failed",
391
+ suppressionReason: import_notification_contracts6.SUPPRESSION_REASON.COMPLAINT,
392
+ errorCode: event.complaint.complaintFeedbackType,
393
+ occurredAt: new Date(event.complaint.timestamp)
394
+ };
395
+ }
396
+ return void 0;
397
+ }
398
+ __name(parseSesNotification, "parseSesNotification");
399
+ // Annotate the CommonJS export names for ESM import in node:
400
+ 0 && (module.exports = {
401
+ createEmailProvider,
402
+ createResendEmailProvider,
403
+ createSesEmailProvider,
404
+ createSmtpEmailProvider,
405
+ parseResendWebhook,
406
+ parseSesNotification
407
+ });
408
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/SmtpEmailProvider.ts","../src/SmtpTransportClient.ts","../src/ResendEmailProvider.ts","../src/SesEmailProvider.ts","../src/SesSendClient.ts","../src/EmailProviderFactory.ts","../src/receipts/parseResendWebhook.ts","../src/receipts/parseSesNotification.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport { createSmtpEmailProvider } from './SmtpEmailProvider'\nexport type { SmtpEmailProviderConfig } from './SmtpEmailProvider'\nexport type { SmtpMailMessage, SmtpSendResult, SmtpTransportClient, SmtpError } from './SmtpTransportClient'\n\nexport { createResendEmailProvider } from './ResendEmailProvider'\nexport type { ResendEmailProviderConfig } from './ResendEmailProvider'\nexport type { ResendClientLike, ResendEmailsClient, ResendSendResult } from './ResendClient'\n\nexport { createSesEmailProvider } from './SesEmailProvider'\nexport type { SesEmailProviderConfig } from './SesEmailProvider'\nexport type { SesSendClient, SesSendParams, SesSendResult, SesError } from './SesSendClient'\n\nexport { createEmailProvider } from './EmailProviderFactory'\nexport type { CreateEmailProviderParams } from './EmailProviderFactory'\n\nexport { parseResendWebhook } from './receipts/parseResendWebhook'\nexport { parseSesNotification } from './receipts/parseSesNotification'\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { ConfigMissingError, EMAIL_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, EmailDriverPort, SendEmailParams } from '@adatechnology/notification-contracts'\n\nimport { isSmtpError, type SmtpTransportClient } from './SmtpTransportClient'\n\nexport type SmtpEmailProviderConfig = {\n readonly from: string\n /**\n * URL de conexão (`smtps://user:pass@host:port`). Em dev aponta para o Mailpit do\n * `docker-compose.yml` da raiz — e-mail nunca sai da máquina e é inspecionável.\n */\n readonly smtpUrl?: string\n /** Injeção de teste — presente, o `nodemailer` real nunca é importado. */\n readonly transportClient?: SmtpTransportClient\n}\n\n// Códigos de \"usuário desconhecido\" — o mais próximo que o SMTP tem de \"apaga o token\" do push.\nconst INVALID_TARGET_CODES = new Set([550, 551, 553])\n\nfunction classifySmtpError(error: unknown): DeliveryAttemptResult {\n const responseCode = isSmtpError(error) ? error.responseCode : undefined\n if (responseCode === undefined) return { outcome: 'retriable', errorCode: 'smtp_unknown' }\n if (INVALID_TARGET_CODES.has(responseCode)) return { outcome: 'invalid_target', errorCode: `smtp_${responseCode}` }\n if (responseCode >= 500) return { outcome: 'permanent', errorCode: `smtp_${responseCode}` }\n if (responseCode >= 400) return { outcome: 'retriable', errorCode: `smtp_${responseCode}` }\n return { outcome: 'permanent', errorCode: `smtp_${responseCode}` }\n}\n\nasync function initNodemailerTransport(config: SmtpEmailProviderConfig): Promise<SmtpTransportClient> {\n if (!config.smtpUrl) throw new ConfigMissingError('smtpUrl')\n\n const nodemailer = await import('nodemailer')\n return nodemailer.createTransport(config.smtpUrl)\n}\n\nexport function createSmtpEmailProvider(config: SmtpEmailProviderConfig): EmailDriverPort {\n let clientPromise: Promise<SmtpTransportClient> | undefined\n\n function resolveClient(): Promise<SmtpTransportClient> {\n if (config.transportClient) return Promise.resolve(config.transportClient)\n clientPromise ??= initNodemailerTransport(config)\n return clientPromise\n }\n\n return {\n driver: EMAIL_DRIVER.SMTP,\n async send(params: SendEmailParams): Promise<DeliveryAttemptResult> {\n const client = await resolveClient()\n try {\n const result = await client.sendMail({\n from: config.from,\n to: params.to,\n subject: params.subject,\n html: params.html,\n text: params.text,\n replyTo: params.replyTo,\n })\n\n // Servidor aceitou a conexão mas rejeitou o destinatário sem lançar erro — mesmo sinal de\n // endereço morto que um 550 lançado como exceção.\n if (result.accepted.length === 0 && result.rejected.length > 0) {\n return { outcome: 'invalid_target', errorCode: 'smtp_rejected' }\n }\n\n return { outcome: 'sent', providerMessageId: result.messageId }\n } catch (error) {\n return classifySmtpError(error)\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * Forma mínima que o `Transporter` do `nodemailer` já satisfaz. Declarada por estrutura — não\n * importada do pacote — para os testes injetarem um dublê sem carregar o SDK real.\n */\nexport type SmtpMailMessage = {\n readonly from: string\n readonly to: string\n readonly subject: string\n readonly html: string\n readonly text: string\n readonly replyTo?: string\n}\n\nexport type SmtpSendResult = {\n readonly messageId: string\n readonly accepted: readonly unknown[]\n readonly rejected: readonly unknown[]\n}\n\nexport type SmtpTransportClient = {\n sendMail(message: SmtpMailMessage): Promise<SmtpSendResult>\n}\n\nexport type SmtpError = {\n /** Código de resposta SMTP (RFC 5321): 4xx é transitório, 5xx é permanente. */\n readonly responseCode?: number\n readonly message?: string\n}\n\nexport function isSmtpError(error: unknown): error is SmtpError {\n return typeof error === 'object' && error !== null\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { ConfigMissingError, EMAIL_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, EmailDriverPort, SendEmailParams } from '@adatechnology/notification-contracts'\n\nimport type { ResendClientLike, ResendSendResult } from './ResendClient'\n\nexport type ResendEmailProviderConfig = {\n readonly from: string\n readonly apiKey?: string\n /** Injeção de teste — presente, o `resend` real nunca é importado. */\n readonly client?: ResendClientLike\n}\n\n// error.name documentado pela Resend (RESEND_ERROR_CODE_KEY). Sem sinal de \"endereço não existe\"\n// — bounce é sempre assíncrono, via webhook (spec §11, \"delivered é assimétrico\").\nconst RETRIABLE_NAMES = new Set([\n 'rate_limit_exceeded',\n 'monthly_quota_exceeded',\n 'daily_quota_exceeded',\n 'internal_server_error',\n 'application_error',\n])\n\nfunction classifyResendError(error: NonNullable<ResendSendResult['error']>): DeliveryAttemptResult {\n if (error.statusCode === 429 || (error.statusCode !== null && error.statusCode >= 500)) {\n return { outcome: 'retriable', errorCode: error.name }\n }\n if (RETRIABLE_NAMES.has(error.name)) return { outcome: 'retriable', errorCode: error.name }\n return { outcome: 'permanent', errorCode: error.name }\n}\n\nasync function initResendClient(config: ResendEmailProviderConfig): Promise<ResendClientLike> {\n if (!config.apiKey) throw new ConfigMissingError('apiKey')\n\n const { Resend } = await import('resend')\n return new Resend(config.apiKey)\n}\n\nexport function createResendEmailProvider(config: ResendEmailProviderConfig): EmailDriverPort {\n let clientPromise: Promise<ResendClientLike> | undefined\n\n function resolveClient(): Promise<ResendClientLike> {\n if (config.client) return Promise.resolve(config.client)\n clientPromise ??= initResendClient(config)\n return clientPromise\n }\n\n return {\n driver: EMAIL_DRIVER.RESEND,\n async send(params: SendEmailParams): Promise<DeliveryAttemptResult> {\n const client = await resolveClient()\n const result = await client.emails.send({\n from: config.from,\n to: params.to,\n subject: params.subject,\n html: params.html,\n text: params.text,\n replyTo: params.replyTo,\n })\n\n if (result.error) return classifyResendError(result.error)\n return { outcome: 'sent', providerMessageId: result.data?.id }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { ConfigMissingError, EMAIL_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, EmailDriverPort, SendEmailParams } from '@adatechnology/notification-contracts'\n\nimport { isSesError, type SesSendClient } from './SesSendClient'\n\nexport type SesEmailProviderConfig = {\n readonly from: string\n readonly region?: string\n /** Injeção de teste — presente, o `@aws-sdk/client-sesv2` real nunca é importado. */\n readonly client?: SesSendClient\n}\n\n// SESv2ServiceException.name — só o que muda a decisão de retry.\nconst RETRIABLE_NAMES = new Set([\n 'TooManyRequestsException',\n 'LimitExceededException',\n 'InternalServiceErrorException',\n 'ConcurrentModificationException',\n])\n\nfunction classifySesError(error: unknown): DeliveryAttemptResult {\n if (!isSesError(error)) return { outcome: 'retriable', errorCode: 'ses_unknown' }\n if (RETRIABLE_NAMES.has(error.name)) return { outcome: 'retriable', errorCode: error.name }\n return { outcome: 'permanent', errorCode: error.name }\n}\n\nasync function initSesClient(config: SesEmailProviderConfig): Promise<SesSendClient> {\n if (!config.region) throw new ConfigMissingError('region')\n\n const { SESv2Client, SendEmailCommand } = await import('@aws-sdk/client-sesv2')\n const sesClient = new SESv2Client({ region: config.region })\n\n return {\n async sendEmail(params) {\n const response = await sesClient.send(\n new SendEmailCommand({\n FromEmailAddress: params.from,\n Destination: { ToAddresses: [params.to] },\n ReplyToAddresses: params.replyTo ? [params.replyTo] : undefined,\n Content: {\n Simple: {\n Subject: { Data: params.subject },\n Body: { Html: { Data: params.html }, Text: { Data: params.text } },\n },\n },\n }),\n )\n return { messageId: response.MessageId }\n },\n }\n}\n\nexport function createSesEmailProvider(config: SesEmailProviderConfig): EmailDriverPort {\n let clientPromise: Promise<SesSendClient> | undefined\n\n function resolveClient(): Promise<SesSendClient> {\n if (config.client) return Promise.resolve(config.client)\n clientPromise ??= initSesClient(config)\n return clientPromise\n }\n\n return {\n driver: EMAIL_DRIVER.SES,\n async send(params: SendEmailParams): Promise<DeliveryAttemptResult> {\n const client = await resolveClient()\n try {\n const result = await client.sendEmail({\n from: config.from,\n to: params.to,\n subject: params.subject,\n html: params.html,\n text: params.text,\n replyTo: params.replyTo,\n })\n return { outcome: 'sent', providerMessageId: result.messageId }\n } catch (error) {\n return classifySesError(error)\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * Forma própria, não a do `@aws-sdk/client-sesv2` — os testes injetam este dublê sem carregar o\n * SDK real, e a versão exata do SDK do consumidor não vaza para a superfície pública do pacote.\n */\nexport type SesSendParams = {\n readonly from: string\n readonly to: string\n readonly subject: string\n readonly html: string\n readonly text: string\n readonly replyTo?: string\n}\n\nexport type SesSendResult = {\n readonly messageId?: string\n}\n\nexport type SesSendClient = {\n sendEmail(params: SesSendParams): Promise<SesSendResult>\n}\n\nexport type SesError = {\n readonly name: string\n}\n\nexport function isSesError(error: unknown): error is SesError {\n return typeof error === 'object' && error !== null && 'name' in error && typeof (error as SesError).name === 'string'\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { EMAIL_DRIVER } from '@adatechnology/notification-contracts'\nimport type { EmailDriverPort } from '@adatechnology/notification-contracts'\n\nimport { createResendEmailProvider, type ResendEmailProviderConfig } from './ResendEmailProvider'\nimport { createSesEmailProvider, type SesEmailProviderConfig } from './SesEmailProvider'\nimport { createSmtpEmailProvider, type SmtpEmailProviderConfig } from './SmtpEmailProvider'\n\nexport type CreateEmailProviderParams =\n | ({ readonly driver: typeof EMAIL_DRIVER.SMTP } & SmtpEmailProviderConfig)\n | ({ readonly driver: typeof EMAIL_DRIVER.RESEND } & ResendEmailProviderConfig)\n | ({ readonly driver: typeof EMAIL_DRIVER.SES } & SesEmailProviderConfig)\n\nexport function createEmailProvider(params: CreateEmailProviderParams): EmailDriverPort {\n if (params.driver === EMAIL_DRIVER.SMTP) return createSmtpEmailProvider(params)\n if (params.driver === EMAIL_DRIVER.RESEND) return createResendEmailProvider(params)\n if (params.driver === EMAIL_DRIVER.SES) return createSesEmailProvider(params)\n\n const _exhaustive: never = params\n throw new Error(`Driver de e-mail desconhecido: ${String((_exhaustive as { driver?: unknown }).driver)}`)\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { SUPPRESSION_REASON } from '@adatechnology/notification-contracts'\nimport type { DeliveryReceipt } from '@adatechnology/notification-contracts'\n\n/**\n * Formato documentado do webhook da Resend (`WebhookEvent`), reproduzido aqui por estrutura em\n * vez de importado do SDK — este arquivo só faz parsing de JSON, não precisa do cliente.\n */\ntype ResendWebhookPayload = {\n readonly type: string\n readonly created_at: string\n readonly data: {\n readonly email_id: string\n readonly bounce?: { readonly type?: string; readonly subType?: string }\n }\n}\n\nfunction isResendWebhookPayload(value: unknown): value is ResendWebhookPayload {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n if (typeof candidate.type !== 'string' || typeof candidate.created_at !== 'string') return false\n const data = candidate.data as Record<string, unknown> | undefined\n return typeof data?.email_id === 'string'\n}\n\n/**\n * Traduz o evento assinado da Resend para o recibo normalizado do módulo. A verificação de\n * assinatura HMAC acontece **antes** desta função, sobre o `rawBody` — este parser já recebe o\n * JSON confiável.\n *\n * Devolve `undefined` para eventos que não mudam o estado de uma entrega (`email.sent`,\n * `email.opened`, `email.clicked`, ...) — o módulo simplesmente ignora o webhook.\n */\nexport function parseResendWebhook(payload: unknown): DeliveryReceipt | undefined {\n if (!isResendWebhookPayload(payload)) return undefined\n\n const occurredAt = new Date(payload.created_at)\n const providerMessageId = payload.data.email_id\n\n if (payload.type === 'email.delivered') {\n return { providerMessageId, status: 'delivered', occurredAt }\n }\n\n if (payload.type === 'email.bounced') {\n const errorCode = payload.data.bounce?.subType ?? payload.data.bounce?.type\n return { providerMessageId, status: 'bounced', suppressionReason: SUPPRESSION_REASON.BOUNCE, errorCode, occurredAt }\n }\n\n if (payload.type === 'email.complained') {\n return { providerMessageId, status: 'failed', suppressionReason: SUPPRESSION_REASON.COMPLAINT, occurredAt }\n }\n\n return undefined\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { SUPPRESSION_REASON } from '@adatechnology/notification-contracts'\nimport type { DeliveryReceipt } from '@adatechnology/notification-contracts'\n\n/**\n * SES publica bounce/complaint/delivery via SNS: o corpo do POST é o envelope da SNS\n * (`Type`, `Message`), e `Message` é uma STRING com o evento da SES serializado dentro. Dois\n * `JSON.parse` em sequência, não um só — é a causa mais comum de parser de SES quebrado.\n *\n * A verificação da assinatura da SNS (certificado X.509, separada do HMAC do módulo) é\n * responsabilidade de quem expõe a rota; esta função só traduz o payload já autenticado.\n */\ntype SesEventMessage = {\n readonly notificationType: 'Bounce' | 'Complaint' | 'Delivery'\n readonly mail: { readonly messageId: string }\n readonly bounce?: { readonly bounceType: string; readonly bounceSubType: string; readonly timestamp: string }\n readonly complaint?: { readonly complaintFeedbackType?: string; readonly timestamp: string }\n readonly delivery?: { readonly timestamp: string }\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return undefined\n }\n}\n\nfunction isSesEventMessage(value: unknown): value is SesEventMessage {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n const mail = candidate.mail as Record<string, unknown> | undefined\n return (\n (candidate.notificationType === 'Bounce' ||\n candidate.notificationType === 'Complaint' ||\n candidate.notificationType === 'Delivery') &&\n typeof mail?.messageId === 'string'\n )\n}\n\n/** `undefined` para envelope malformado, confirmação de assinatura da SNS, ou tipo desconhecido. */\nexport function parseSesNotification(rawBody: string): DeliveryReceipt | undefined {\n const envelope = parseJson(rawBody) as { readonly Type?: string; readonly Message?: string } | undefined\n if (envelope?.Type !== 'Notification' || typeof envelope.Message !== 'string') return undefined\n\n const event = parseJson(envelope.Message)\n if (!isSesEventMessage(event)) return undefined\n\n const providerMessageId = event.mail.messageId\n\n if (event.notificationType === 'Delivery' && event.delivery) {\n return { providerMessageId, status: 'delivered', occurredAt: new Date(event.delivery.timestamp) }\n }\n\n if (event.notificationType === 'Bounce' && event.bounce) {\n return {\n providerMessageId,\n status: 'bounced',\n suppressionReason: SUPPRESSION_REASON.BOUNCE,\n errorCode: `${event.bounce.bounceType}/${event.bounce.bounceSubType}`,\n occurredAt: new Date(event.bounce.timestamp),\n }\n }\n\n if (event.notificationType === 'Complaint' && event.complaint) {\n return {\n providerMessageId,\n status: 'failed',\n suppressionReason: SUPPRESSION_REASON.COMPLAINT,\n errorCode: event.complaint.complaintFeedbackType,\n occurredAt: new Date(event.complaint.timestamp),\n }\n }\n\n return undefined\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;ACIA,oCAAiD;;;AC6B1C,SAASA,YAAYC,OAAc;AACxC,SAAO,OAAOA,UAAU,YAAYA,UAAU;AAChD;AAFgBD;;;ADZhB,IAAME,uBAAuB,oBAAIC,IAAI;EAAC;EAAK;EAAK;CAAI;AAEpD,SAASC,kBAAkBC,OAAc;AACvC,QAAMC,eAAeC,YAAYF,KAAAA,IAASA,MAAMC,eAAeE;AAC/D,MAAIF,iBAAiBE,OAAW,QAAO;IAAEC,SAAS;IAAaC,WAAW;EAAe;AACzF,MAAIR,qBAAqBS,IAAIL,YAAAA,EAAe,QAAO;IAAEG,SAAS;IAAkBC,WAAW,QAAQJ,YAAAA;EAAe;AAClH,MAAIA,gBAAgB,IAAK,QAAO;IAAEG,SAAS;IAAaC,WAAW,QAAQJ,YAAAA;EAAe;AAC1F,MAAIA,gBAAgB,IAAK,QAAO;IAAEG,SAAS;IAAaC,WAAW,QAAQJ,YAAAA;EAAe;AAC1F,SAAO;IAAEG,SAAS;IAAaC,WAAW,QAAQJ,YAAAA;EAAe;AACnE;AAPSF;AAST,eAAeQ,wBAAwBC,QAA+B;AACpE,MAAI,CAACA,OAAOC,QAAS,OAAM,IAAIC,iDAAmB,SAAA;AAElD,QAAMC,aAAa,MAAM,OAAO,YAAA;AAChC,SAAOA,WAAWC,gBAAgBJ,OAAOC,OAAO;AAClD;AALeF;AAOR,SAASM,wBAAwBL,QAA+B;AACrE,MAAIM;AAEJ,WAASC,gBAAAA;AACP,QAAIP,OAAOQ,gBAAiB,QAAOC,QAAQC,QAAQV,OAAOQ,eAAe;AACzEF,sBAAkBP,wBAAwBC,MAAAA;A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AAMF,IAAAA;EACpB,QAAQ;AACN,WAAOG;EACT;AACF;AANSJ;AAQT,SAASK,kBAAkBC,OAAc;AACvC,MAAI,OAAOA,UAAU,YAAYA,UAAU,KAAM,QAAO;AACxD,QAAMC,YAAYD;AAClB,QAAME,OAAOD,UAAUC;AACvB,UACGD,UAAUE,qBAAqB,YAC9BF,UAAUE,qBAAqB,eAC/BF,UAAUE,qBAAqB,eACjC,OAAOD,MAAME,cAAc;AAE/B;AAVSL;AAaF,SAASM,qBAAqBC,SAAe;AAClD,QAAMC,WAAWb,UAAUY,OAAAA;AAC3B,MAAIC,UAAUC,SAAS,kBAAkB,OAAOD,SAASE,YAAY,SAAU,QAAOX;AAEtF,QAAMY,QAAQhB,UAAUa,SAASE,OAAO;AACxC,MAAI,CAACV,kBAAkBW,KAAAA,EAAQ,QAAOZ;AAEtC,QAAMa,oBAAoBD,MAAMR,KAAKE;AAErC,MAAIM,MAAMP,qBAAqB,cAAcO,MAAME,UAAU;AAC3D,WAAO;MAAED;MAAmBE,QAAQ;MAAaC,YAAY,IAAIC,KAAKL,MAAME,SAASI,SAAS;IAAE;EAClG;AAEA,MAAIN,MAAMP,qBAAqB,YAAYO,MAAMO,QAAQ;AACvD,WAAO;MACLN;MACAE,QAAQ;MACRK,mBAAmBC,kDAAmBC;MACtCC,WAAW,GAAGX,MAAMO,OAAOK,UAAU,IAAIZ,MAAMO,OAAOM,aAAa;MACnET,YAAY,IAAIC,KAAKL,MAAMO,OAAOD,SAAS;IAC7C;EACF;AAEA,MAAIN,MAAMP,qBAAqB,eAAeO,MAAMc,WAAW;AAC7D,WAAO;MACLb;MACAE,QAAQ;MACRK,mBAAmBC,kDAAmBM;MACtCJ,WAAWX,MAAMc,UAAUE;MAC3BZ,YAAY,IAAIC,KAAKL,MAAMc,UAAUR,SAAS;IAChD;EACF;AAEA,SAAOlB;AACT;AAlCgBO;","names":["isSmtpError","error","INVALID_TARGET_CODES","Set","classifySmtpError","error","responseCode","isSmtpError","undefined","outcome","errorCode","has","initNodemailerTransport","config","smtpUrl","ConfigMissingError","nodemailer","createTransport","createSmtpEmailProvider","clientPromise","resolveClient","transportClient","Promise","resolve","driver","EMAIL_DRIVER","SMTP","send","params","client","result","sendMail","from","to","subject","html","text","replyTo","accepted","length","rejected","providerMessageId","messageId","import_notification_contracts","RETRIABLE_NAMES","Set","classifyResendError","error","statusCode","outcome","errorCode","name","has","initResendClient","config","apiKey","ConfigMissingError","Resend","createResendEmailProvider","clientPromise","resolveClient","client","Promise","resolve","driver","EMAIL_DRIVER","RESEND","send","params","result","emails","from","to","subject","html","text","replyTo","providerMessageId","data","id","import_notification_contracts","isSesError","error","name","RETRIABLE_NAMES","Set","classifySesError","error","isSesError","outcome","errorCode","has","name","initSesClient","config","region","ConfigMissingError","SESv2Client","SendEmailCommand","sesClient","sendEmail","params","response","send","FromEmailAddress","from","Destination","ToAddresses","to","ReplyToAddresses","replyTo","undefined","Content","Simple","Subject","Data","subject","Body","Html","html","Text","text","messageId","MessageId","createSesEmailProvider","clientPromise","resolveClient","client","Promise","resolve","driver","EMAIL_DRIVER","SES","result","providerMessageId","import_notification_contracts","createEmailProvider","params","driver","EMAIL_DRIVER","SMTP","createSmtpEmailProvider","RESEND","createResendEmailProvider","SES","createSesEmailProvider","_exhaustive","Error","String","import_notification_contracts","isResendWebhookPayload","value","candidate","type","created_at","data","email_id","parseResendWebhook","payload","undefined","occurredAt","Date","providerMessageId","status","errorCode","bounce","subType","suppressionReason","SUPPRESSION_REASON","BOUNCE","COMPLAINT","import_notification_contracts","parseJson","text","JSON","parse","undefined","isSesEventMessage","value","candidate","mail","notificationType","messageId","parseSesNotification","rawBody","envelope","Type","Message","event","providerMessageId","delivery","status","occurredAt","Date","timestamp","bounce","suppressionReason","SUPPRESSION_REASON","BOUNCE","errorCode","bounceType","bounceSubType","complaint","COMPLAINT","complaintFeedbackType"]}
@@ -0,0 +1,162 @@
1
+ import { EmailDriverPort, EMAIL_DRIVER, DeliveryReceipt } from '@adatechnology/notification-contracts';
2
+
3
+ /**
4
+ * Copyright (c) 2026 Ada Technology. MIT License.
5
+ */
6
+ /**
7
+ * Forma mínima que o `Transporter` do `nodemailer` já satisfaz. Declarada por estrutura — não
8
+ * importada do pacote — para os testes injetarem um dublê sem carregar o SDK real.
9
+ */
10
+ type SmtpMailMessage = {
11
+ readonly from: string;
12
+ readonly to: string;
13
+ readonly subject: string;
14
+ readonly html: string;
15
+ readonly text: string;
16
+ readonly replyTo?: string;
17
+ };
18
+ type SmtpSendResult = {
19
+ readonly messageId: string;
20
+ readonly accepted: readonly unknown[];
21
+ readonly rejected: readonly unknown[];
22
+ };
23
+ type SmtpTransportClient = {
24
+ sendMail(message: SmtpMailMessage): Promise<SmtpSendResult>;
25
+ };
26
+ type SmtpError = {
27
+ /** Código de resposta SMTP (RFC 5321): 4xx é transitório, 5xx é permanente. */
28
+ readonly responseCode?: number;
29
+ readonly message?: string;
30
+ };
31
+
32
+ /**
33
+ * Copyright (c) 2026 Ada Technology. MIT License.
34
+ */
35
+
36
+ type SmtpEmailProviderConfig = {
37
+ readonly from: string;
38
+ /**
39
+ * URL de conexão (`smtps://user:pass@host:port`). Em dev aponta para o Mailpit do
40
+ * `docker-compose.yml` da raiz — e-mail nunca sai da máquina e é inspecionável.
41
+ */
42
+ readonly smtpUrl?: string;
43
+ /** Injeção de teste — presente, o `nodemailer` real nunca é importado. */
44
+ readonly transportClient?: SmtpTransportClient;
45
+ };
46
+ declare function createSmtpEmailProvider(config: SmtpEmailProviderConfig): EmailDriverPort;
47
+
48
+ /**
49
+ * Copyright (c) 2026 Ada Technology. MIT License.
50
+ */
51
+ /**
52
+ * Forma mínima que `new Resend(apiKey).emails` já satisfaz. O SDK do Resend não lança em erro de
53
+ * negócio — devolve `{ data, error }` — então a classificação lê `error.name`, nunca uma exceção.
54
+ */
55
+ type ResendSendResult = {
56
+ readonly data: {
57
+ readonly id: string;
58
+ } | null;
59
+ readonly error: {
60
+ readonly name: string;
61
+ readonly message: string;
62
+ readonly statusCode: number | null;
63
+ } | null;
64
+ };
65
+ type ResendEmailsClient = {
66
+ send(message: {
67
+ readonly from: string;
68
+ readonly to: string;
69
+ readonly subject: string;
70
+ readonly html: string;
71
+ readonly text: string;
72
+ readonly replyTo?: string;
73
+ }): Promise<ResendSendResult>;
74
+ };
75
+ type ResendClientLike = {
76
+ readonly emails: ResendEmailsClient;
77
+ };
78
+
79
+ /**
80
+ * Copyright (c) 2026 Ada Technology. MIT License.
81
+ */
82
+
83
+ type ResendEmailProviderConfig = {
84
+ readonly from: string;
85
+ readonly apiKey?: string;
86
+ /** Injeção de teste — presente, o `resend` real nunca é importado. */
87
+ readonly client?: ResendClientLike;
88
+ };
89
+ declare function createResendEmailProvider(config: ResendEmailProviderConfig): EmailDriverPort;
90
+
91
+ /**
92
+ * Copyright (c) 2026 Ada Technology. MIT License.
93
+ */
94
+ /**
95
+ * Forma própria, não a do `@aws-sdk/client-sesv2` — os testes injetam este dublê sem carregar o
96
+ * SDK real, e a versão exata do SDK do consumidor não vaza para a superfície pública do pacote.
97
+ */
98
+ type SesSendParams = {
99
+ readonly from: string;
100
+ readonly to: string;
101
+ readonly subject: string;
102
+ readonly html: string;
103
+ readonly text: string;
104
+ readonly replyTo?: string;
105
+ };
106
+ type SesSendResult = {
107
+ readonly messageId?: string;
108
+ };
109
+ type SesSendClient = {
110
+ sendEmail(params: SesSendParams): Promise<SesSendResult>;
111
+ };
112
+ type SesError = {
113
+ readonly name: string;
114
+ };
115
+
116
+ /**
117
+ * Copyright (c) 2026 Ada Technology. MIT License.
118
+ */
119
+
120
+ type SesEmailProviderConfig = {
121
+ readonly from: string;
122
+ readonly region?: string;
123
+ /** Injeção de teste — presente, o `@aws-sdk/client-sesv2` real nunca é importado. */
124
+ readonly client?: SesSendClient;
125
+ };
126
+ declare function createSesEmailProvider(config: SesEmailProviderConfig): EmailDriverPort;
127
+
128
+ /**
129
+ * Copyright (c) 2026 Ada Technology. MIT License.
130
+ */
131
+
132
+ type CreateEmailProviderParams = ({
133
+ readonly driver: typeof EMAIL_DRIVER.SMTP;
134
+ } & SmtpEmailProviderConfig) | ({
135
+ readonly driver: typeof EMAIL_DRIVER.RESEND;
136
+ } & ResendEmailProviderConfig) | ({
137
+ readonly driver: typeof EMAIL_DRIVER.SES;
138
+ } & SesEmailProviderConfig);
139
+ declare function createEmailProvider(params: CreateEmailProviderParams): EmailDriverPort;
140
+
141
+ /**
142
+ * Copyright (c) 2026 Ada Technology. MIT License.
143
+ */
144
+
145
+ /**
146
+ * Traduz o evento assinado da Resend para o recibo normalizado do módulo. A verificação de
147
+ * assinatura HMAC acontece **antes** desta função, sobre o `rawBody` — este parser já recebe o
148
+ * JSON confiável.
149
+ *
150
+ * Devolve `undefined` para eventos que não mudam o estado de uma entrega (`email.sent`,
151
+ * `email.opened`, `email.clicked`, ...) — o módulo simplesmente ignora o webhook.
152
+ */
153
+ declare function parseResendWebhook(payload: unknown): DeliveryReceipt | undefined;
154
+
155
+ /**
156
+ * Copyright (c) 2026 Ada Technology. MIT License.
157
+ */
158
+
159
+ /** `undefined` para envelope malformado, confirmação de assinatura da SNS, ou tipo desconhecido. */
160
+ declare function parseSesNotification(rawBody: string): DeliveryReceipt | undefined;
161
+
162
+ export { type CreateEmailProviderParams, type ResendClientLike, type ResendEmailProviderConfig, type ResendEmailsClient, type ResendSendResult, type SesEmailProviderConfig, type SesError, type SesSendClient, type SesSendParams, type SesSendResult, type SmtpEmailProviderConfig, type SmtpError, type SmtpMailMessage, type SmtpSendResult, type SmtpTransportClient, createEmailProvider, createResendEmailProvider, createSesEmailProvider, createSmtpEmailProvider, parseResendWebhook, parseSesNotification };
@@ -0,0 +1,162 @@
1
+ import { EmailDriverPort, EMAIL_DRIVER, DeliveryReceipt } from '@adatechnology/notification-contracts';
2
+
3
+ /**
4
+ * Copyright (c) 2026 Ada Technology. MIT License.
5
+ */
6
+ /**
7
+ * Forma mínima que o `Transporter` do `nodemailer` já satisfaz. Declarada por estrutura — não
8
+ * importada do pacote — para os testes injetarem um dublê sem carregar o SDK real.
9
+ */
10
+ type SmtpMailMessage = {
11
+ readonly from: string;
12
+ readonly to: string;
13
+ readonly subject: string;
14
+ readonly html: string;
15
+ readonly text: string;
16
+ readonly replyTo?: string;
17
+ };
18
+ type SmtpSendResult = {
19
+ readonly messageId: string;
20
+ readonly accepted: readonly unknown[];
21
+ readonly rejected: readonly unknown[];
22
+ };
23
+ type SmtpTransportClient = {
24
+ sendMail(message: SmtpMailMessage): Promise<SmtpSendResult>;
25
+ };
26
+ type SmtpError = {
27
+ /** Código de resposta SMTP (RFC 5321): 4xx é transitório, 5xx é permanente. */
28
+ readonly responseCode?: number;
29
+ readonly message?: string;
30
+ };
31
+
32
+ /**
33
+ * Copyright (c) 2026 Ada Technology. MIT License.
34
+ */
35
+
36
+ type SmtpEmailProviderConfig = {
37
+ readonly from: string;
38
+ /**
39
+ * URL de conexão (`smtps://user:pass@host:port`). Em dev aponta para o Mailpit do
40
+ * `docker-compose.yml` da raiz — e-mail nunca sai da máquina e é inspecionável.
41
+ */
42
+ readonly smtpUrl?: string;
43
+ /** Injeção de teste — presente, o `nodemailer` real nunca é importado. */
44
+ readonly transportClient?: SmtpTransportClient;
45
+ };
46
+ declare function createSmtpEmailProvider(config: SmtpEmailProviderConfig): EmailDriverPort;
47
+
48
+ /**
49
+ * Copyright (c) 2026 Ada Technology. MIT License.
50
+ */
51
+ /**
52
+ * Forma mínima que `new Resend(apiKey).emails` já satisfaz. O SDK do Resend não lança em erro de
53
+ * negócio — devolve `{ data, error }` — então a classificação lê `error.name`, nunca uma exceção.
54
+ */
55
+ type ResendSendResult = {
56
+ readonly data: {
57
+ readonly id: string;
58
+ } | null;
59
+ readonly error: {
60
+ readonly name: string;
61
+ readonly message: string;
62
+ readonly statusCode: number | null;
63
+ } | null;
64
+ };
65
+ type ResendEmailsClient = {
66
+ send(message: {
67
+ readonly from: string;
68
+ readonly to: string;
69
+ readonly subject: string;
70
+ readonly html: string;
71
+ readonly text: string;
72
+ readonly replyTo?: string;
73
+ }): Promise<ResendSendResult>;
74
+ };
75
+ type ResendClientLike = {
76
+ readonly emails: ResendEmailsClient;
77
+ };
78
+
79
+ /**
80
+ * Copyright (c) 2026 Ada Technology. MIT License.
81
+ */
82
+
83
+ type ResendEmailProviderConfig = {
84
+ readonly from: string;
85
+ readonly apiKey?: string;
86
+ /** Injeção de teste — presente, o `resend` real nunca é importado. */
87
+ readonly client?: ResendClientLike;
88
+ };
89
+ declare function createResendEmailProvider(config: ResendEmailProviderConfig): EmailDriverPort;
90
+
91
+ /**
92
+ * Copyright (c) 2026 Ada Technology. MIT License.
93
+ */
94
+ /**
95
+ * Forma própria, não a do `@aws-sdk/client-sesv2` — os testes injetam este dublê sem carregar o
96
+ * SDK real, e a versão exata do SDK do consumidor não vaza para a superfície pública do pacote.
97
+ */
98
+ type SesSendParams = {
99
+ readonly from: string;
100
+ readonly to: string;
101
+ readonly subject: string;
102
+ readonly html: string;
103
+ readonly text: string;
104
+ readonly replyTo?: string;
105
+ };
106
+ type SesSendResult = {
107
+ readonly messageId?: string;
108
+ };
109
+ type SesSendClient = {
110
+ sendEmail(params: SesSendParams): Promise<SesSendResult>;
111
+ };
112
+ type SesError = {
113
+ readonly name: string;
114
+ };
115
+
116
+ /**
117
+ * Copyright (c) 2026 Ada Technology. MIT License.
118
+ */
119
+
120
+ type SesEmailProviderConfig = {
121
+ readonly from: string;
122
+ readonly region?: string;
123
+ /** Injeção de teste — presente, o `@aws-sdk/client-sesv2` real nunca é importado. */
124
+ readonly client?: SesSendClient;
125
+ };
126
+ declare function createSesEmailProvider(config: SesEmailProviderConfig): EmailDriverPort;
127
+
128
+ /**
129
+ * Copyright (c) 2026 Ada Technology. MIT License.
130
+ */
131
+
132
+ type CreateEmailProviderParams = ({
133
+ readonly driver: typeof EMAIL_DRIVER.SMTP;
134
+ } & SmtpEmailProviderConfig) | ({
135
+ readonly driver: typeof EMAIL_DRIVER.RESEND;
136
+ } & ResendEmailProviderConfig) | ({
137
+ readonly driver: typeof EMAIL_DRIVER.SES;
138
+ } & SesEmailProviderConfig);
139
+ declare function createEmailProvider(params: CreateEmailProviderParams): EmailDriverPort;
140
+
141
+ /**
142
+ * Copyright (c) 2026 Ada Technology. MIT License.
143
+ */
144
+
145
+ /**
146
+ * Traduz o evento assinado da Resend para o recibo normalizado do módulo. A verificação de
147
+ * assinatura HMAC acontece **antes** desta função, sobre o `rawBody` — este parser já recebe o
148
+ * JSON confiável.
149
+ *
150
+ * Devolve `undefined` para eventos que não mudam o estado de uma entrega (`email.sent`,
151
+ * `email.opened`, `email.clicked`, ...) — o módulo simplesmente ignora o webhook.
152
+ */
153
+ declare function parseResendWebhook(payload: unknown): DeliveryReceipt | undefined;
154
+
155
+ /**
156
+ * Copyright (c) 2026 Ada Technology. MIT License.
157
+ */
158
+
159
+ /** `undefined` para envelope malformado, confirmação de assinatura da SNS, ou tipo desconhecido. */
160
+ declare function parseSesNotification(rawBody: string): DeliveryReceipt | undefined;
161
+
162
+ export { type CreateEmailProviderParams, type ResendClientLike, type ResendEmailProviderConfig, type ResendEmailsClient, type ResendSendResult, type SesEmailProviderConfig, type SesError, type SesSendClient, type SesSendParams, type SesSendResult, type SmtpEmailProviderConfig, type SmtpError, type SmtpMailMessage, type SmtpSendResult, type SmtpTransportClient, createEmailProvider, createResendEmailProvider, createSesEmailProvider, createSmtpEmailProvider, parseResendWebhook, parseSesNotification };
package/dist/index.js ADDED
@@ -0,0 +1,368 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/SmtpEmailProvider.ts
5
+ import { ConfigMissingError, EMAIL_DRIVER } from "@adatechnology/notification-contracts";
6
+
7
+ // src/SmtpTransportClient.ts
8
+ function isSmtpError(error) {
9
+ return typeof error === "object" && error !== null;
10
+ }
11
+ __name(isSmtpError, "isSmtpError");
12
+
13
+ // src/SmtpEmailProvider.ts
14
+ var INVALID_TARGET_CODES = /* @__PURE__ */ new Set([
15
+ 550,
16
+ 551,
17
+ 553
18
+ ]);
19
+ function classifySmtpError(error) {
20
+ const responseCode = isSmtpError(error) ? error.responseCode : void 0;
21
+ if (responseCode === void 0) return {
22
+ outcome: "retriable",
23
+ errorCode: "smtp_unknown"
24
+ };
25
+ if (INVALID_TARGET_CODES.has(responseCode)) return {
26
+ outcome: "invalid_target",
27
+ errorCode: `smtp_${responseCode}`
28
+ };
29
+ if (responseCode >= 500) return {
30
+ outcome: "permanent",
31
+ errorCode: `smtp_${responseCode}`
32
+ };
33
+ if (responseCode >= 400) return {
34
+ outcome: "retriable",
35
+ errorCode: `smtp_${responseCode}`
36
+ };
37
+ return {
38
+ outcome: "permanent",
39
+ errorCode: `smtp_${responseCode}`
40
+ };
41
+ }
42
+ __name(classifySmtpError, "classifySmtpError");
43
+ async function initNodemailerTransport(config) {
44
+ if (!config.smtpUrl) throw new ConfigMissingError("smtpUrl");
45
+ const nodemailer = await import("nodemailer");
46
+ return nodemailer.createTransport(config.smtpUrl);
47
+ }
48
+ __name(initNodemailerTransport, "initNodemailerTransport");
49
+ function createSmtpEmailProvider(config) {
50
+ let clientPromise;
51
+ function resolveClient() {
52
+ if (config.transportClient) return Promise.resolve(config.transportClient);
53
+ clientPromise ??= initNodemailerTransport(config);
54
+ return clientPromise;
55
+ }
56
+ __name(resolveClient, "resolveClient");
57
+ return {
58
+ driver: EMAIL_DRIVER.SMTP,
59
+ async send(params) {
60
+ const client = await resolveClient();
61
+ try {
62
+ const result = await client.sendMail({
63
+ from: config.from,
64
+ to: params.to,
65
+ subject: params.subject,
66
+ html: params.html,
67
+ text: params.text,
68
+ replyTo: params.replyTo
69
+ });
70
+ if (result.accepted.length === 0 && result.rejected.length > 0) {
71
+ return {
72
+ outcome: "invalid_target",
73
+ errorCode: "smtp_rejected"
74
+ };
75
+ }
76
+ return {
77
+ outcome: "sent",
78
+ providerMessageId: result.messageId
79
+ };
80
+ } catch (error) {
81
+ return classifySmtpError(error);
82
+ }
83
+ }
84
+ };
85
+ }
86
+ __name(createSmtpEmailProvider, "createSmtpEmailProvider");
87
+
88
+ // src/ResendEmailProvider.ts
89
+ import { ConfigMissingError as ConfigMissingError2, EMAIL_DRIVER as EMAIL_DRIVER2 } from "@adatechnology/notification-contracts";
90
+ var RETRIABLE_NAMES = /* @__PURE__ */ new Set([
91
+ "rate_limit_exceeded",
92
+ "monthly_quota_exceeded",
93
+ "daily_quota_exceeded",
94
+ "internal_server_error",
95
+ "application_error"
96
+ ]);
97
+ function classifyResendError(error) {
98
+ if (error.statusCode === 429 || error.statusCode !== null && error.statusCode >= 500) {
99
+ return {
100
+ outcome: "retriable",
101
+ errorCode: error.name
102
+ };
103
+ }
104
+ if (RETRIABLE_NAMES.has(error.name)) return {
105
+ outcome: "retriable",
106
+ errorCode: error.name
107
+ };
108
+ return {
109
+ outcome: "permanent",
110
+ errorCode: error.name
111
+ };
112
+ }
113
+ __name(classifyResendError, "classifyResendError");
114
+ async function initResendClient(config) {
115
+ if (!config.apiKey) throw new ConfigMissingError2("apiKey");
116
+ const { Resend } = await import("resend");
117
+ return new Resend(config.apiKey);
118
+ }
119
+ __name(initResendClient, "initResendClient");
120
+ function createResendEmailProvider(config) {
121
+ let clientPromise;
122
+ function resolveClient() {
123
+ if (config.client) return Promise.resolve(config.client);
124
+ clientPromise ??= initResendClient(config);
125
+ return clientPromise;
126
+ }
127
+ __name(resolveClient, "resolveClient");
128
+ return {
129
+ driver: EMAIL_DRIVER2.RESEND,
130
+ async send(params) {
131
+ const client = await resolveClient();
132
+ const result = await client.emails.send({
133
+ from: config.from,
134
+ to: params.to,
135
+ subject: params.subject,
136
+ html: params.html,
137
+ text: params.text,
138
+ replyTo: params.replyTo
139
+ });
140
+ if (result.error) return classifyResendError(result.error);
141
+ return {
142
+ outcome: "sent",
143
+ providerMessageId: result.data?.id
144
+ };
145
+ }
146
+ };
147
+ }
148
+ __name(createResendEmailProvider, "createResendEmailProvider");
149
+
150
+ // src/SesEmailProvider.ts
151
+ import { ConfigMissingError as ConfigMissingError3, EMAIL_DRIVER as EMAIL_DRIVER3 } from "@adatechnology/notification-contracts";
152
+
153
+ // src/SesSendClient.ts
154
+ function isSesError(error) {
155
+ return typeof error === "object" && error !== null && "name" in error && typeof error.name === "string";
156
+ }
157
+ __name(isSesError, "isSesError");
158
+
159
+ // src/SesEmailProvider.ts
160
+ var RETRIABLE_NAMES2 = /* @__PURE__ */ new Set([
161
+ "TooManyRequestsException",
162
+ "LimitExceededException",
163
+ "InternalServiceErrorException",
164
+ "ConcurrentModificationException"
165
+ ]);
166
+ function classifySesError(error) {
167
+ if (!isSesError(error)) return {
168
+ outcome: "retriable",
169
+ errorCode: "ses_unknown"
170
+ };
171
+ if (RETRIABLE_NAMES2.has(error.name)) return {
172
+ outcome: "retriable",
173
+ errorCode: error.name
174
+ };
175
+ return {
176
+ outcome: "permanent",
177
+ errorCode: error.name
178
+ };
179
+ }
180
+ __name(classifySesError, "classifySesError");
181
+ async function initSesClient(config) {
182
+ if (!config.region) throw new ConfigMissingError3("region");
183
+ const { SESv2Client, SendEmailCommand } = await import("@aws-sdk/client-sesv2");
184
+ const sesClient = new SESv2Client({
185
+ region: config.region
186
+ });
187
+ return {
188
+ async sendEmail(params) {
189
+ const response = await sesClient.send(new SendEmailCommand({
190
+ FromEmailAddress: params.from,
191
+ Destination: {
192
+ ToAddresses: [
193
+ params.to
194
+ ]
195
+ },
196
+ ReplyToAddresses: params.replyTo ? [
197
+ params.replyTo
198
+ ] : void 0,
199
+ Content: {
200
+ Simple: {
201
+ Subject: {
202
+ Data: params.subject
203
+ },
204
+ Body: {
205
+ Html: {
206
+ Data: params.html
207
+ },
208
+ Text: {
209
+ Data: params.text
210
+ }
211
+ }
212
+ }
213
+ }
214
+ }));
215
+ return {
216
+ messageId: response.MessageId
217
+ };
218
+ }
219
+ };
220
+ }
221
+ __name(initSesClient, "initSesClient");
222
+ function createSesEmailProvider(config) {
223
+ let clientPromise;
224
+ function resolveClient() {
225
+ if (config.client) return Promise.resolve(config.client);
226
+ clientPromise ??= initSesClient(config);
227
+ return clientPromise;
228
+ }
229
+ __name(resolveClient, "resolveClient");
230
+ return {
231
+ driver: EMAIL_DRIVER3.SES,
232
+ async send(params) {
233
+ const client = await resolveClient();
234
+ try {
235
+ const result = await client.sendEmail({
236
+ from: config.from,
237
+ to: params.to,
238
+ subject: params.subject,
239
+ html: params.html,
240
+ text: params.text,
241
+ replyTo: params.replyTo
242
+ });
243
+ return {
244
+ outcome: "sent",
245
+ providerMessageId: result.messageId
246
+ };
247
+ } catch (error) {
248
+ return classifySesError(error);
249
+ }
250
+ }
251
+ };
252
+ }
253
+ __name(createSesEmailProvider, "createSesEmailProvider");
254
+
255
+ // src/EmailProviderFactory.ts
256
+ import { EMAIL_DRIVER as EMAIL_DRIVER4 } from "@adatechnology/notification-contracts";
257
+ function createEmailProvider(params) {
258
+ if (params.driver === EMAIL_DRIVER4.SMTP) return createSmtpEmailProvider(params);
259
+ if (params.driver === EMAIL_DRIVER4.RESEND) return createResendEmailProvider(params);
260
+ if (params.driver === EMAIL_DRIVER4.SES) return createSesEmailProvider(params);
261
+ const _exhaustive = params;
262
+ throw new Error(`Driver de e-mail desconhecido: ${String(_exhaustive.driver)}`);
263
+ }
264
+ __name(createEmailProvider, "createEmailProvider");
265
+
266
+ // src/receipts/parseResendWebhook.ts
267
+ import { SUPPRESSION_REASON } from "@adatechnology/notification-contracts";
268
+ function isResendWebhookPayload(value) {
269
+ if (typeof value !== "object" || value === null) return false;
270
+ const candidate = value;
271
+ if (typeof candidate.type !== "string" || typeof candidate.created_at !== "string") return false;
272
+ const data = candidate.data;
273
+ return typeof data?.email_id === "string";
274
+ }
275
+ __name(isResendWebhookPayload, "isResendWebhookPayload");
276
+ function parseResendWebhook(payload) {
277
+ if (!isResendWebhookPayload(payload)) return void 0;
278
+ const occurredAt = new Date(payload.created_at);
279
+ const providerMessageId = payload.data.email_id;
280
+ if (payload.type === "email.delivered") {
281
+ return {
282
+ providerMessageId,
283
+ status: "delivered",
284
+ occurredAt
285
+ };
286
+ }
287
+ if (payload.type === "email.bounced") {
288
+ const errorCode = payload.data.bounce?.subType ?? payload.data.bounce?.type;
289
+ return {
290
+ providerMessageId,
291
+ status: "bounced",
292
+ suppressionReason: SUPPRESSION_REASON.BOUNCE,
293
+ errorCode,
294
+ occurredAt
295
+ };
296
+ }
297
+ if (payload.type === "email.complained") {
298
+ return {
299
+ providerMessageId,
300
+ status: "failed",
301
+ suppressionReason: SUPPRESSION_REASON.COMPLAINT,
302
+ occurredAt
303
+ };
304
+ }
305
+ return void 0;
306
+ }
307
+ __name(parseResendWebhook, "parseResendWebhook");
308
+
309
+ // src/receipts/parseSesNotification.ts
310
+ import { SUPPRESSION_REASON as SUPPRESSION_REASON2 } from "@adatechnology/notification-contracts";
311
+ function parseJson(text) {
312
+ try {
313
+ return JSON.parse(text);
314
+ } catch {
315
+ return void 0;
316
+ }
317
+ }
318
+ __name(parseJson, "parseJson");
319
+ function isSesEventMessage(value) {
320
+ if (typeof value !== "object" || value === null) return false;
321
+ const candidate = value;
322
+ const mail = candidate.mail;
323
+ return (candidate.notificationType === "Bounce" || candidate.notificationType === "Complaint" || candidate.notificationType === "Delivery") && typeof mail?.messageId === "string";
324
+ }
325
+ __name(isSesEventMessage, "isSesEventMessage");
326
+ function parseSesNotification(rawBody) {
327
+ const envelope = parseJson(rawBody);
328
+ if (envelope?.Type !== "Notification" || typeof envelope.Message !== "string") return void 0;
329
+ const event = parseJson(envelope.Message);
330
+ if (!isSesEventMessage(event)) return void 0;
331
+ const providerMessageId = event.mail.messageId;
332
+ if (event.notificationType === "Delivery" && event.delivery) {
333
+ return {
334
+ providerMessageId,
335
+ status: "delivered",
336
+ occurredAt: new Date(event.delivery.timestamp)
337
+ };
338
+ }
339
+ if (event.notificationType === "Bounce" && event.bounce) {
340
+ return {
341
+ providerMessageId,
342
+ status: "bounced",
343
+ suppressionReason: SUPPRESSION_REASON2.BOUNCE,
344
+ errorCode: `${event.bounce.bounceType}/${event.bounce.bounceSubType}`,
345
+ occurredAt: new Date(event.bounce.timestamp)
346
+ };
347
+ }
348
+ if (event.notificationType === "Complaint" && event.complaint) {
349
+ return {
350
+ providerMessageId,
351
+ status: "failed",
352
+ suppressionReason: SUPPRESSION_REASON2.COMPLAINT,
353
+ errorCode: event.complaint.complaintFeedbackType,
354
+ occurredAt: new Date(event.complaint.timestamp)
355
+ };
356
+ }
357
+ return void 0;
358
+ }
359
+ __name(parseSesNotification, "parseSesNotification");
360
+ export {
361
+ createEmailProvider,
362
+ createResendEmailProvider,
363
+ createSesEmailProvider,
364
+ createSmtpEmailProvider,
365
+ parseResendWebhook,
366
+ parseSesNotification
367
+ };
368
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/SmtpEmailProvider.ts","../src/SmtpTransportClient.ts","../src/ResendEmailProvider.ts","../src/SesEmailProvider.ts","../src/SesSendClient.ts","../src/EmailProviderFactory.ts","../src/receipts/parseResendWebhook.ts","../src/receipts/parseSesNotification.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { ConfigMissingError, EMAIL_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, EmailDriverPort, SendEmailParams } from '@adatechnology/notification-contracts'\n\nimport { isSmtpError, type SmtpTransportClient } from './SmtpTransportClient'\n\nexport type SmtpEmailProviderConfig = {\n readonly from: string\n /**\n * URL de conexão (`smtps://user:pass@host:port`). Em dev aponta para o Mailpit do\n * `docker-compose.yml` da raiz — e-mail nunca sai da máquina e é inspecionável.\n */\n readonly smtpUrl?: string\n /** Injeção de teste — presente, o `nodemailer` real nunca é importado. */\n readonly transportClient?: SmtpTransportClient\n}\n\n// Códigos de \"usuário desconhecido\" — o mais próximo que o SMTP tem de \"apaga o token\" do push.\nconst INVALID_TARGET_CODES = new Set([550, 551, 553])\n\nfunction classifySmtpError(error: unknown): DeliveryAttemptResult {\n const responseCode = isSmtpError(error) ? error.responseCode : undefined\n if (responseCode === undefined) return { outcome: 'retriable', errorCode: 'smtp_unknown' }\n if (INVALID_TARGET_CODES.has(responseCode)) return { outcome: 'invalid_target', errorCode: `smtp_${responseCode}` }\n if (responseCode >= 500) return { outcome: 'permanent', errorCode: `smtp_${responseCode}` }\n if (responseCode >= 400) return { outcome: 'retriable', errorCode: `smtp_${responseCode}` }\n return { outcome: 'permanent', errorCode: `smtp_${responseCode}` }\n}\n\nasync function initNodemailerTransport(config: SmtpEmailProviderConfig): Promise<SmtpTransportClient> {\n if (!config.smtpUrl) throw new ConfigMissingError('smtpUrl')\n\n const nodemailer = await import('nodemailer')\n return nodemailer.createTransport(config.smtpUrl)\n}\n\nexport function createSmtpEmailProvider(config: SmtpEmailProviderConfig): EmailDriverPort {\n let clientPromise: Promise<SmtpTransportClient> | undefined\n\n function resolveClient(): Promise<SmtpTransportClient> {\n if (config.transportClient) return Promise.resolve(config.transportClient)\n clientPromise ??= initNodemailerTransport(config)\n return clientPromise\n }\n\n return {\n driver: EMAIL_DRIVER.SMTP,\n async send(params: SendEmailParams): Promise<DeliveryAttemptResult> {\n const client = await resolveClient()\n try {\n const result = await client.sendMail({\n from: config.from,\n to: params.to,\n subject: params.subject,\n html: params.html,\n text: params.text,\n replyTo: params.replyTo,\n })\n\n // Servidor aceitou a conexão mas rejeitou o destinatário sem lançar erro — mesmo sinal de\n // endereço morto que um 550 lançado como exceção.\n if (result.accepted.length === 0 && result.rejected.length > 0) {\n return { outcome: 'invalid_target', errorCode: 'smtp_rejected' }\n }\n\n return { outcome: 'sent', providerMessageId: result.messageId }\n } catch (error) {\n return classifySmtpError(error)\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * Forma mínima que o `Transporter` do `nodemailer` já satisfaz. Declarada por estrutura — não\n * importada do pacote — para os testes injetarem um dublê sem carregar o SDK real.\n */\nexport type SmtpMailMessage = {\n readonly from: string\n readonly to: string\n readonly subject: string\n readonly html: string\n readonly text: string\n readonly replyTo?: string\n}\n\nexport type SmtpSendResult = {\n readonly messageId: string\n readonly accepted: readonly unknown[]\n readonly rejected: readonly unknown[]\n}\n\nexport type SmtpTransportClient = {\n sendMail(message: SmtpMailMessage): Promise<SmtpSendResult>\n}\n\nexport type SmtpError = {\n /** Código de resposta SMTP (RFC 5321): 4xx é transitório, 5xx é permanente. */\n readonly responseCode?: number\n readonly message?: string\n}\n\nexport function isSmtpError(error: unknown): error is SmtpError {\n return typeof error === 'object' && error !== null\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { ConfigMissingError, EMAIL_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, EmailDriverPort, SendEmailParams } from '@adatechnology/notification-contracts'\n\nimport type { ResendClientLike, ResendSendResult } from './ResendClient'\n\nexport type ResendEmailProviderConfig = {\n readonly from: string\n readonly apiKey?: string\n /** Injeção de teste — presente, o `resend` real nunca é importado. */\n readonly client?: ResendClientLike\n}\n\n// error.name documentado pela Resend (RESEND_ERROR_CODE_KEY). Sem sinal de \"endereço não existe\"\n// — bounce é sempre assíncrono, via webhook (spec §11, \"delivered é assimétrico\").\nconst RETRIABLE_NAMES = new Set([\n 'rate_limit_exceeded',\n 'monthly_quota_exceeded',\n 'daily_quota_exceeded',\n 'internal_server_error',\n 'application_error',\n])\n\nfunction classifyResendError(error: NonNullable<ResendSendResult['error']>): DeliveryAttemptResult {\n if (error.statusCode === 429 || (error.statusCode !== null && error.statusCode >= 500)) {\n return { outcome: 'retriable', errorCode: error.name }\n }\n if (RETRIABLE_NAMES.has(error.name)) return { outcome: 'retriable', errorCode: error.name }\n return { outcome: 'permanent', errorCode: error.name }\n}\n\nasync function initResendClient(config: ResendEmailProviderConfig): Promise<ResendClientLike> {\n if (!config.apiKey) throw new ConfigMissingError('apiKey')\n\n const { Resend } = await import('resend')\n return new Resend(config.apiKey)\n}\n\nexport function createResendEmailProvider(config: ResendEmailProviderConfig): EmailDriverPort {\n let clientPromise: Promise<ResendClientLike> | undefined\n\n function resolveClient(): Promise<ResendClientLike> {\n if (config.client) return Promise.resolve(config.client)\n clientPromise ??= initResendClient(config)\n return clientPromise\n }\n\n return {\n driver: EMAIL_DRIVER.RESEND,\n async send(params: SendEmailParams): Promise<DeliveryAttemptResult> {\n const client = await resolveClient()\n const result = await client.emails.send({\n from: config.from,\n to: params.to,\n subject: params.subject,\n html: params.html,\n text: params.text,\n replyTo: params.replyTo,\n })\n\n if (result.error) return classifyResendError(result.error)\n return { outcome: 'sent', providerMessageId: result.data?.id }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { ConfigMissingError, EMAIL_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, EmailDriverPort, SendEmailParams } from '@adatechnology/notification-contracts'\n\nimport { isSesError, type SesSendClient } from './SesSendClient'\n\nexport type SesEmailProviderConfig = {\n readonly from: string\n readonly region?: string\n /** Injeção de teste — presente, o `@aws-sdk/client-sesv2` real nunca é importado. */\n readonly client?: SesSendClient\n}\n\n// SESv2ServiceException.name — só o que muda a decisão de retry.\nconst RETRIABLE_NAMES = new Set([\n 'TooManyRequestsException',\n 'LimitExceededException',\n 'InternalServiceErrorException',\n 'ConcurrentModificationException',\n])\n\nfunction classifySesError(error: unknown): DeliveryAttemptResult {\n if (!isSesError(error)) return { outcome: 'retriable', errorCode: 'ses_unknown' }\n if (RETRIABLE_NAMES.has(error.name)) return { outcome: 'retriable', errorCode: error.name }\n return { outcome: 'permanent', errorCode: error.name }\n}\n\nasync function initSesClient(config: SesEmailProviderConfig): Promise<SesSendClient> {\n if (!config.region) throw new ConfigMissingError('region')\n\n const { SESv2Client, SendEmailCommand } = await import('@aws-sdk/client-sesv2')\n const sesClient = new SESv2Client({ region: config.region })\n\n return {\n async sendEmail(params) {\n const response = await sesClient.send(\n new SendEmailCommand({\n FromEmailAddress: params.from,\n Destination: { ToAddresses: [params.to] },\n ReplyToAddresses: params.replyTo ? [params.replyTo] : undefined,\n Content: {\n Simple: {\n Subject: { Data: params.subject },\n Body: { Html: { Data: params.html }, Text: { Data: params.text } },\n },\n },\n }),\n )\n return { messageId: response.MessageId }\n },\n }\n}\n\nexport function createSesEmailProvider(config: SesEmailProviderConfig): EmailDriverPort {\n let clientPromise: Promise<SesSendClient> | undefined\n\n function resolveClient(): Promise<SesSendClient> {\n if (config.client) return Promise.resolve(config.client)\n clientPromise ??= initSesClient(config)\n return clientPromise\n }\n\n return {\n driver: EMAIL_DRIVER.SES,\n async send(params: SendEmailParams): Promise<DeliveryAttemptResult> {\n const client = await resolveClient()\n try {\n const result = await client.sendEmail({\n from: config.from,\n to: params.to,\n subject: params.subject,\n html: params.html,\n text: params.text,\n replyTo: params.replyTo,\n })\n return { outcome: 'sent', providerMessageId: result.messageId }\n } catch (error) {\n return classifySesError(error)\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * Forma própria, não a do `@aws-sdk/client-sesv2` — os testes injetam este dublê sem carregar o\n * SDK real, e a versão exata do SDK do consumidor não vaza para a superfície pública do pacote.\n */\nexport type SesSendParams = {\n readonly from: string\n readonly to: string\n readonly subject: string\n readonly html: string\n readonly text: string\n readonly replyTo?: string\n}\n\nexport type SesSendResult = {\n readonly messageId?: string\n}\n\nexport type SesSendClient = {\n sendEmail(params: SesSendParams): Promise<SesSendResult>\n}\n\nexport type SesError = {\n readonly name: string\n}\n\nexport function isSesError(error: unknown): error is SesError {\n return typeof error === 'object' && error !== null && 'name' in error && typeof (error as SesError).name === 'string'\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { EMAIL_DRIVER } from '@adatechnology/notification-contracts'\nimport type { EmailDriverPort } from '@adatechnology/notification-contracts'\n\nimport { createResendEmailProvider, type ResendEmailProviderConfig } from './ResendEmailProvider'\nimport { createSesEmailProvider, type SesEmailProviderConfig } from './SesEmailProvider'\nimport { createSmtpEmailProvider, type SmtpEmailProviderConfig } from './SmtpEmailProvider'\n\nexport type CreateEmailProviderParams =\n | ({ readonly driver: typeof EMAIL_DRIVER.SMTP } & SmtpEmailProviderConfig)\n | ({ readonly driver: typeof EMAIL_DRIVER.RESEND } & ResendEmailProviderConfig)\n | ({ readonly driver: typeof EMAIL_DRIVER.SES } & SesEmailProviderConfig)\n\nexport function createEmailProvider(params: CreateEmailProviderParams): EmailDriverPort {\n if (params.driver === EMAIL_DRIVER.SMTP) return createSmtpEmailProvider(params)\n if (params.driver === EMAIL_DRIVER.RESEND) return createResendEmailProvider(params)\n if (params.driver === EMAIL_DRIVER.SES) return createSesEmailProvider(params)\n\n const _exhaustive: never = params\n throw new Error(`Driver de e-mail desconhecido: ${String((_exhaustive as { driver?: unknown }).driver)}`)\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { SUPPRESSION_REASON } from '@adatechnology/notification-contracts'\nimport type { DeliveryReceipt } from '@adatechnology/notification-contracts'\n\n/**\n * Formato documentado do webhook da Resend (`WebhookEvent`), reproduzido aqui por estrutura em\n * vez de importado do SDK — este arquivo só faz parsing de JSON, não precisa do cliente.\n */\ntype ResendWebhookPayload = {\n readonly type: string\n readonly created_at: string\n readonly data: {\n readonly email_id: string\n readonly bounce?: { readonly type?: string; readonly subType?: string }\n }\n}\n\nfunction isResendWebhookPayload(value: unknown): value is ResendWebhookPayload {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n if (typeof candidate.type !== 'string' || typeof candidate.created_at !== 'string') return false\n const data = candidate.data as Record<string, unknown> | undefined\n return typeof data?.email_id === 'string'\n}\n\n/**\n * Traduz o evento assinado da Resend para o recibo normalizado do módulo. A verificação de\n * assinatura HMAC acontece **antes** desta função, sobre o `rawBody` — este parser já recebe o\n * JSON confiável.\n *\n * Devolve `undefined` para eventos que não mudam o estado de uma entrega (`email.sent`,\n * `email.opened`, `email.clicked`, ...) — o módulo simplesmente ignora o webhook.\n */\nexport function parseResendWebhook(payload: unknown): DeliveryReceipt | undefined {\n if (!isResendWebhookPayload(payload)) return undefined\n\n const occurredAt = new Date(payload.created_at)\n const providerMessageId = payload.data.email_id\n\n if (payload.type === 'email.delivered') {\n return { providerMessageId, status: 'delivered', occurredAt }\n }\n\n if (payload.type === 'email.bounced') {\n const errorCode = payload.data.bounce?.subType ?? payload.data.bounce?.type\n return { providerMessageId, status: 'bounced', suppressionReason: SUPPRESSION_REASON.BOUNCE, errorCode, occurredAt }\n }\n\n if (payload.type === 'email.complained') {\n return { providerMessageId, status: 'failed', suppressionReason: SUPPRESSION_REASON.COMPLAINT, occurredAt }\n }\n\n return undefined\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { SUPPRESSION_REASON } from '@adatechnology/notification-contracts'\nimport type { DeliveryReceipt } from '@adatechnology/notification-contracts'\n\n/**\n * SES publica bounce/complaint/delivery via SNS: o corpo do POST é o envelope da SNS\n * (`Type`, `Message`), e `Message` é uma STRING com o evento da SES serializado dentro. Dois\n * `JSON.parse` em sequência, não um só — é a causa mais comum de parser de SES quebrado.\n *\n * A verificação da assinatura da SNS (certificado X.509, separada do HMAC do módulo) é\n * responsabilidade de quem expõe a rota; esta função só traduz o payload já autenticado.\n */\ntype SesEventMessage = {\n readonly notificationType: 'Bounce' | 'Complaint' | 'Delivery'\n readonly mail: { readonly messageId: string }\n readonly bounce?: { readonly bounceType: string; readonly bounceSubType: string; readonly timestamp: string }\n readonly complaint?: { readonly complaintFeedbackType?: string; readonly timestamp: string }\n readonly delivery?: { readonly timestamp: string }\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return undefined\n }\n}\n\nfunction isSesEventMessage(value: unknown): value is SesEventMessage {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n const mail = candidate.mail as Record<string, unknown> | undefined\n return (\n (candidate.notificationType === 'Bounce' ||\n candidate.notificationType === 'Complaint' ||\n candidate.notificationType === 'Delivery') &&\n typeof mail?.messageId === 'string'\n )\n}\n\n/** `undefined` para envelope malformado, confirmação de assinatura da SNS, ou tipo desconhecido. */\nexport function parseSesNotification(rawBody: string): DeliveryReceipt | undefined {\n const envelope = parseJson(rawBody) as { readonly Type?: string; readonly Message?: string } | undefined\n if (envelope?.Type !== 'Notification' || typeof envelope.Message !== 'string') return undefined\n\n const event = parseJson(envelope.Message)\n if (!isSesEventMessage(event)) return undefined\n\n const providerMessageId = event.mail.messageId\n\n if (event.notificationType === 'Delivery' && event.delivery) {\n return { providerMessageId, status: 'delivered', occurredAt: new Date(event.delivery.timestamp) }\n }\n\n if (event.notificationType === 'Bounce' && event.bounce) {\n return {\n providerMessageId,\n status: 'bounced',\n suppressionReason: SUPPRESSION_REASON.BOUNCE,\n errorCode: `${event.bounce.bounceType}/${event.bounce.bounceSubType}`,\n occurredAt: new Date(event.bounce.timestamp),\n }\n }\n\n if (event.notificationType === 'Complaint' && event.complaint) {\n return {\n providerMessageId,\n status: 'failed',\n suppressionReason: SUPPRESSION_REASON.COMPLAINT,\n errorCode: event.complaint.complaintFeedbackType,\n occurredAt: new Date(event.complaint.timestamp),\n }\n }\n\n return undefined\n}\n"],"mappings":";;;;AAIA,SAASA,oBAAoBC,oBAAoB;;;AC6B1C,SAASC,YAAYC,OAAc;AACxC,SAAO,OAAOA,UAAU,YAAYA,UAAU;AAChD;AAFgBD;;;ADZhB,IAAME,uBAAuB,oBAAIC,IAAI;EAAC;EAAK;EAAK;CAAI;AAEpD,SAASC,kBAAkBC,OAAc;AACvC,QAAMC,eAAeC,YAAYF,KAAAA,IAASA,MAAMC,eAAeE;AAC/D,MAAIF,iBAAiBE,OAAW,QAAO;IAAEC,SAAS;IAAaC,WAAW;EAAe;AACzF,MAAIR,qBAAqBS,IAAIL,YAAAA,EAAe,QAAO;IAAEG,SAAS;IAAkBC,WAAW,QAAQJ,YAAAA;EAAe;AAClH,MAAIA,gBAAgB,IAAK,QAAO;IAAEG,SAAS;IAAaC,WAAW,QAAQJ,YAAAA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AKL,MAAME,SAASI,SAAS;IAAE;EAClG;AAEA,MAAIN,MAAMP,qBAAqB,YAAYO,MAAMO,QAAQ;AACvD,WAAO;MACLN;MACAE,QAAQ;MACRK,mBAAmBC,oBAAmBC;MACtCC,WAAW,GAAGX,MAAMO,OAAOK,UAAU,IAAIZ,MAAMO,OAAOM,aAAa;MACnET,YAAY,IAAIC,KAAKL,MAAMO,OAAOD,SAAS;IAC7C;EACF;AAEA,MAAIN,MAAMP,qBAAqB,eAAeO,MAAMc,WAAW;AAC7D,WAAO;MACLb;MACAE,QAAQ;MACRK,mBAAmBC,oBAAmBM;MACtCJ,WAAWX,MAAMc,UAAUE;MAC3BZ,YAAY,IAAIC,KAAKL,MAAMc,UAAUR,SAAS;IAChD;EACF;AAEA,SAAOlB;AACT;AAlCgBO;","names":["ConfigMissingError","EMAIL_DRIVER","isSmtpError","error","INVALID_TARGET_CODES","Set","classifySmtpError","error","responseCode","isSmtpError","undefined","outcome","errorCode","has","initNodemailerTransport","config","smtpUrl","ConfigMissingError","nodemailer","createTransport","createSmtpEmailProvider","clientPromise","resolveClient","transportClient","Promise","resolve","driver","EMAIL_DRIVER","SMTP","send","params","client","result","sendMail","from","to","subject","html","text","replyTo","accepted","length","rejected","providerMessageId","messageId","ConfigMissingError","EMAIL_DRIVER","RETRIABLE_NAMES","Set","classifyResendError","error","statusCode","outcome","errorCode","name","has","initResendClient","config","apiKey","ConfigMissingError","Resend","createResendEmailProvider","clientPromise","resolveClient","client","Promise","resolve","driver","EMAIL_DRIVER","RESEND","send","params","result","emails","from","to","subject","html","text","replyTo","providerMessageId","data","id","ConfigMissingError","EMAIL_DRIVER","isSesError","error","name","RETRIABLE_NAMES","Set","classifySesError","error","isSesError","outcome","errorCode","has","name","initSesClient","config","region","ConfigMissingError","SESv2Client","SendEmailCommand","sesClient","sendEmail","params","response","send","FromEmailAddress","from","Destination","ToAddresses","to","ReplyToAddresses","replyTo","undefined","Content","Simple","Subject","Data","subject","Body","Html","html","Text","text","messageId","MessageId","createSesEmailProvider","clientPromise","resolveClient","client","Promise","resolve","driver","EMAIL_DRIVER","SES","result","providerMessageId","EMAIL_DRIVER","createEmailProvider","params","driver","EMAIL_DRIVER","SMTP","createSmtpEmailProvider","RESEND","createResendEmailProvider","SES","createSesEmailProvider","_exhaustive","Error","String","SUPPRESSION_REASON","isResendWebhookPayload","value","candidate","type","created_at","data","email_id","parseResendWebhook","payload","undefined","occurredAt","Date","providerMessageId","status","errorCode","bounce","subType","suppressionReason","SUPPRESSION_REASON","BOUNCE","COMPLAINT","SUPPRESSION_REASON","parseJson","text","JSON","parse","undefined","isSesEventMessage","value","candidate","mail","notificationType","messageId","parseSesNotification","rawBody","envelope","Type","Message","event","providerMessageId","delivery","status","occurredAt","Date","timestamp","bounce","suppressionReason","SUPPRESSION_REASON","BOUNCE","errorCode","bounceType","bounceSubType","complaint","COMPLAINT","complaintFeedbackType"]}
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@adatechnology/email-provider",
3
+ "version": "0.1.0-rc.1",
4
+ "description": "Stateless email providers (SMTP, Resend, SES) behind a single port — part of the notification trio",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "type": "module",
10
+ "main": "dist/index.js",
11
+ "types": "dist/index.d.ts",
12
+ "sideEffects": false,
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js",
17
+ "require": "./dist/index.cjs"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "dependencies": {
24
+ "@adatechnology/notification-contracts": "0.1.0-rc.1"
25
+ },
26
+ "peerDependencies": {
27
+ "nodemailer": ">=6.9.0 <10",
28
+ "resend": ">=4 <7",
29
+ "@aws-sdk/client-sesv2": ">=3 <4"
30
+ },
31
+ "peerDependenciesMeta": {
32
+ "nodemailer": {
33
+ "optional": true
34
+ },
35
+ "resend": {
36
+ "optional": true
37
+ },
38
+ "@aws-sdk/client-sesv2": {
39
+ "optional": true
40
+ }
41
+ },
42
+ "devDependencies": {
43
+ "@aws-sdk/client-sesv2": "3.1091.0",
44
+ "@types/bun": "1.3.14",
45
+ "@types/nodemailer": "^7.0.2",
46
+ "nodemailer": "^9.0.1",
47
+ "resend": "^6.17.2",
48
+ "tsup": "^8.5.1",
49
+ "typescript": "^5.7.3"
50
+ },
51
+ "scripts": {
52
+ "build": "tsup",
53
+ "check": "tsc -p tsconfig.json --noEmit",
54
+ "test": "bun test"
55
+ }
56
+ }