@adatechnology/email-provider 0.1.0-rc.5 → 0.1.0-rc.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -31,17 +31,64 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  // src/index.ts
32
32
  var index_exports = {};
33
33
  __export(index_exports, {
34
+ AttachmentFetchError: () => AttachmentFetchError,
35
+ buildMimeMessage: () => buildMimeMessage,
34
36
  createEmailProvider: () => createEmailProvider,
35
37
  createResendEmailProvider: () => createResendEmailProvider,
36
38
  createSesEmailProvider: () => createSesEmailProvider,
37
39
  createSmtpEmailProvider: () => createSmtpEmailProvider,
40
+ fetchAttachments: () => fetchAttachments,
38
41
  parseResendWebhook: () => parseResendWebhook,
39
42
  parseSesNotification: () => parseSesNotification
40
43
  });
41
44
  module.exports = __toCommonJS(index_exports);
42
45
 
43
46
  // src/SmtpEmailProvider.ts
47
+ var import_notification_contracts2 = require("@adatechnology/notification-contracts");
48
+
49
+ // src/fetchAttachments.ts
44
50
  var import_notification_contracts = require("@adatechnology/notification-contracts");
51
+ var AttachmentFetchError = class extends Error {
52
+ static {
53
+ __name(this, "AttachmentFetchError");
54
+ }
55
+ errorCode;
56
+ constructor(errorCode) {
57
+ super(`attachment: ${errorCode}`), this.errorCode = errorCode;
58
+ this.name = "AttachmentFetchError";
59
+ }
60
+ };
61
+ async function fetchAttachments(attachments, fetchImpl = fetch) {
62
+ if (!attachments || attachments.length === 0) return [];
63
+ if (attachments.length > import_notification_contracts.EMAIL_ATTACHMENT_MAX_COUNT) {
64
+ throw new AttachmentFetchError("attachment_count_exceeded");
65
+ }
66
+ const fetched = await Promise.all(attachments.map((attachment) => fetchOne(attachment, fetchImpl)));
67
+ const total = fetched.reduce((sum, attachment) => sum + attachment.content.byteLength, 0);
68
+ if (total > import_notification_contracts.EMAIL_ATTACHMENT_MAX_BYTES) throw new AttachmentFetchError("attachment_total_too_large");
69
+ return fetched;
70
+ }
71
+ __name(fetchAttachments, "fetchAttachments");
72
+ async function fetchOne(attachment, fetchImpl) {
73
+ const problem = (0, import_notification_contracts.checkEmailAttachment)(attachment);
74
+ if (problem) throw new AttachmentFetchError(problem.toLowerCase());
75
+ const response = await fetchImpl(attachment.url).catch(() => void 0);
76
+ if (!response) throw new AttachmentFetchError("attachment_unreachable");
77
+ if (!response.ok) throw new AttachmentFetchError(`attachment_http_${response.status}`);
78
+ const declared = Number(response.headers.get("content-length"));
79
+ if (Number.isFinite(declared) && declared > import_notification_contracts.EMAIL_ATTACHMENT_MAX_BYTES) {
80
+ throw new AttachmentFetchError("attachment_too_large");
81
+ }
82
+ const content = new Uint8Array(await response.arrayBuffer());
83
+ if (content.byteLength > import_notification_contracts.EMAIL_ATTACHMENT_MAX_BYTES) throw new AttachmentFetchError("attachment_too_large");
84
+ if (content.byteLength === 0) throw new AttachmentFetchError("attachment_empty");
85
+ return {
86
+ filename: attachment.filename,
87
+ contentType: attachment.contentType,
88
+ content
89
+ };
90
+ }
91
+ __name(fetchOne, "fetchOne");
45
92
 
46
93
  // src/SmtpTransportClient.ts
