|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { getNotificationUrl, getProviderConfig } from '@/lib/webhooks/providers/subscription-utils' |
| 3 | +import type { |
| 4 | + DeleteSubscriptionContext, |
| 5 | + FormatInputContext, |
| 6 | + FormatInputResult, |
| 7 | + SubscriptionContext, |
| 8 | + SubscriptionResult, |
| 9 | + WebhookProviderHandler, |
| 10 | +} from '@/lib/webhooks/providers/types' |
| 11 | + |
| 12 | +const logger = createLogger('WebhookProvider:Resend') |
| 13 | + |
| 14 | +const ALL_RESEND_EVENTS = [ |
| 15 | + 'email.sent', |
| 16 | + 'email.delivered', |
| 17 | + 'email.delivery_delayed', |
| 18 | + 'email.bounced', |
| 19 | + 'email.complained', |
| 20 | + 'email.opened', |
| 21 | + 'email.clicked', |
| 22 | + 'email.failed', |
| 23 | + 'email.received', |
| 24 | + 'email.scheduled', |
| 25 | + 'email.suppressed', |
| 26 | + 'contact.created', |
| 27 | + 'contact.updated', |
| 28 | + 'contact.deleted', |
| 29 | + 'domain.created', |
| 30 | + 'domain.updated', |
| 31 | + 'domain.deleted', |
| 32 | +] |
| 33 | + |
| 34 | +export const resendHandler: WebhookProviderHandler = { |
| 35 | + async formatInput({ body }: FormatInputContext): Promise<FormatInputResult> { |
| 36 | + const payload = body as Record<string, unknown> |
| 37 | + const data = payload.data as Record<string, unknown> | undefined |
| 38 | + const bounce = data?.bounce as Record<string, unknown> | undefined |
| 39 | + const click = data?.click as Record<string, unknown> | undefined |
| 40 | + |
| 41 | + return { |
| 42 | + input: { |
| 43 | + type: payload.type, |
| 44 | + created_at: payload.created_at, |
| 45 | + email_id: data?.email_id ?? null, |
| 46 | + from: data?.from ?? null, |
| 47 | + to: data?.to ?? null, |
| 48 | + subject: data?.subject ?? null, |
| 49 | + bounceType: bounce?.type ?? null, |
| 50 | + bounceSubType: bounce?.subType ?? null, |
| 51 | + bounceMessage: bounce?.message ?? null, |
| 52 | + clickIpAddress: click?.ipAddress ?? null, |
| 53 | + clickLink: click?.link ?? null, |
| 54 | + clickTimestamp: click?.timestamp ?? null, |
| 55 | + clickUserAgent: click?.userAgent ?? null, |
| 56 | + }, |
| 57 | + } |
| 58 | + }, |
| 59 | + |
| 60 | + async createSubscription(ctx: SubscriptionContext): Promise<SubscriptionResult | undefined> { |
| 61 | + const { webhook, requestId } = ctx |
| 62 | + try { |
| 63 | + const providerConfig = getProviderConfig(webhook) |
| 64 | + const apiKey = providerConfig.apiKey as string | undefined |
| 65 | + const triggerId = providerConfig.triggerId as string | undefined |
| 66 | + |
| 67 | + if (!apiKey) { |
| 68 | + logger.warn(`[${requestId}] Missing apiKey for Resend webhook creation.`, { |
| 69 | + webhookId: webhook.id, |
| 70 | + }) |
| 71 | + throw new Error( |
| 72 | + 'Resend API Key is required. Please provide your Resend API Key in the trigger configuration.' |
| 73 | + ) |
| 74 | + } |
| 75 | + |
| 76 | + const eventTypeMap: Record<string, string[]> = { |
| 77 | + resend_email_sent: ['email.sent'], |
| 78 | + resend_email_delivered: ['email.delivered'], |
| 79 | + resend_email_bounced: ['email.bounced'], |
| 80 | + resend_email_complained: ['email.complained'], |
| 81 | + resend_email_opened: ['email.opened'], |
| 82 | + resend_email_clicked: ['email.clicked'], |
| 83 | + resend_email_failed: ['email.failed'], |
| 84 | + resend_webhook: ALL_RESEND_EVENTS, |
| 85 | + } |
| 86 | + |
| 87 | + const events = eventTypeMap[triggerId ?? ''] ?? ALL_RESEND_EVENTS |
| 88 | + const notificationUrl = getNotificationUrl(webhook) |
| 89 | + |
| 90 | + logger.info(`[${requestId}] Creating Resend webhook`, { |
| 91 | + triggerId, |
| 92 | + events, |
| 93 | + webhookId: webhook.id, |
| 94 | + }) |
| 95 | + |
| 96 | + const resendResponse = await fetch('https://api.resend.com/webhooks', { |
| 97 | + method: 'POST', |
| 98 | + headers: { |
| 99 | + Authorization: `Bearer ${apiKey}`, |
| 100 | + 'Content-Type': 'application/json', |
| 101 | + }, |
| 102 | + body: JSON.stringify({ |
| 103 | + endpoint: notificationUrl, |
| 104 | + events, |
| 105 | + }), |
| 106 | + }) |
| 107 | + |
| 108 | + const responseBody = (await resendResponse.json()) as Record<string, unknown> |
| 109 | + |
| 110 | + if (!resendResponse.ok) { |
| 111 | + const errorMessage = |
| 112 | + (responseBody.message as string) || |
| 113 | + (responseBody.name as string) || |
| 114 | + 'Unknown Resend API error' |
| 115 | + logger.error( |
| 116 | + `[${requestId}] Failed to create webhook in Resend for webhook ${webhook.id}. Status: ${resendResponse.status}`, |
| 117 | + { message: errorMessage, response: responseBody } |
| 118 | + ) |
| 119 | + |
| 120 | + let userFriendlyMessage = 'Failed to create webhook subscription in Resend' |
| 121 | + if (resendResponse.status === 401 || resendResponse.status === 403) { |
| 122 | + userFriendlyMessage = 'Invalid Resend API Key. Please verify your API Key is correct.' |
| 123 | + } else if (errorMessage && errorMessage !== 'Unknown Resend API error') { |
| 124 | + userFriendlyMessage = `Resend error: ${errorMessage}` |
| 125 | + } |
| 126 | + |
| 127 | + throw new Error(userFriendlyMessage) |
| 128 | + } |
| 129 | + |
| 130 | + logger.info( |
| 131 | + `[${requestId}] Successfully created webhook in Resend for webhook ${webhook.id}.`, |
| 132 | + { |
| 133 | + resendWebhookId: responseBody.id, |
| 134 | + } |
| 135 | + ) |
| 136 | + |
| 137 | + return { providerConfigUpdates: { externalId: responseBody.id } } |
| 138 | + } catch (error: unknown) { |
| 139 | + const err = error as Error |
| 140 | + logger.error( |
| 141 | + `[${requestId}] Exception during Resend webhook creation for webhook ${webhook.id}.`, |
| 142 | + { |
| 143 | + message: err.message, |
| 144 | + stack: err.stack, |
| 145 | + } |
| 146 | + ) |
| 147 | + throw error |
| 148 | + } |
| 149 | + }, |
| 150 | + |
| 151 | + async deleteSubscription(ctx: DeleteSubscriptionContext): Promise<void> { |
| 152 | + const { webhook, requestId } = ctx |
| 153 | + try { |
| 154 | + const config = getProviderConfig(webhook) |
| 155 | + const apiKey = config.apiKey as string | undefined |
| 156 | + const externalId = config.externalId as string | undefined |
| 157 | + |
| 158 | + if (!apiKey || !externalId) { |
| 159 | + logger.warn( |
| 160 | + `[${requestId}] Missing apiKey or externalId for Resend webhook deletion ${webhook.id}, skipping cleanup` |
| 161 | + ) |
| 162 | + return |
| 163 | + } |
| 164 | + |
| 165 | + const resendResponse = await fetch(`https://api.resend.com/webhooks/${externalId}`, { |
| 166 | + method: 'DELETE', |
| 167 | + headers: { |
| 168 | + Authorization: `Bearer ${apiKey}`, |
| 169 | + }, |
| 170 | + }) |
| 171 | + |
| 172 | + if (!resendResponse.ok && resendResponse.status !== 404) { |
| 173 | + const responseBody = await resendResponse.json().catch(() => ({})) |
| 174 | + logger.warn( |
| 175 | + `[${requestId}] Failed to delete Resend webhook (non-fatal): ${resendResponse.status}`, |
| 176 | + { response: responseBody } |
| 177 | + ) |
| 178 | + } else { |
| 179 | + logger.info(`[${requestId}] Successfully deleted Resend webhook ${externalId}`) |
| 180 | + } |
| 181 | + } catch (error) { |
| 182 | + logger.warn(`[${requestId}] Error deleting Resend webhook (non-fatal)`, error) |
| 183 | + } |
| 184 | + }, |
| 185 | +} |
0 commit comments