import { EasySesError } from './errors.js'; export type SesEventType = | 'send' | 'delivered' | 'bounced' | 'complained' | 'rejected' | 'delayed' | 'opened' | 'clicked' | 'rendering_failure' | 'other'; export interface SesEvent { type: SesEventType; /** The SES MessageId, the same one send() returned. */ messageId: string; /** Addresses this event is about. */ recipients: string[]; timestamp?: string; /** True for a permanent bounce or a complaint: stop mailing these addresses. */ shouldSuppress: boolean; /** Bounce, delay, reject or failure reason when SES gave one. */ reason?: string; /** Tags you set on send(), first value of each. */ tags: Record; /** SES eventType string as received, for example "Bounce". */ sesEventType: string; /** The parsed SES event, for anything not mapped above. */ raw: any; } const TYPE_MAP: Record = { send: 'send', delivery: 'delivered', bounce: 'bounced', complaint: 'complained', reject: 'rejected', deliverydelay: 'delayed', open: 'opened', click: 'clicked', 'rendering failure': 'rendering_failure', }; function fail(msg: string): never { throw new EasySesError('VALIDATION', `Not an SES event: ${msg}`); } function parseJson(s: string): any { try { return JSON.parse(s); } catch { return fail('body is not JSON'); } } /** Unwraps an SQS message body or an SNS envelope until we reach the SES event itself. */ function unwrap(input: unknown): any { let cur: any = typeof input === 'string' ? parseJson(input) : input; for (let i = 0; i < 4; i++) { if (cur && typeof cur === 'object' && typeof cur.Message === 'string' && (cur.Type === 'Notification' || cur.TopicArn)) { cur = parseJson(cur.Message); // SNS envelope } else if (cur && typeof cur === 'object' && typeof cur.body === 'string' && !cur.mail) { cur = parseJson(cur.body); // SQS record or Lambda event record } else break; } return cur; } /** * Turns one SES event into a simple shape. Accepts the SES JSON as an object or string, * wrapped or not: raw SNS-to-SQS delivery, the SNS envelope, or an SQS record with a `body`. * Works with both `eventType` (configuration set) and the older `notificationType`. * Does NOT verify SNS signatures. If you receive over HTTP, verify them in your endpoint. */ export function parseSesEvent(input: unknown): SesEvent { const e = unwrap(input); if (!e || typeof e !== 'object') fail('empty'); const kind: string | undefined = e.eventType ?? e.notificationType; if (!kind || !e.mail?.messageId) fail('missing eventType or mail.messageId'); const type = TYPE_MAP[String(kind).toLowerCase()] ?? 'other'; const mail = e.mail; let recipients: string[] = mail.destination ?? []; let reason: string | undefined; let timestamp: string | undefined; let shouldSuppress = false; if (type === 'bounced' && e.bounce) { recipients = (e.bounce.bouncedRecipients ?? []).map((r: any) => r.emailAddress); reason = [e.bounce.bounceType, e.bounce.bounceSubType, e.bounce.bouncedRecipients?.[0]?.diagnosticCode] .filter(Boolean).join(' / '); timestamp = e.bounce.timestamp; shouldSuppress = e.bounce.bounceType === 'Permanent'; } else if (type === 'complained' && e.complaint) { recipients = (e.complaint.complainedRecipients ?? []).map((r: any) => r.emailAddress); reason = e.complaint.complaintFeedbackType; timestamp = e.complaint.timestamp; shouldSuppress = true; } else if (type === 'delivered' && e.delivery) { recipients = e.delivery.recipients ?? recipients; timestamp = e.delivery.timestamp; } else if (type === 'delayed' && e.deliveryDelay) { recipients = (e.deliveryDelay.delayedRecipients ?? []).map((r: any) => r.emailAddress); reason = e.deliveryDelay.delayType; timestamp = e.deliveryDelay.timestamp; } else if (type === 'rejected' && e.reject) { reason = e.reject.reason; } else if (type === 'rendering_failure' && e.failure) { reason = e.failure.errorMessage; } else if ((type === 'opened' || type === 'clicked') && e[kind.toLowerCase()]) { timestamp = e[kind.toLowerCase()].timestamp; } timestamp ??= mail.timestamp; const tags: Record = {}; for (const [k, v] of Object.entries(mail.tags ?? {})) tags[k] = Array.isArray(v) ? String(v[0]) : String(v); return { type, messageId: mail.messageId, recipients, timestamp, shouldSuppress, reason, tags, sesEventType: String(kind), raw: e }; }