47
94
  function isSmtpError(error) {
@@ -80,7 +127,7 @@ function classifySmtpError(error) {
80
127
  }
81
128
  __name(classifySmtpError, "classifySmtpError");
82
129
  async function initNodemailerTransport(config) {
83
- if (!config.smtpUrl) throw new import_notification_contracts.ConfigMissingError("smtpUrl");
130
+ if (!config.smtpUrl) throw new import_notification_contracts2.ConfigMissingError("smtpUrl");
84
131
  const nodemailer = await import("nodemailer");
85
132
  return nodemailer.createTransport(config.smtpUrl);
86
133
  }
@@ -94,9 +141,19 @@ function createSmtpEmailProvider(config) {
94
141
  }
95
142
  __name(resolveClient, "resolveClient");
96
143
  return {
97
- driver: import_notification_contracts.EMAIL_DRIVER.SMTP,
144
+ driver: import_notification_contracts2.EMAIL_DRIVER.SMTP,
98
145
  async send(params) {
99
146
  const client = await resolveClient();
147
+ let attachments;
148
+ try {
149
+ attachments = await fetchAttachments(params.attachments);
150
+ } catch (error) {
151
+ if (error instanceof AttachmentFetchError) return {
152
+ outcome: "retriable",
153
+ errorCode: error.errorCode
154
+ };
155
+ throw error;
156
+ }
100
157
  try {
101
158
  const result = await client.sendMail({
102
159
  from: config.from,
@@ -104,7 +161,14 @@ function createSmtpEmailProvider(config) {
104
161
  subject: params.subject,
105
162
  html: params.html,
106
163
  text: params.text,
107
- replyTo: params.replyTo
164
+ replyTo: params.replyTo,
165
+ ...attachments.length > 0 ? {
166
+ attachments: attachments.map((attachment) => ({
167
+ filename: attachment.filename,
168
+ content: Buffer.from(attachment.content),
169
+ contentType: attachment.contentType
170
+ }))
171
+ } : {}
108
172
  });
109
173
  if (result.accepted.length === 0 && result.rejected.length > 0) {
110
174
  return {
@@ -125,7 +189,7 @@ function createSmtpEmailProvider(config) {
125
189
  __name(createSmtpEmailProvider, "createSmtpEmailProvider");
126
190
 
127
191
  // src/ResendEmailProvider.ts
128
- var import_notification_contracts2 = require("@adatechnology/notification-contracts");
192
+ var import_notification_contracts3 = require("@adatechnology/notification-contracts");
129
193
  var RETRIABLE_NAMES = /* @__PURE__ */ new Set([
130
194
  "rate_limit_exceeded",
131
195
  "monthly_quota_exceeded",
@@ -151,7 +215,7 @@ function classifyResendError(error) {
151
215
  }
152
216
  __name(classifyResendError, "classifyResendError");
153
217
  async function initResendClient(config) {
154
- if (!config.apiKey) throw new import_notification_contracts2.ConfigMissingError("apiKey");
218
+ if (!config.apiKey) throw new import_notification_contracts3.ConfigMissingError("apiKey");
155
219
  const { Resend } = await import("resend");
156
220
  return new Resend(config.apiKey);
157
221
  }
@@ -165,16 +229,33 @@ function createResendEmailProvider(config) {
165
229
  }
166
230
  __name(resolveClient, "resolveClient");
167
231
  return {
168
- driver: import_notification_contracts2.EMAIL_DRIVER.RESEND,
232
+ driver: import_notification_contracts3.EMAIL_DRIVER.RESEND,
169
233
  async send(params) {
170
234
  const client = await resolveClient();
235
+ let attachments;
236
+ try {
237
+ attachments = await fetchAttachments(params.attachments);
238
+ } catch (error) {
239
+ if (error instanceof AttachmentFetchError) return {
240
+ outcome: "retriable",
241
+ errorCode: error.errorCode
242
+ };
243
+ throw error;
244
+ }
171
245
  const result = await client.emails.send({
172
246
  from: config.from,
173
247
  to: params.to,
174
248
  subject: params.subject,
175
249
  html: params.html,
176
250
  text: params.text,
177
- replyTo: params.replyTo
251
+ replyTo: params.replyTo,
252
+ ...attachments.length > 0 ? {
253
+ attachments: attachments.map((attachment) => ({
254
+ filename: attachment.filename,
255
+ content: Buffer.from(attachment.content).toString("base64"),
256
+ contentType: attachment.contentType
257
+ }))
258
+ } : {}
178
259
  });
179
260
  if (result.error) return classifyResendError(result.error);
180
261
  return {
@@ -187,7 +268,69 @@ function createResendEmailProvider(config) {
187
268
  __name(createResendEmailProvider, "createResendEmailProvider");
188
269
 
189
270
  // src/SesEmailProvider.ts
190
- var import_notification_contracts3 = require("@adatechnology/notification-contracts");
271
+ var import_notification_contracts4 = require("@adatechnology/notification-contracts");
272
+
273
+ // src/buildMimeMessage.ts
274
+ var CRLF = "\r\n";
275
+ var BASE64_LINE = 76;
276
+ function buildMimeMessage(params) {
277
+ const mixed = newBoundary("mixed");
278
+ const alternative = newBoundary("alt");
279
+ const lines = [
280
+ `From: ${params.from}`,
281
+ `To: ${params.to}`,
282
+ ...params.replyTo ? [
283
+ `Reply-To: ${params.replyTo}`
284
+ ] : [],
285
+ `Subject: ${encodeHeaderValue(params.subject)}`,
286
+ "MIME-Version: 1.0",
287
+ `Content-Type: multipart/mixed; boundary="${mixed}"`,
288
+ "",
289
+ `--${mixed}`,
290
+ `Content-Type: multipart/alternative; boundary="${alternative}"`,
291
+ "",
292
+ `--${alternative}`,
293
+ "Content-Type: text/plain; charset=utf-8",
294
+ "Content-Transfer-Encoding: base64",
295
+ "",
296
+ encodeBase64Lines(new TextEncoder().encode(params.text)),
297
+ `--${alternative}`,
298
+ "Content-Type: text/html; charset=utf-8",
299
+ "Content-Transfer-Encoding: base64",
300
+ "",
301
+ encodeBase64Lines(new TextEncoder().encode(params.html)),
302
+ `--${alternative}--`,
303
+ ""
304
+ ];
305
+ for (const attachment of params.attachments) {
306
+ lines.push(`--${mixed}`, `Content-Type: ${attachment.contentType}; name="${escapeQuoted(attachment.filename)}"`, "Content-Transfer-Encoding: base64", `Content-Disposition: attachment; filename="${escapeQuoted(attachment.filename)}"`, "", encodeBase64Lines(attachment.content));
307
+ }
308
+ lines.push(`--${mixed}--`, "");
309
+ return new TextEncoder().encode(lines.join(CRLF));
310
+ }
311
+ __name(buildMimeMessage, "buildMimeMessage");
312
+ function encodeBase64Lines(bytes) {
313
+ const base64 = Buffer.from(bytes).toString("base64");
314
+ const lines = [];
315
+ for (let index = 0; index < base64.length; index += BASE64_LINE) {
316
+ lines.push(base64.slice(index, index + BASE64_LINE));
317
+ }
318
+ return lines.join(CRLF) + CRLF;
319
+ }
320
+ __name(encodeBase64Lines, "encodeBase64Lines");
321
+ function encodeHeaderValue(value) {
322
+ if (!/[^ -~]/.test(value)) return value;
323
+ return `=?UTF-8?B?${Buffer.from(value, "utf8").toString("base64")}?=`;
324
+ }
325
+ __name(encodeHeaderValue, "encodeHeaderValue");
326
+ function escapeQuoted(value) {
327
+ return value.replace(/["\\]/g, "");
328
+ }
329
+ __name(escapeQuoted, "escapeQuoted");
330
+ function newBoundary(prefix) {
331
+ return `ada-${prefix}-${crypto.randomUUID()}`;
332
+ }
333
+ __name(newBoundary, "newBoundary");
191
334
 
192
335
  // src/SesSendClient.ts
193
336
  function isSesError(error) {
@@ -218,7 +361,7 @@ function classifySesError(error) {
218
361
  }
219
362
  __name(classifySesError, "classifySesError");
220
363
  async function initSesClient(config) {
221
- if (!config.region) throw new import_notification_contracts3.ConfigMissingError("region");
364
+ if (!config.region) throw new import_notification_contracts4.ConfigMissingError("region");
222
365
  const { SESv2Client, SendEmailCommand } = await import("@aws-sdk/client-sesv2");
223
366
  const sesClient = new SESv2Client({
224
367
  region: config.region
@@ -254,6 +397,18 @@ async function initSesClient(config) {
254
397
  return {
255
398
  messageId: response.MessageId
256
399
  };
400
+ },
401
+ async sendRawEmail(params) {
402
+ const response = await sesClient.send(new SendEmailCommand({
403
+ Content: {
404
+ Raw: {
405
+ Data: params.raw
406
+ }
407
+ }
408
+ }));
409
+ return {
410
+ messageId: response.MessageId
411
+ };
257
412
  }
258
413
  };
259
414
  }
@@ -267,17 +422,37 @@ function createSesEmailProvider(config) {
267
422
  }
268
423
  __name(resolveClient, "resolveClient");
269
424
  return {
270
- driver: import_notification_contracts3.EMAIL_DRIVER.SES,
425
+ driver: import_notification_contracts4.EMAIL_DRIVER.SES,
271
426
  async send(params) {
272
427
  const client = await resolveClient();
428
+ let attachments;
273
429
  try {
274
- const result = await client.sendEmail({
430
+ attachments = await fetchAttachments(params.attachments);
431
+ } catch (error) {
432
+ if (error instanceof AttachmentFetchError) return {
433
+ outcome: "retriable",
434
+ errorCode: error.errorCode
435
+ };
436
+ throw error;
437
+ }
438
+ try {
439
+ const result = attachments.length === 0 ? await client.sendEmail({
275
440
  from: config.from,
276
441
  to: params.to,
277
442
  subject: params.subject,
278
443
  html: params.html,
279
444
  text: params.text,
280
445
  replyTo: params.replyTo
446
+ }) : await client.sendRawEmail({
447
+ raw: buildMimeMessage({
448
+ from: config.from,
449
+ to: params.to,
450
+ subject: params.subject,
451
+ html: params.html,
452
+ text: params.text,
453
+ replyTo: params.replyTo,
454
+ attachments
455
+ })
281
456
  });
282
457
  return {
283
458
  outcome: "sent",
@@ -292,18 +467,18 @@ function createSesEmailProvider(config) {
292
467
  __name(createSesEmailProvider, "createSesEmailProvider");
293
468
 
294
469
  // src/EmailProviderFactory.ts
295
- var import_notification_contracts4 = require("@adatechnology/notification-contracts");
470
+ var import_notification_contracts5 = require("@adatechnology/notification-contracts");
296
471
  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);
472
+ if (params.driver === import_notification_contracts5.EMAIL_DRIVER.SMTP) return createSmtpEmailProvider(params);
473
+ if (params.driver === import_notification_contracts5.EMAIL_DRIVER.RESEND) return createResendEmailProvider(params);
474
+ if (params.driver === import_notification_contracts5.EMAIL_DRIVER.SES) return createSesEmailProvider(params);
300
475
  const _exhaustive = params;
301
476
  throw new Error(`Driver de e-mail desconhecido: ${String(_exhaustive.driver)}`);
302
477
  }
303
478
  __name(createEmailProvider, "createEmailProvider");
304
479
 
305
480
  // src/receipts/parseResendWebhook.ts
306
- var import_notification_contracts5 = require("@adatechnology/notification-contracts");
481
+ var import_notification_contracts6 = require("@adatechnology/notification-contracts");
307
482
  function isResendWebhookPayload(value) {
308
483
  if (typeof value !== "object" || value === null) return false;
309
484
  const candidate = value;
@@ -328,7 +503,7 @@ function parseResendWebhook(payload) {
328
503
  return {
329
504
  providerMessageId,
330
505
  status: "bounced",
331
- suppressionReason: import_notification_contracts5.SUPPRESSION_REASON.BOUNCE,
506
+ suppressionReason: import_notification_contracts6.SUPPRESSION_REASON.BOUNCE,
332
507
  errorCode,
333
508
  occurredAt
334
509
  };
@@ -337,7 +512,7 @@ function parseResendWebhook(payload) {
337
512
  return {
338
513
  providerMessageId,
339
514
  status: "failed",
340
- suppressionReason: import_notification_contracts5.SUPPRESSION_REASON.COMPLAINT,
515
+ suppressionReason: import_notification_contracts6.SUPPRESSION_REASON.COMPLAINT,
341
516
  occurredAt
342
517
  };
343
518
  }
@@ -346,7 +521,7 @@ function parseResendWebhook(payload) {
346
521
  __name(parseResendWebhook, "parseResendWebhook");
347
522
 
348
523
  // src/receipts/parseSesNotification.ts
349
- var import_notification_contracts6 = require("@adatechnology/notification-contracts");
524
+ var import_notification_contracts7 = require("@adatechnology/notification-contracts");
350
525
  function parseJson(text) {
351
526
  try {
352
527
  return JSON.parse(text);
@@ -379,7 +554,7 @@ function parseSesNotification(rawBody) {
379
554
  return {
380
555
  providerMessageId,
381
556
  status: "bounced",
382
- suppressionReason: import_notification_contracts6.SUPPRESSION_REASON.BOUNCE,
557
+ suppressionReason: import_notification_contracts7.SUPPRESSION_REASON.BOUNCE,
383
558
  errorCode: `${event.bounce.bounceType}/${event.bounce.bounceSubType}`,
384
559
  occurredAt: new Date(event.bounce.timestamp)
385
560
  };
@@ -388,7 +563,7 @@ function parseSesNotification(rawBody) {
388
563
  return {
389
564
  providerMessageId,
390
565
  status: "failed",
391
- suppressionReason: import_notification_contracts6.SUPPRESSION_REASON.COMPLAINT,
566
+ suppressionReason: import_notification_contracts7.SUPPRESSION_REASON.COMPLAINT,
392
567
  errorCode: event.complaint.complaintFeedbackType,
393
568
  occurredAt: new Date(event.complaint.timestamp)
394
569
  };
@@ -398,10 +573,13 @@ function parseSesNotification(rawBody) {
398
573
  __name(parseSesNotification, "parseSesNotification");
399
574
  // Annotate the CommonJS export names for ESM import in node:
400
575
  0 && (module.exports = {
576
+ AttachmentFetchError,
577
+ buildMimeMessage,
401
578
  createEmailProvider,
402
579
  createResendEmailProvider,
403
580
  createSesEmailProvider,
404
581
  createSmtpEmailProvider,
582
+ fetchAttachments,
405
583
  parseResendWebhook,
406
584
  parseSesNotification
407
585
  });
@@ -1 +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,QAA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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"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/SmtpEmailProvider.ts","../src/fetchAttachments.ts","../src/SmtpTransportClient.ts","../src/ResendEmailProvider.ts","../src/SesEmailProvider.ts","../src/buildMimeMessage.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/** Anexo: download com teto no envio, e o MIME cru que o SES exige. */\nexport { fetchAttachments, AttachmentFetchError } from './fetchAttachments'\nexport type { FetchedAttachment } from './fetchAttachments'\nexport { buildMimeMessage } from './buildMimeMessage'\nexport type { BuildMimeMessageParams } from './buildMimeMessage'\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 { AttachmentFetchError, fetchAttachments } from './fetchAttachments'\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\n /**\n * Anexo antes da conexao: um arquivo inalcancavel nao vira mensagem pela metade, e o motivo\n * fica no `errorCode` da tentativa em vez de virar uma falha generica de SMTP.\n *\n * `retriable` porque a causa e quase sempre a URL assinada vencida ou o storage fora do ar —\n * os dois se resolvem sozinhos numa nova tentativa, com uma assinatura nova.\n */\n let attachments\n try {\n attachments = await fetchAttachments(params.attachments)\n } catch (error) {\n if (error instanceof AttachmentFetchError) return { outcome: 'retriable', errorCode: error.errorCode }\n throw error\n }\n\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 ...(attachments.length > 0\n ? {\n attachments: attachments.map((attachment) => ({\n filename: attachment.filename,\n content: Buffer.from(attachment.content),\n contentType: attachment.contentType,\n })),\n }\n : {}),\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 * Baixa os anexos no momento do envio.\n *\n * O contrato trafega REFERENCIA (`emailAttachment.ts` do contracts): o arquivo vive no storage e a\n * URL assinada chega aqui. Quem baixa e o driver, e nao o modulo, porque o modulo pode decidir nao\n * enviar — supressao, canal desligado, preferencia — e ter carregado 25MB para descobrir isso e\n * desperdicio de memoria num processo que atende outras entregas ao mesmo tempo.\n */\n\nimport {\n EMAIL_ATTACHMENT_MAX_BYTES,\n EMAIL_ATTACHMENT_MAX_COUNT,\n checkEmailAttachment,\n} from '@adatechnology/notification-contracts'\nimport type { EmailAttachment } from '@adatechnology/notification-contracts'\n\n/** O anexo pronto para virar MIME: nome, tipo e os bytes. */\nexport type FetchedAttachment = {\n readonly filename: string\n readonly contentType: string\n readonly content: Uint8Array\n}\n\n/**\n * `Error` e nao `DeliveryAttemptResult`: quem chama e o `send` de cada driver, que ja sabe traduzir\n * falha em resultado de tentativa — e cada um classifica diferente.\n */\nexport class AttachmentFetchError extends Error {\n constructor(readonly errorCode: string) {\n super(`attachment: ${errorCode}`)\n this.name = 'AttachmentFetchError'\n }\n}\n\nexport async function fetchAttachments(\n attachments: readonly EmailAttachment[] | undefined,\n fetchImpl: typeof fetch = fetch,\n): Promise<readonly FetchedAttachment[]> {\n if (!attachments || attachments.length === 0) return []\n\n if (attachments.length > EMAIL_ATTACHMENT_MAX_COUNT) {\n throw new AttachmentFetchError('attachment_count_exceeded')\n }\n\n // Em paralelo: sao arquivos independentes, e em serie o envio esperaria a soma dos downloads.\n const fetched = await Promise.all(attachments.map((attachment) => fetchOne(attachment, fetchImpl)))\n\n /**\n * O teto tambem vale para a SOMA. Dez anexos de 20MB passam um a um e produzem uma mensagem de\n * 200MB que nenhum provedor aceita — e o erro voltaria do provedor como falha generica de envio.\n */\n const total = fetched.reduce((sum, attachment) => sum + attachment.content.byteLength, 0)\n if (total > EMAIL_ATTACHMENT_MAX_BYTES) throw new AttachmentFetchError('attachment_total_too_large')\n\n return fetched\n}\n\nasync function fetchOne(attachment: EmailAttachment, fetchImpl: typeof fetch): Promise<FetchedAttachment> {\n // Antes de qualquer rede: nome com caminho, tipo vazio e URL fora de https nao viram requisicao.\n const problem = checkEmailAttachment(attachment)\n if (problem) throw new AttachmentFetchError(problem.toLowerCase())\n\n const response = await fetchImpl(attachment.url).catch(() => undefined)\n if (!response) throw new AttachmentFetchError('attachment_unreachable')\n if (!response.ok) throw new AttachmentFetchError(`attachment_http_${response.status}`)\n\n /**\n * O `content-length` e conferido ANTES de ler o corpo: sem isso, um objeto trocado no storage\n * entre a assinatura e o envio derrubaria o processo por memoria em vez de reprovar a entrega.\n * Ele e dica, nao garantia — por isso o tamanho real e conferido de novo depois.\n */\n const declared = Number(response.headers.get('content-length'))\n if (Number.isFinite(declared) && declared > EMAIL_ATTACHMENT_MAX_BYTES) {\n throw new AttachmentFetchError('attachment_too_large')\n }\n\n const content = new Uint8Array(await response.arrayBuffer())\n if (content.byteLength > EMAIL_ATTACHMENT_MAX_BYTES) throw new AttachmentFetchError('attachment_too_large')\n if (content.byteLength === 0) throw new AttachmentFetchError('attachment_empty')\n\n return { filename: attachment.filename, contentType: attachment.contentType, content }\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 */\n/**\n * `Buffer` e array mutavel para casar com o `Attachment` do nodemailer: o `Transporter` real\n * precisa continuar satisfazendo esta interface por estrutura, sem cast e sem importar o SDK.\n */\nexport type SmtpAttachment = {\n filename: string\n content: Buffer\n contentType: string\n}\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 /** O nodemailer monta o MIME sozinho — aqui basta entregar os bytes. */\n readonly attachments?: SmtpAttachment[]\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 { AttachmentFetchError, fetchAttachments } from './fetchAttachments'\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\n // Anexo antes da chamada: o Resend leva o arquivo dentro do JSON, entao sem os bytes nao ha o\n // que enviar. `retriable` porque a causa costuma ser assinatura vencida ou storage fora.\n let attachments\n try {\n attachments = await fetchAttachments(params.attachments)\n } catch (error) {\n if (error instanceof AttachmentFetchError) return { outcome: 'retriable', errorCode: error.errorCode }\n throw error\n }\n\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 ...(attachments.length > 0\n ? {\n attachments: attachments.map((attachment) => ({\n filename: attachment.filename,\n content: Buffer.from(attachment.content).toString('base64'),\n contentType: attachment.contentType,\n })),\n }\n : {}),\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 { AttachmentFetchError, fetchAttachments } from './fetchAttachments'\nimport { buildMimeMessage } from './buildMimeMessage'\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 async sendRawEmail(params) {\n const response = await sesClient.send(new SendEmailCommand({ Content: { Raw: { Data: params.raw } } }))\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\n // `retriable` porque a causa costuma ser a URL assinada vencida ou o storage fora do ar — os\n // dois se resolvem numa nova tentativa, com assinatura nova.\n let attachments\n try {\n attachments = await fetchAttachments(params.attachments)\n } catch (error) {\n if (error instanceof AttachmentFetchError) return { outcome: 'retriable', errorCode: error.errorCode }\n throw error\n }\n\n try {\n /**\n * Sem anexo continua no caminho `Simple`, e nao no MIME montado a mao.\n *\n * Nao e otimizacao: o `Simple` deixa a AWS cuidar de codificacao de cabecalho, quebra de\n * linha e charset. Montar MIME quando nao precisa e assumir esse trabalho — e os bugs dele —\n * em todo e-mail do produto, para servir a minoria que leva arquivo.\n */\n const result =\n attachments.length === 0\n ? 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 : await client.sendRawEmail({\n raw: buildMimeMessage({\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 attachments,\n }),\n })\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 * Monta a mensagem MIME crua.\n *\n * Existe por causa do SES: o `SendEmail` do SESv2 so aceita `Simple` — assunto, HTML e texto — e\n * nao tem campo de anexo. Com anexo a unica saida e `Raw`, e ai o MIME inteiro e responsabilidade\n * de quem chama. Nodemailer e Resend montam sozinhos; a AWS nao.\n *\n * A estrutura e a canonica de e-mail com anexo:\n *\n * multipart/mixed\n * multipart/alternative <- as duas versoes do MESMO conteudo\n * text/plain\n * text/html\n * application/pdf <- os anexos, irmaos do conteudo\n *\n * Aninhar o `alternative` dentro do `mixed` nao e detalhe: no mesmo nivel, o cliente trataria o\n * anexo como uma terceira \"versao alternativa\" do corpo e poderia exibi-lo NO LUGAR do texto.\n */\n\nimport type { FetchedAttachment } from './fetchAttachments'\n\nexport type BuildMimeMessageParams = {\n readonly from: string\n readonly to: string\n readonly subject: string\n readonly html: string\n readonly text: string\n readonly replyTo?: string | undefined\n readonly attachments: readonly FetchedAttachment[]\n}\n\nconst CRLF = '\\r\\n'\n\n/** 76 caracteres e o limite de linha do base64 em MIME (RFC 2045). */\nconst BASE64_LINE = 76\n\nexport function buildMimeMessage(params: BuildMimeMessageParams): Uint8Array {\n const mixed = newBoundary('mixed')\n const alternative = newBoundary('alt')\n\n const lines: string[] = [\n `From: ${params.from}`,\n `To: ${params.to}`,\n ...(params.replyTo ? [`Reply-To: ${params.replyTo}`] : []),\n `Subject: ${encodeHeaderValue(params.subject)}`,\n 'MIME-Version: 1.0',\n `Content-Type: multipart/mixed; boundary=\"${mixed}\"`,\n '',\n `--${mixed}`,\n `Content-Type: multipart/alternative; boundary=\"${alternative}\"`,\n '',\n `--${alternative}`,\n 'Content-Type: text/plain; charset=utf-8',\n 'Content-Transfer-Encoding: base64',\n '',\n encodeBase64Lines(new TextEncoder().encode(params.text)),\n `--${alternative}`,\n 'Content-Type: text/html; charset=utf-8',\n 'Content-Transfer-Encoding: base64',\n '',\n encodeBase64Lines(new TextEncoder().encode(params.html)),\n `--${alternative}--`,\n '',\n ]\n\n for (const attachment of params.attachments) {\n lines.push(\n `--${mixed}`,\n `Content-Type: ${attachment.contentType}; name=\"${escapeQuoted(attachment.filename)}\"`,\n 'Content-Transfer-Encoding: base64',\n `Content-Disposition: attachment; filename=\"${escapeQuoted(attachment.filename)}\"`,\n '',\n encodeBase64Lines(attachment.content),\n )\n }\n\n lines.push(`--${mixed}--`, '')\n\n return new TextEncoder().encode(lines.join(CRLF))\n}\n\n/**\n * Corpo e anexo vao em base64, inclusive o texto.\n *\n * Alternativa seria `quoted-printable` para o texto, que e legivel na fonte — e que obriga a\n * escapar `=`, cortar em 76 colunas sem partir caractere multibyte e tratar espaco no fim da linha.\n * Base64 nao tem nenhuma dessas armadilhas, e acento em portugues nao sobrevive a `7bit`.\n */\nfunction encodeBase64Lines(bytes: Uint8Array): string {\n const base64 = Buffer.from(bytes).toString('base64')\n const lines: string[] = []\n\n for (let index = 0; index < base64.length; index += BASE64_LINE) {\n lines.push(base64.slice(index, index + BASE64_LINE))\n }\n\n return lines.join(CRLF) + CRLF\n}\n\n/**\n * Assunto com acento nao pode ir cru: cabecalho e ASCII por definicao (RFC 5322), e um \"Confirmacao\"\n * com cedilha chega como byte quebrado. `=?UTF-8?B?...?=` e a codificacao de palavra do RFC 2047.\n *\n * Assunto ASCII puro fica como esta — codificar tudo esconderia o texto de quem le a fonte sem\n * ganhar nada.\n */\nfunction encodeHeaderValue(value: string): string {\n if (!/[^ -~]/.test(value)) return value\n return `=?UTF-8?B?${Buffer.from(value, 'utf8').toString('base64')}?=`\n}\n\n/**\n * Aspas e barra dentro do nome do arquivo fechariam o parametro do cabecalho e o resto do nome\n * viraria diretiva MIME. O contrato ja recusa caminho no nome; isto e a segunda camada.\n */\nfunction escapeQuoted(value: string): string {\n return value.replace(/[\"\\\\]/g, '')\n}\n\n/**\n * O boundary precisa ser impossivel de aparecer no conteudo: se aparecer, o cliente corta a\n * mensagem no meio do anexo. Aleatorio resolve, e o prefixo so ajuda a ler a fonte.\n */\nfunction newBoundary(prefix: string): string {\n return `ada-${prefix}-${crypto.randomUUID()}`\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\n/**\n * Envio com o MIME ja montado.\n *\n * O `SendEmail` do SESv2 aceita `Simple` (assunto, HTML, texto) OU `Raw`, e so o `Raw` carrega\n * anexo — nao existe campo de anexo no `Simple`. Entao o caminho com anexo e outro comando, com a\n * mensagem inteira serializada por nos (`buildMimeMessage.ts`).\n */\nexport type SesSendRawParams = {\n readonly raw: Uint8Array\n}\n\nexport type SesSendClient = {\n sendEmail(params: SesSendParams): Promise<SesSendResult>\n sendRawEmail(params: SesSendRawParams): 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,IAAAA,iCAAiD;;;ACOjD,oCAIO;AAcA,IAAMC,uBAAN,cAAmCC,MAAAA;EA7B1C,OA6B0CA;;;;EACxC,YAAqBC,WAAmB;AACtC,UAAM,eAAeA,SAAAA,EAAW,GAAA,KADbA,YAAAA;AAEnB,SAAKC,OAAO;EACd;AACF;AAEA,eAAsBC,iBACpBC,aACAC,YAA0BC,OAAK;AAE/B,MAAI,CAACF,eAAeA,YAAYG,WAAW,EAAG,QAAO,CAAA;AAErD,MAAIH,YAAYG,SAASC,0DAA4B;AACnD,UAAM,IAAIT,qBAAqB,2BAAA;EACjC;AAGA,QAAMU,UAAU,MAAMC,QAAQC,IAAIP,YAAYQ,IAAI,CAACC,eAAeC,SAASD,YAAYR,SAAAA,CAAAA,CAAAA;AAMvF,QAAMU,QAAQN,QAAQO,OAAO,CAACC,KAAKJ,eAAeI,MAAMJ,WAAWK,QAAQC,YAAY,CAAA;AACvF,MAAIJ,QAAQK,yDAA4B,OAAM,IAAIrB,qBAAqB,4BAAA;AAEvE,SAAOU;AACT;AArBsBN;AAuBtB,eAAeW,SAASD,YAA6BR,WAAuB;AAE1E,QAAMgB,cAAUC,oDAAqBT,UAAAA;AACrC,MAAIQ,QAAS,OAAM,IAAItB,qBAAqBsB,QAAQE,YAAW,CAAA;AAE/D,QAAMC,WAAW,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AUE,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":["import_notification_contracts","AttachmentFetchError","Error","errorCode","name","fetchAttachments","attachments","fetchImpl","fetch","length","EMAIL_ATTACHMENT_MAX_COUNT","fetched","Promise","all","map","attachment","fetchOne","total","reduce","sum","content","byteLength","EMAIL_ATTACHMENT_MAX_BYTES","problem","checkEmailAttachment","toLowerCase","response","url","catch","undefined","ok","status","declared","Number","headers","get","isFinite","Uint8Array","arrayBuffer","filename","contentType","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","attachments","fetchAttachments","AttachmentFetchError","result","sendMail","from","to","subject","html","text","replyTo","length","map","attachment","filename","content","Buffer","contentType","accepted","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","attachments","fetchAttachments","AttachmentFetchError","result","emails","from","to","subject","html","text","replyTo","length","map","attachment","filename","content","Buffer","toString","contentType","providerMessageId","data","id","import_notification_contracts","CRLF","BASE64_LINE","buildMimeMessage","params","mixed","newBoundary","alternative","lines","from","to","replyTo","encodeHeaderValue","subject","encodeBase64Lines","TextEncoder","encode","text","html","attachment","attachments","push","contentType","escapeQuoted","filename","content","join","bytes","base64","Buffer","toString","index","length","slice","value","test","replace","prefix","crypto","randomUUID","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","sendRawEmail","Raw","raw","createSesEmailProvider","clientPromise","resolveClient","client","Promise","resolve","driver","EMAIL_DRIVER","SES","attachments","fetchAttachments","AttachmentFetchError","result","length","buildMimeMessage","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"]}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { EmailDriverPort, EMAIL_DRIVER, DeliveryReceipt } from '@adatechnology/notification-contracts';
1
+ import { EmailDriverPort, EMAIL_DRIVER, DeliveryReceipt, EmailAttachment } from '@adatechnology/notification-contracts';
2
2
 
3
3
  /**
4
4
  * Copyright (c) 2026 Ada Technology. MIT License.
@@ -7,6 +7,15 @@ import { EmailDriverPort, EMAIL_DRIVER, DeliveryReceipt } from '@adatechnology/n
7
7
  * Forma mínima que o `Transporter` do `nodemailer` já satisfaz. Declarada por estrutura — não
8
8
  * importada do pacote — para os testes injetarem um dublê sem carregar o SDK real.
9
9
  */
10
+ /**
11
+ * `Buffer` e array mutavel para casar com o `Attachment` do nodemailer: o `Transporter` real
12
+ * precisa continuar satisfazendo esta interface por estrutura, sem cast e sem importar o SDK.
13
+ */
14
+ type SmtpAttachment = {
15
+ filename: string;
16
+ content: Buffer;
17
+ contentType: string;
18
+ };
10
19
  type SmtpMailMessage = {
11
20
  readonly from: string;
12
21
  readonly to: string;
@@ -14,6 +23,8 @@ type SmtpMailMessage = {
14
23
  readonly html: string;
15
24
  readonly text: string;
16
25
  readonly replyTo?: string;
26
+ /** O nodemailer monta o MIME sozinho — aqui basta entregar os bytes. */
27
+ readonly attachments?: SmtpAttachment[];
17
28
  };
18
29
  type SmtpSendResult = {
19
30
  readonly messageId: string;
@@ -62,6 +73,13 @@ type ResendSendResult = {
62
73
  readonly statusCode: number | null;
63
74
  } | null;
64
75
  };
76
+ /** Mutavel para casar por estrutura com o `Attachment` do SDK do Resend, sem importa-lo. */
77
+ type ResendAttachment = {
78
+ filename: string;
79
+ /** Base64 do arquivo. O SDK aceita `Buffer` tambem, mas a string atravessa o JSON sem surpresa. */
80
+ content: string;
81
+ contentType: string;
82
+ };
65
83
  type ResendEmailsClient = {
66
84
  send(message: {
67
85
  readonly from: string;
@@ -70,6 +88,11 @@ type ResendEmailsClient = {
70
88
  readonly html: string;
71
89
  readonly text: string;
72
90
  readonly replyTo?: string;
91
+ /**
92
+ * O Resend recebe o arquivo no proprio JSON, em base64 — nao ha upload separado nem URL. Por
93
+ * isso o driver baixa antes: o que ele envia e conteudo, nao referencia.
94
+ */
95
+ readonly attachments?: ResendAttachment[];
73
96
  }): Promise<ResendSendResult>;
74
97
  };
75
98
  type ResendClientLike = {
@@ -106,8 +129,19 @@ type SesSendParams = {
106
129
  type SesSendResult = {
107
130
  readonly messageId?: string;
108
131
  };
132
+ /**
133
+ * Envio com o MIME ja montado.
134
+ *
135
+ * O `SendEmail` do SESv2 aceita `Simple` (assunto, HTML, texto) OU `Raw`, e so o `Raw` carrega
136
+ * anexo — nao existe campo de anexo no `Simple`. Entao o caminho com anexo e outro comando, com a
137
+ * mensagem inteira serializada por nos (`buildMimeMessage.ts`).
138
+ */
139
+ type SesSendRawParams = {
140
+ readonly raw: Uint8Array;
141
+ };
109
142
  type SesSendClient = {
110
143
  sendEmail(params: SesSendParams): Promise<SesSendResult>;
144
+ sendRawEmail(params: SesSendRawParams): Promise<SesSendResult>;
111
145
  };
112
146
  type SesError = {
113
147
  readonly name: string;
@@ -159,4 +193,63 @@ declare function parseResendWebhook(payload: unknown): DeliveryReceipt | undefin
159
193
  /** `undefined` para envelope malformado, confirmação de assinatura da SNS, ou tipo desconhecido. */
160
194
  declare function parseSesNotification(rawBody: string): DeliveryReceipt | undefined;
161
195
 
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 };
196
+ /**
197
+ * Copyright (c) 2026 Ada Technology. MIT License.
198
+ *
199
+ * Baixa os anexos no momento do envio.
200
+ *
201
+ * O contrato trafega REFERENCIA (`emailAttachment.ts` do contracts): o arquivo vive no storage e a
202
+ * URL assinada chega aqui. Quem baixa e o driver, e nao o modulo, porque o modulo pode decidir nao
203
+ * enviar — supressao, canal desligado, preferencia — e ter carregado 25MB para descobrir isso e
204
+ * desperdicio de memoria num processo que atende outras entregas ao mesmo tempo.
205
+ */
206
+
207
+ /** O anexo pronto para virar MIME: nome, tipo e os bytes. */
208
+ type FetchedAttachment = {
209
+ readonly filename: string;
210
+ readonly contentType: string;
211
+ readonly content: Uint8Array;
212
+ };
213
+ /**
214
+ * `Error` e nao `DeliveryAttemptResult`: quem chama e o `send` de cada driver, que ja sabe traduzir
215
+ * falha em resultado de tentativa — e cada um classifica diferente.
216
+ */
217
+ declare class AttachmentFetchError extends Error {
218
+ readonly errorCode: string;
219
+ constructor(errorCode: string);
220
+ }
221
+ declare function fetchAttachments(attachments: readonly EmailAttachment[] | undefined, fetchImpl?: typeof fetch): Promise<readonly FetchedAttachment[]>;
222
+
223
+ /**
224
+ * Copyright (c) 2026 Ada Technology. MIT License.
225
+ *
226
+ * Monta a mensagem MIME crua.
227
+ *
228
+ * Existe por causa do SES: o `SendEmail` do SESv2 so aceita `Simple` — assunto, HTML e texto — e
229
+ * nao tem campo de anexo. Com anexo a unica saida e `Raw`, e ai o MIME inteiro e responsabilidade
230
+ * de quem chama. Nodemailer e Resend montam sozinhos; a AWS nao.
231
+ *
232
+ * A estrutura e a canonica de e-mail com anexo:
233
+ *
234
+ * multipart/mixed
235
+ * multipart/alternative <- as duas versoes do MESMO conteudo
236
+ * text/plain
237
+ * text/html
238
+ * application/pdf <- os anexos, irmaos do conteudo
239
+ *
240
+ * Aninhar o `alternative` dentro do `mixed` nao e detalhe: no mesmo nivel, o cliente trataria o
241
+ * anexo como uma terceira "versao alternativa" do corpo e poderia exibi-lo NO LUGAR do texto.
242
+ */
243
+
244
+ type BuildMimeMessageParams = {
245
+ readonly from: string;
246
+ readonly to: string;
247
+ readonly subject: string;
248
+ readonly html: string;
249
+ readonly text: string;
250
+ readonly replyTo?: string | undefined;
251
+ readonly attachments: readonly FetchedAttachment[];
252
+ };
253
+ declare function buildMimeMessage(params: BuildMimeMessageParams): Uint8Array;
254
+
255
+ export { AttachmentFetchError, type BuildMimeMessageParams, type CreateEmailProviderParams, type FetchedAttachment, 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, buildMimeMessage, createEmailProvider, createResendEmailProvider, createSesEmailProvider, createSmtpEmailProvider, fetchAttachments, parseResendWebhook, parseSesNotification };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { EmailDriverPort, EMAIL_DRIVER, DeliveryReceipt } from '@adatechnology/notification-contracts';
1
+ import { EmailDriverPort, EMAIL_DRIVER, DeliveryReceipt, EmailAttachment } from '@adatechnology/notification-contracts';
2
2
 
3
3
  /**
4
4
  * Copyright (c) 2026 Ada Technology. MIT License.
@@ -7,6 +7,15 @@ import { EmailDriverPort, EMAIL_DRIVER, DeliveryReceipt } from '@adatechnology/n
7
7
  * Forma mínima que o `Transporter` do `nodemailer` já satisfaz. Declarada por estrutura — não
8
8
  * importada do pacote — para os testes injetarem um dublê sem carregar o SDK real.
9
9
  */
10
+ /**
11
+ * `Buffer` e array mutavel para casar com o `Attachment` do nodemailer: o `Transporter` real
12
+ * precisa continuar satisfazendo esta interface por estrutura, sem cast e sem importar o SDK.
13
+ */
14
+ type SmtpAttachment = {
15
+ filename: string;
16
+ content: Buffer;
17
+ contentType: string;
18
+ };
10
19
  type SmtpMailMessage = {
11
20
  readonly from: string;
12
21
  readonly to: string;
@@ -14,6 +23,8 @@ type SmtpMailMessage = {
14
23
  readonly html: string;
15
24
  readonly text: string;
16
25
  readonly replyTo?: string;
26
+ /** O nodemailer monta o MIME sozinho — aqui basta entregar os bytes. */
27
+ readonly attachments?: SmtpAttachment[];
17
28
  };
18
29
  type SmtpSendResult = {
19
30
  readonly messageId: string;
@@ -62,6 +73,13 @@ type ResendSendResult = {
62
73
  readonly statusCode: number | null;
63
74
  } | null;
64
75
  };
76
+ /** Mutavel para casar por estrutura com o `Attachment` do SDK do Resend, sem importa-lo. */
77
+ type ResendAttachment = {
78
+ filename: string;
79
+ /** Base64 do arquivo. O SDK aceita `Buffer` tambem, mas a string atravessa o JSON sem surpresa. */
80
+ content: string;
81
+ contentType: string;
82
+ };
65
83
  type ResendEmailsClient = {
66
84
  send(message: {
67
85
  readonly from: string;
@@ -70,6 +88,11 @@ type ResendEmailsClient = {
70
88
  readonly html: string;
71
89
  readonly text: string;
72
90
  readonly replyTo?: string;
91
+ /**
92
+ * O Resend recebe o arquivo no proprio JSON, em base64 — nao ha upload separado nem URL. Por
93
+ * isso o driver baixa antes: o que ele envia e conteudo, nao referencia.
94
+ */
95
+ readonly attachments?: ResendAttachment[];
73
96
  }): Promise<ResendSendResult>;
74
97
  };
75
98
  type ResendClientLike = {
@@ -106,8 +129,19 @@ type SesSendParams = {
106
129
  type SesSendResult = {
107
130
  readonly messageId?: string;
108
131
  };
132
+ /**
133
+ * Envio com o MIME ja montado.
134
+ *
135
+ * O `SendEmail` do SESv2 aceita `Simple` (assunto, HTML, texto) OU `Raw`, e so o `Raw` carrega
136
+ * anexo — nao existe campo de anexo no `Simple`. Entao o caminho com anexo e outro comando, com a
137
+ * mensagem inteira serializada por nos (`buildMimeMessage.ts`).
138
+ */
139
+ type SesSendRawParams = {
140
+ readonly raw: Uint8Array;
141
+ };
109
142
  type SesSendClient = {
110
143
  sendEmail(params: SesSendParams): Promise<SesSendResult>;
144
+ sendRawEmail(params: SesSendRawParams): Promise<SesSendResult>;
111
145
  };
112
146
  type SesError = {
113
147
  readonly name: string;
@@ -159,4 +193,63 @@ declare function parseResendWebhook(payload: unknown): DeliveryReceipt | undefin
159
193
  /** `undefined` para envelope malformado, confirmação de assinatura da SNS, ou tipo desconhecido. */
160
194
  declare function parseSesNotification(rawBody: string): DeliveryReceipt | undefined;
161
195
 
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 };
196
+ /**
197
+ * Copyright (c) 2026 Ada Technology. MIT License.
198
+ *
199
+ * Baixa os anexos no momento do envio.
200
+ *
201
+ * O contrato trafega REFERENCIA (`emailAttachment.ts` do contracts): o arquivo vive no storage e a
202
+ * URL assinada chega aqui. Quem baixa e o driver, e nao o modulo, porque o modulo pode decidir nao
203
+ * enviar — supressao, canal desligado, preferencia — e ter carregado 25MB para descobrir isso e
204
+ * desperdicio de memoria num processo que atende outras entregas ao mesmo tempo.
205
+ */
206
+
207
+ /** O anexo pronto para virar MIME: nome, tipo e os bytes. */
208
+ type FetchedAttachment = {
209
+ readonly filename: string;
210
+ readonly contentType: string;
211
+ readonly content: Uint8Array;
212
+ };
213
+ /**
214
+ * `Error` e nao `DeliveryAttemptResult`: quem chama e o `send` de cada driver, que ja sabe traduzir
215
+ * falha em resultado de tentativa — e cada um classifica diferente.
216
+ */
217
+ declare class AttachmentFetchError extends Error {
218
+ readonly errorCode: string;
219
+ constructor(errorCode: string);
220
+ }
221
+ declare function fetchAttachments(attachments: readonly EmailAttachment[] | undefined, fetchImpl?: typeof fetch): Promise<readonly FetchedAttachment[]>;
222
+
223
+ /**
224
+ * Copyright (c) 2026 Ada Technology. MIT License.
225
+ *
226
+ * Monta a mensagem MIME crua.
227
+ *
228
+ * Existe por causa do SES: o `SendEmail` do SESv2 so aceita `Simple` — assunto, HTML e texto — e
229
+ * nao tem campo de anexo. Com anexo a unica saida e `Raw`, e ai o MIME inteiro e responsabilidade
230
+ * de quem chama. Nodemailer e Resend montam sozinhos; a AWS nao.
231
+ *
232
+ * A estrutura e a canonica de e-mail com anexo:
233
+ *
234
+ * multipart/mixed
235
+ * multipart/alternative <- as duas versoes do MESMO conteudo
236
+ * text/plain
237
+ * text/html
238
+ * application/pdf <- os anexos, irmaos do conteudo
239
+ *
240
+ * Aninhar o `alternative` dentro do `mixed` nao e detalhe: no mesmo nivel, o cliente trataria o
241
+ * anexo como uma terceira "versao alternativa" do corpo e poderia exibi-lo NO LUGAR do texto.
242
+ */
243
+
244
+ type BuildMimeMessageParams = {
245
+ readonly from: string;
246
+ readonly to: string;
247
+ readonly subject: string;
248
+ readonly html: string;
249
+ readonly text: string;
250
+ readonly replyTo?: string | undefined;
251
+ readonly attachments: readonly FetchedAttachment[];
252
+ };
253
+ declare function buildMimeMessage(params: BuildMimeMessageParams): Uint8Array;
254
+
255
+ export { AttachmentFetchError, type BuildMimeMessageParams, type CreateEmailProviderParams, type FetchedAttachment, 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, buildMimeMessage, createEmailProvider, createResendEmailProvider, createSesEmailProvider, createSmtpEmailProvider, fetchAttachments, parseResendWebhook, parseSesNotification };
package/dist/index.js CHANGED
@@ -4,6 +4,50 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable:
4
4
  // src/SmtpEmailProvider.ts
5
5
  import { ConfigMissingError, EMAIL_DRIVER } from "@adatechnology/notification-contracts";
6
6
 
7
+ // src/fetchAttachments.ts
8
+ import { EMAIL_ATTACHMENT_MAX_BYTES, EMAIL_ATTACHMENT_MAX_COUNT, checkEmailAttachment } from "@adatechnology/notification-contracts";
9
+ var AttachmentFetchError = class extends Error {
10
+ static {
11
+ __name(this, "AttachmentFetchError");
12
+ }
13
+ errorCode;
14
+ constructor(errorCode) {
15
+ super(`attachment: ${errorCode}`), this.errorCode = errorCode;
16
+ this.name = "AttachmentFetchError";
17
+ }
18
+ };
19
+ async function fetchAttachments(attachments, fetchImpl = fetch) {
20
+ if (!attachments || attachments.length === 0) return [];
21
+ if (attachments.length > EMAIL_ATTACHMENT_MAX_COUNT) {
22
+ throw new AttachmentFetchError("attachment_count_exceeded");
23
+ }
24
+ const fetched = await Promise.all(attachments.map((attachment) => fetchOne(attachment, fetchImpl)));
25
+ const total = fetched.reduce((sum, attachment) => sum + attachment.content.byteLength, 0);
26
+ if (total > EMAIL_ATTACHMENT_MAX_BYTES) throw new AttachmentFetchError("attachment_total_too_large");
27
+ return fetched;
28
+ }
29
+ __name(fetchAttachments, "fetchAttachments");
30
+ async function fetchOne(attachment, fetchImpl) {
31
+ const problem = checkEmailAttachment(attachment);
32
+ if (problem) throw new AttachmentFetchError(problem.toLowerCase());
33
+ const response = await fetchImpl(attachment.url).catch(() => void 0);
34
+ if (!response) throw new AttachmentFetchError("attachment_unreachable");
35
+ if (!response.ok) throw new AttachmentFetchError(`attachment_http_${response.status}`);
36
+ const declared = Number(response.headers.get("content-length"));
37
+ if (Number.isFinite(declared) && declared > EMAIL_ATTACHMENT_MAX_BYTES) {
38
+ throw new AttachmentFetchError("attachment_too_large");
39
+ }
40
+ const content = new Uint8Array(await response.arrayBuffer());
41
+ if (content.byteLength > EMAIL_ATTACHMENT_MAX_BYTES) throw new AttachmentFetchError("attachment_too_large");
42
+ if (content.byteLength === 0) throw new AttachmentFetchError("attachment_empty");
43
+ return {
44
+ filename: attachment.filename,
45
+ contentType: attachment.contentType,
46
+ content
47
+ };
48
+ }
49
+ __name(fetchOne, "fetchOne");
50
+
7
51
  // src/SmtpTransportClient.ts
8
52
  function isSmtpError(error) {
9
53
  return typeof error === "object" && error !== null;
@@ -58,6 +102,16 @@ function createSmtpEmailProvider(config) {
58
102
  driver: EMAIL_DRIVER.SMTP,
59
103
  async send(params) {
60
104
  const client = await resolveClient();
105
+ let attachments;
106
+ try {
107
+ attachments = await fetchAttachments(params.attachments);
108
+ } catch (error) {
109
+ if (error instanceof AttachmentFetchError) return {
110
+ outcome: "retriable",
111
+ errorCode: error.errorCode
112
+ };
113
+ throw error;
114
+ }
61
115
  try {
62
116
  const result = await client.sendMail({
63
117
  from: config.from,
@@ -65,7 +119,14 @@ function createSmtpEmailProvider(config) {
65
119
  subject: params.subject,
66
120
  html: params.html,
67
121
  text: params.text,
68
- replyTo: params.replyTo
122
+ replyTo: params.replyTo,
123
+ ...attachments.length > 0 ? {
124
+ attachments: attachments.map((attachment) => ({
125
+ filename: attachment.filename,
126
+ content: Buffer.from(attachment.content),
127
+ contentType: attachment.contentType
128
+ }))
129
+ } : {}
69
130
  });
70
131
  if (result.accepted.length === 0 && result.rejected.length > 0) {
71
132
  return {
@@ -129,13 +190,30 @@ function createResendEmailProvider(config) {
129
190
  driver: EMAIL_DRIVER2.RESEND,
130
191
  async send(params) {
131
192
  const client = await resolveClient();
193
+ let attachments;
194
+ try {
195
+ attachments = await fetchAttachments(params.attachments);
196
+ } catch (error) {
197
+ if (error instanceof AttachmentFetchError) return {
198
+ outcome: "retriable",
199
+ errorCode: error.errorCode
200
+ };
201
+ throw error;
202
+ }
132
203
  const result = await client.emails.send({
133
204
  from: config.from,
134
205
  to: params.to,
135
206
  subject: params.subject,
136
207
  html: params.html,
137
208
  text: params.text,
138
- replyTo: params.replyTo
209
+ replyTo: params.replyTo,
210
+ ...attachments.length > 0 ? {
211
+ attachments: attachments.map((attachment) => ({
212
+ filename: attachment.filename,
213
+ content: Buffer.from(attachment.content).toString("base64"),
214
+ contentType: attachment.contentType
215
+ }))
216
+ } : {}
139
217
  });
140
218
  if (result.error) return classifyResendError(result.error);
141
219
  return {
@@ -150,6 +228,68 @@ __name(createResendEmailProvider, "createResendEmailProvider");
150
228
  // src/SesEmailProvider.ts
151
229
  import { ConfigMissingError as ConfigMissingError3, EMAIL_DRIVER as EMAIL_DRIVER3 } from "@adatechnology/notification-contracts";
152
230
 
231
+ // src/buildMimeMessage.ts
232
+ var CRLF = "\r\n";
233
+ var BASE64_LINE = 76;
234
+ function buildMimeMessage(params) {
235
+ const mixed = newBoundary("mixed");
236
+ const alternative = newBoundary("alt");
237
+ const lines = [
238
+ `From: ${params.from}`,
239
+ `To: ${params.to}`,
240
+ ...params.replyTo ? [
241
+ `Reply-To: ${params.replyTo}`
242
+ ] : [],
243
+ `Subject: ${encodeHeaderValue(params.subject)}`,
244
+ "MIME-Version: 1.0",
245
+ `Content-Type: multipart/mixed; boundary="${mixed}"`,
246
+ "",
247
+ `--${mixed}`,
248
+ `Content-Type: multipart/alternative; boundary="${alternative}"`,
249
+ "",
250
+ `--${alternative}`,
251
+ "Content-Type: text/plain; charset=utf-8",
252
+ "Content-Transfer-Encoding: base64",
253
+ "",
254
+ encodeBase64Lines(new TextEncoder().encode(params.text)),
255
+ `--${alternative}`,
256
+ "Content-Type: text/html; charset=utf-8",
257
+ "Content-Transfer-Encoding: base64",
258
+ "",
259
+ encodeBase64Lines(new TextEncoder().encode(params.html)),
260
+ `--${alternative}--`,
261
+ ""
262
+ ];
263
+ for (const attachment of params.attachments) {
264
+ lines.push(`--${mixed}`, `Content-Type: ${attachment.contentType}; name="${escapeQuoted(attachment.filename)}"`, "Content-Transfer-Encoding: base64", `Content-Disposition: attachment; filename="${escapeQuoted(attachment.filename)}"`, "", encodeBase64Lines(attachment.content));
265
+ }
266
+ lines.push(`--${mixed}--`, "");
267
+ return new TextEncoder().encode(lines.join(CRLF));
268
+ }
269
+ __name(buildMimeMessage, "buildMimeMessage");
270
+ function encodeBase64Lines(bytes) {
271
+ const base64 = Buffer.from(bytes).toString("base64");
272
+ const lines = [];
273
+ for (let index = 0; index < base64.length; index += BASE64_LINE) {
274
+ lines.push(base64.slice(index, index + BASE64_LINE));
275
+ }
276
+ return lines.join(CRLF) + CRLF;
277
+ }
278
+ __name(encodeBase64Lines, "encodeBase64Lines");
279
+ function encodeHeaderValue(value) {
280
+ if (!/[^ -~]/.test(value)) return value;
281
+ return `=?UTF-8?B?${Buffer.from(value, "utf8").toString("base64")}?=`;
282
+ }
283
+ __name(encodeHeaderValue, "encodeHeaderValue");
284
+ function escapeQuoted(value) {
285
+ return value.replace(/["\\]/g, "");
286
+ }
287
+ __name(escapeQuoted, "escapeQuoted");
288
+ function newBoundary(prefix) {
289
+ return `ada-${prefix}-${crypto.randomUUID()}`;
290
+ }
291
+ __name(newBoundary, "newBoundary");
292
+
153
293
  // src/SesSendClient.ts
154
294
  function isSesError(error) {
155
295
  return typeof error === "object" && error !== null && "name" in error && typeof error.name === "string";
@@ -215,6 +355,18 @@ async function initSesClient(config) {
215
355
  return {
216
356
  messageId: response.MessageId
217
357
  };
358
+ },
359
+ async sendRawEmail(params) {
360
+ const response = await sesClient.send(new SendEmailCommand({
361
+ Content: {
362
+ Raw: {
363
+ Data: params.raw
364
+ }
365
+ }
366
+ }));
367
+ return {
368
+ messageId: response.MessageId
369
+ };
218
370
  }
219
371
  };
220
372
  }
@@ -231,14 +383,34 @@ function createSesEmailProvider(config) {
231
383
  driver: EMAIL_DRIVER3.SES,
232
384
  async send(params) {
233
385
  const client = await resolveClient();
386
+ let attachments;
387
+ try {
388
+ attachments = await fetchAttachments(params.attachments);
389
+ } catch (error) {
390
+ if (error instanceof AttachmentFetchError) return {
391
+ outcome: "retriable",
392
+ errorCode: error.errorCode
393
+ };
394
+ throw error;
395
+ }
234
396
  try {
235
- const result = await client.sendEmail({
397
+ const result = attachments.length === 0 ? await client.sendEmail({
236
398
  from: config.from,
237
399
  to: params.to,
238
400
  subject: params.subject,
239
401
  html: params.html,
240
402
  text: params.text,
241
403
  replyTo: params.replyTo
404
+ }) : await client.sendRawEmail({
405
+ raw: buildMimeMessage({
406
+ from: config.from,
407
+ to: params.to,
408
+ subject: params.subject,
409
+ html: params.html,
410
+ text: params.text,
411
+ replyTo: params.replyTo,
412
+ attachments
413
+ })
242
414
  });
243
415
  return {
244
416
  outcome: "sent",
@@ -358,10 +530,13 @@ function parseSesNotification(rawBody) {
358
530
  }
359
531
  __name(parseSesNotification, "parseSesNotification");
360
532
  export {
533
+ AttachmentFetchError,
534
+ buildMimeMessage,
361
535
  createEmailProvider,
362
536
  createResendEmailProvider,
363
537
  createSesEmailProvider,
364
538
  createSmtpEmailProvider,
539
+ fetchAttachments,
365
540
  parseResendWebhook,
366
541
  parseSesNotification
367
542
  };
package/dist/index.js.map CHANGED
@@ -1 +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;IAAk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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,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"]}
1
+ {"version":3,"sources":["../src/SmtpEmailProvider.ts","../src/fetchAttachments.ts","../src/SmtpTransportClient.ts","../src/ResendEmailProvider.ts","../src/SesEmailProvider.ts","../src/buildMimeMessage.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 { AttachmentFetchError, fetchAttachments } from './fetchAttachments'\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\n /**\n * Anexo antes da conexao: um arquivo inalcancavel nao vira mensagem pela metade, e o motivo\n * fica no `errorCode` da tentativa em vez de virar uma falha generica de SMTP.\n *\n * `retriable` porque a causa e quase sempre a URL assinada vencida ou o storage fora do ar —\n * os dois se resolvem sozinhos numa nova tentativa, com uma assinatura nova.\n */\n let attachments\n try {\n attachments = await fetchAttachments(params.attachments)\n } catch (error) {\n if (error instanceof AttachmentFetchError) return { outcome: 'retriable', errorCode: error.errorCode }\n throw error\n }\n\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 ...(attachments.length > 0\n ? {\n attachments: attachments.map((attachment) => ({\n filename: attachment.filename,\n content: Buffer.from(attachment.content),\n contentType: attachment.contentType,\n })),\n }\n : {}),\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 * Baixa os anexos no momento do envio.\n *\n * O contrato trafega REFERENCIA (`emailAttachment.ts` do contracts): o arquivo vive no storage e a\n * URL assinada chega aqui. Quem baixa e o driver, e nao o modulo, porque o modulo pode decidir nao\n * enviar — supressao, canal desligado, preferencia — e ter carregado 25MB para descobrir isso e\n * desperdicio de memoria num processo que atende outras entregas ao mesmo tempo.\n */\n\nimport {\n EMAIL_ATTACHMENT_MAX_BYTES,\n EMAIL_ATTACHMENT_MAX_COUNT,\n checkEmailAttachment,\n} from '@adatechnology/notification-contracts'\nimport type { EmailAttachment } from '@adatechnology/notification-contracts'\n\n/** O anexo pronto para virar MIME: nome, tipo e os bytes. */\nexport type FetchedAttachment = {\n readonly filename: string\n readonly contentType: string\n readonly content: Uint8Array\n}\n\n/**\n * `Error` e nao `DeliveryAttemptResult`: quem chama e o `send` de cada driver, que ja sabe traduzir\n * falha em resultado de tentativa — e cada um classifica diferente.\n */\nexport class AttachmentFetchError extends Error {\n constructor(readonly errorCode: string) {\n super(`attachment: ${errorCode}`)\n this.name = 'AttachmentFetchError'\n }\n}\n\nexport async function fetchAttachments(\n attachments: readonly EmailAttachment[] | undefined,\n fetchImpl: typeof fetch = fetch,\n): Promise<readonly FetchedAttachment[]> {\n if (!attachments || attachments.length === 0) return []\n\n if (attachments.length > EMAIL_ATTACHMENT_MAX_COUNT) {\n throw new AttachmentFetchError('attachment_count_exceeded')\n }\n\n // Em paralelo: sao arquivos independentes, e em serie o envio esperaria a soma dos downloads.\n const fetched = await Promise.all(attachments.map((attachment) => fetchOne(attachment, fetchImpl)))\n\n /**\n * O teto tambem vale para a SOMA. Dez anexos de 20MB passam um a um e produzem uma mensagem de\n * 200MB que nenhum provedor aceita — e o erro voltaria do provedor como falha generica de envio.\n */\n const total = fetched.reduce((sum, attachment) => sum + attachment.content.byteLength, 0)\n if (total > EMAIL_ATTACHMENT_MAX_BYTES) throw new AttachmentFetchError('attachment_total_too_large')\n\n return fetched\n}\n\nasync function fetchOne(attachment: EmailAttachment, fetchImpl: typeof fetch): Promise<FetchedAttachment> {\n // Antes de qualquer rede: nome com caminho, tipo vazio e URL fora de https nao viram requisicao.\n const problem = checkEmailAttachment(attachment)\n if (problem) throw new AttachmentFetchError(problem.toLowerCase())\n\n const response = await fetchImpl(attachment.url).catch(() => undefined)\n if (!response) throw new AttachmentFetchError('attachment_unreachable')\n if (!response.ok) throw new AttachmentFetchError(`attachment_http_${response.status}`)\n\n /**\n * O `content-length` e conferido ANTES de ler o corpo: sem isso, um objeto trocado no storage\n * entre a assinatura e o envio derrubaria o processo por memoria em vez de reprovar a entrega.\n * Ele e dica, nao garantia — por isso o tamanho real e conferido de novo depois.\n */\n const declared = Number(response.headers.get('content-length'))\n if (Number.isFinite(declared) && declared > EMAIL_ATTACHMENT_MAX_BYTES) {\n throw new AttachmentFetchError('attachment_too_large')\n }\n\n const content = new Uint8Array(await response.arrayBuffer())\n if (content.byteLength > EMAIL_ATTACHMENT_MAX_BYTES) throw new AttachmentFetchError('attachment_too_large')\n if (content.byteLength === 0) throw new AttachmentFetchError('attachment_empty')\n\n return { filename: attachment.filename, contentType: attachment.contentType, content }\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 */\n/**\n * `Buffer` e array mutavel para casar com o `Attachment` do nodemailer: o `Transporter` real\n * precisa continuar satisfazendo esta interface por estrutura, sem cast e sem importar o SDK.\n */\nexport type SmtpAttachment = {\n filename: string\n content: Buffer\n contentType: string\n}\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 /** O nodemailer monta o MIME sozinho — aqui basta entregar os bytes. */\n readonly attachments?: SmtpAttachment[]\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 { AttachmentFetchError, fetchAttachments } from './fetchAttachments'\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\n // Anexo antes da chamada: o Resend leva o arquivo dentro do JSON, entao sem os bytes nao ha o\n // que enviar. `retriable` porque a causa costuma ser assinatura vencida ou storage fora.\n let attachments\n try {\n attachments = await fetchAttachments(params.attachments)\n } catch (error) {\n if (error instanceof AttachmentFetchError) return { outcome: 'retriable', errorCode: error.errorCode }\n throw error\n }\n\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 ...(attachments.length > 0\n ? {\n attachments: attachments.map((attachment) => ({\n filename: attachment.filename,\n content: Buffer.from(attachment.content).toString('base64'),\n contentType: attachment.contentType,\n })),\n }\n : {}),\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 { AttachmentFetchError, fetchAttachments } from './fetchAttachments'\nimport { buildMimeMessage } from './buildMimeMessage'\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 async sendRawEmail(params) {\n const response = await sesClient.send(new SendEmailCommand({ Content: { Raw: { Data: params.raw } } }))\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\n // `retriable` porque a causa costuma ser a URL assinada vencida ou o storage fora do ar — os\n // dois se resolvem numa nova tentativa, com assinatura nova.\n let attachments\n try {\n attachments = await fetchAttachments(params.attachments)\n } catch (error) {\n if (error instanceof AttachmentFetchError) return { outcome: 'retriable', errorCode: error.errorCode }\n throw error\n }\n\n try {\n /**\n * Sem anexo continua no caminho `Simple`, e nao no MIME montado a mao.\n *\n * Nao e otimizacao: o `Simple` deixa a AWS cuidar de codificacao de cabecalho, quebra de\n * linha e charset. Montar MIME quando nao precisa e assumir esse trabalho — e os bugs dele —\n * em todo e-mail do produto, para servir a minoria que leva arquivo.\n */\n const result =\n attachments.length === 0\n ? 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 : await client.sendRawEmail({\n raw: buildMimeMessage({\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 attachments,\n }),\n })\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 * Monta a mensagem MIME crua.\n *\n * Existe por causa do SES: o `SendEmail` do SESv2 so aceita `Simple` — assunto, HTML e texto — e\n * nao tem campo de anexo. Com anexo a unica saida e `Raw`, e ai o MIME inteiro e responsabilidade\n * de quem chama. Nodemailer e Resend montam sozinhos; a AWS nao.\n *\n * A estrutura e a canonica de e-mail com anexo:\n *\n * multipart/mixed\n * multipart/alternative <- as duas versoes do MESMO conteudo\n * text/plain\n * text/html\n * application/pdf <- os anexos, irmaos do conteudo\n *\n * Aninhar o `alternative` dentro do `mixed` nao e detalhe: no mesmo nivel, o cliente trataria o\n * anexo como uma terceira \"versao alternativa\" do corpo e poderia exibi-lo NO LUGAR do texto.\n */\n\nimport type { FetchedAttachment } from './fetchAttachments'\n\nexport type BuildMimeMessageParams = {\n readonly from: string\n readonly to: string\n readonly subject: string\n readonly html: string\n readonly text: string\n readonly replyTo?: string | undefined\n readonly attachments: readonly FetchedAttachment[]\n}\n\nconst CRLF = '\\r\\n'\n\n/** 76 caracteres e o limite de linha do base64 em MIME (RFC 2045). */\nconst BASE64_LINE = 76\n\nexport function buildMimeMessage(params: BuildMimeMessageParams): Uint8Array {\n const mixed = newBoundary('mixed')\n const alternative = newBoundary('alt')\n\n const lines: string[] = [\n `From: ${params.from}`,\n `To: ${params.to}`,\n ...(params.replyTo ? [`Reply-To: ${params.replyTo}`] : []),\n `Subject: ${encodeHeaderValue(params.subject)}`,\n 'MIME-Version: 1.0',\n `Content-Type: multipart/mixed; boundary=\"${mixed}\"`,\n '',\n `--${mixed}`,\n `Content-Type: multipart/alternative; boundary=\"${alternative}\"`,\n '',\n `--${alternative}`,\n 'Content-Type: text/plain; charset=utf-8',\n 'Content-Transfer-Encoding: base64',\n '',\n encodeBase64Lines(new TextEncoder().encode(params.text)),\n `--${alternative}`,\n 'Content-Type: text/html; charset=utf-8',\n 'Content-Transfer-Encoding: base64',\n '',\n encodeBase64Lines(new TextEncoder().encode(params.html)),\n `--${alternative}--`,\n '',\n ]\n\n for (const attachment of params.attachments) {\n lines.push(\n `--${mixed}`,\n `Content-Type: ${attachment.contentType}; name=\"${escapeQuoted(attachment.filename)}\"`,\n 'Content-Transfer-Encoding: base64',\n `Content-Disposition: attachment; filename=\"${escapeQuoted(attachment.filename)}\"`,\n '',\n encodeBase64Lines(attachment.content),\n )\n }\n\n lines.push(`--${mixed}--`, '')\n\n return new TextEncoder().encode(lines.join(CRLF))\n}\n\n/**\n * Corpo e anexo vao em base64, inclusive o texto.\n *\n * Alternativa seria `quoted-printable` para o texto, que e legivel na fonte — e que obriga a\n * escapar `=`, cortar em 76 colunas sem partir caractere multibyte e tratar espaco no fim da linha.\n * Base64 nao tem nenhuma dessas armadilhas, e acento em portugues nao sobrevive a `7bit`.\n */\nfunction encodeBase64Lines(bytes: Uint8Array): string {\n const base64 = Buffer.from(bytes).toString('base64')\n const lines: string[] = []\n\n for (let index = 0; index < base64.length; index += BASE64_LINE) {\n lines.push(base64.slice(index, index + BASE64_LINE))\n }\n\n return lines.join(CRLF) + CRLF\n}\n\n/**\n * Assunto com acento nao pode ir cru: cabecalho e ASCII por definicao (RFC 5322), e um \"Confirmacao\"\n * com cedilha chega como byte quebrado. `=?UTF-8?B?...?=` e a codificacao de palavra do RFC 2047.\n *\n * Assunto ASCII puro fica como esta — codificar tudo esconderia o texto de quem le a fonte sem\n * ganhar nada.\n */\nfunction encodeHeaderValue(value: string): string {\n if (!/[^ -~]/.test(value)) return value\n return `=?UTF-8?B?${Buffer.from(value, 'utf8').toString('base64')}?=`\n}\n\n/**\n * Aspas e barra dentro do nome do arquivo fechariam o parametro do cabecalho e o resto do nome\n * viraria diretiva MIME. O contrato ja recusa caminho no nome; isto e a segunda camada.\n */\nfunction escapeQuoted(value: string): string {\n return value.replace(/[\"\\\\]/g, '')\n}\n\n/**\n * O boundary precisa ser impossivel de aparecer no conteudo: se aparecer, o cliente corta a\n * mensagem no meio do anexo. Aleatorio resolve, e o prefixo so ajuda a ler a fonte.\n */\nfunction newBoundary(prefix: string): string {\n return `ada-${prefix}-${crypto.randomUUID()}`\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\n/**\n * Envio com o MIME ja montado.\n *\n * O `SendEmail` do SESv2 aceita `Simple` (assunto, HTML, texto) OU `Raw`, e so o `Raw` carrega\n * anexo — nao existe campo de anexo no `Simple`. Entao o caminho com anexo e outro comando, com a\n * mensagem inteira serializada por nos (`buildMimeMessage.ts`).\n */\nexport type SesSendRawParams = {\n readonly raw: Uint8Array\n}\n\nexport type SesSendClient = {\n sendEmail(params: SesSendParams): Promise<SesSendResult>\n sendRawEmail(params: SesSendRawParams): 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;;;ACOjD,SACEC,4BACAC,4BACAC,4BACK;AAcA,IAAMC,uBAAN,cAAmCC,MAAAA;EA7B1C,OA6B0CA;;;;EACxC,YAAqBC,WAAmB;AACtC,UAAM,eAAeA,SAAAA,EAAW,GAAA,KADbA,YAAAA;AAEnB,SAAKC,OAAO;EACd;AACF;AAEA,eAAsBC,iBACpBC,aACAC,YAA0BC,OAAK;AAE/B,MAAI,CAACF,eAAeA,YAAYG,WAAW,EAAG,QAAO,CAAA;AAErD,MAAIH,YAAYG,SAASC,4BAA4B;AACnD,UAAM,IAAIT,qBAAqB,2BAAA;EACjC;AAGA,QAAMU,UAAU,MAAMC,QAAQC,IAAIP,YAAYQ,IAAI,CAACC,eAAeC,SAASD,YAAYR,SAAAA,CAAAA,CAAAA;AAMvF,QAAMU,QAAQN,QAAQO,OAAO,CAACC,KAAKJ,eAAeI,MAAMJ,WAAWK,QAAQC,YAAY,CAAA;AACvF,MAAIJ,QAAQK,2BAA4B,OAAM,IAAIrB,qBAAqB,4BAAA;AAEvE,SAAOU;AACT;AArBsBN;AAuBtB,eAAeW,SAASD,YAA6BR,WAAuB;AAE1E,QAAMgB,UAAUC,qBAAqBT,UAAAA;AACrC,MAAIQ,QAAS,OAAM,IAAItB,qBAAqBsB,QAAQE,YAAW,CAAA;AAE/D,QAAMC,WAAW,MAAMnB,UAAUQ,WAAWY,GAAG,EAAEC,MAAM,MAAMC,MAAAA;AAC7D,MAAI,CAACH,SAAU,OAAM,IAAIzB,qBAAqB,wBAAA;AAC9C,MAAI,CAACyB,SAASI,GAAI,OAAM,IAAI7B,qBAAqB,mBAAmByB,SAASK,MAAM,EAAE;AAOrF,QAAMC,WAAWC,OAAOP,SAASQ,QAAQC,IAAI,gBAAA,CAAA;AAC7C,MAAIF,OAAO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AAO;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,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","EMAIL_ATTACHMENT_MAX_BYTES","EMAIL_ATTACHMENT_MAX_COUNT","checkEmailAttachment","AttachmentFetchError","Error","errorCode","name","fetchAttachments","attachments","fetchImpl","fetch","length","EMAIL_ATTACHMENT_MAX_COUNT","fetched","Promise","all","map","attachment","fetchOne","total","reduce","sum","content","byteLength","EMAIL_ATTACHMENT_MAX_BYTES","problem","checkEmailAttachment","toLowerCase","response","url","catch","undefined","ok","status","declared","Number","headers","get","isFinite","Uint8Array","arrayBuffer","filename","contentType","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","attachments","fetchAttachments","AttachmentFetchError","result","sendMail","from","to","subject","html","text","replyTo","length","map","attachment","filename","content","Buffer","contentType","accepted","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","attachments","fetchAttachments","AttachmentFetchError","result","emails","from","to","subject","html","text","replyTo","length","map","attachment","filename","content","Buffer","toString","contentType","providerMessageId","data","id","ConfigMissingError","EMAIL_DRIVER","CRLF","BASE64_LINE","buildMimeMessage","params","mixed","newBoundary","alternative","lines","from","to","replyTo","encodeHeaderValue","subject","encodeBase64Lines","TextEncoder","encode","text","html","attachment","attachments","push","contentType","escapeQuoted","filename","content","join","bytes","base64","Buffer","toString","index","length","slice","value","test","replace","prefix","crypto","randomUUID","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","sendRawEmail","Raw","raw","createSesEmailProvider","clientPromise","resolveClient","client","Promise","resolve","driver","EMAIL_DRIVER","SES","attachments","fetchAttachments","AttachmentFetchError","result","length","buildMimeMessage","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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adatechnology/email-provider",
3
- "version": "0.1.0-rc.5",
3
+ "version": "0.1.0-rc.7",
4
4
  "description": "Stateless email providers (SMTP, Resend, SES) behind a single port — part of the notification trio",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -21,7 +21,7 @@
21
21
  "dist"
22
22
  ],
23
23
  "dependencies": {
24
- "@adatechnology/notification-contracts": "0.1.0-rc.5"
24
+ "@adatechnology/notification-contracts": "0.1.0-rc.6"
25
25
  },
26
26
  "peerDependencies": {
27
27
  "nodemailer": ">=6.9.0 <10",