@bernierllc/email-webhook-events 1.4.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/EmailWebhookEventsService.js +4 -0
- package/dist/EmailWebhookEventsService.js.map +1 -1
- package/dist/analytics/AnalyticsEngine.js +2 -1
- package/dist/analytics/AnalyticsEngine.js.map +1 -1
- package/dist/errors.d.ts +12 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +25 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/persistence/InMemoryPersistenceAdapter.js +2 -4
- package/dist/persistence/InMemoryPersistenceAdapter.js.map +1 -1
- package/package.json +6 -2
- package/.eslintrc.cjs +0 -30
- package/CHANGELOG.md +0 -131
- package/__tests__/EmailWebhookEventsService.test.ts +0 -251
- package/__tests__/WebhookEventCallbacks.test.ts +0 -343
- package/__tests__/analytics/AnalyticsEngine.test.ts +0 -250
- package/__tests__/fixtures/sendgrid-webhooks/.gitkeep +0 -0
- package/__tests__/fixtures/sendgrid-webhooks/README.md +0 -63
- package/__tests__/fixtures/sendgrid-webhooks/deferred.json +0 -31
- package/__tests__/fixtures/sendgrid-webhooks/delivered.json +0 -83
- package/__tests__/fixtures/sendgrid-webhooks/open.json +0 -83
- package/__tests__/integration/ngrok-tunnel-manager.ts +0 -88
- package/__tests__/integration/sendgrid-webhook-integration.test.ts +0 -272
- package/__tests__/integration/webhook-server.ts +0 -188
- package/__tests__/mocks/README.md +0 -172
- package/__tests__/mocks/index.ts +0 -94
- package/__tests__/mocks/sendgrid-api-responses.ts +0 -391
- package/__tests__/mocks/sendgrid-webhook-payloads.ts +0 -463
- package/__tests__/normalizers/MailgunNormalizer.test.ts +0 -149
- package/__tests__/normalizers/PostmarkNormalizer.test.ts +0 -112
- package/__tests__/normalizers/SESNormalizer.test.ts +0 -168
- package/__tests__/normalizers/SMTP2GONormalizer.test.ts +0 -83
- package/__tests__/normalizers/SendGridNormalizer.test.ts +0 -181
- package/__tests__/persistence/PersistenceAdapter.test.ts +0 -103
- package/jest.config.cjs +0 -38
- package/src/EmailWebhookEventsService.ts +0 -290
- package/src/analytics/AnalyticsEngine.ts +0 -230
- package/src/index.ts +0 -40
- package/src/normalizers/EventNormalizer.ts +0 -13
- package/src/normalizers/MailgunNormalizer.ts +0 -72
- package/src/normalizers/PostmarkNormalizer.ts +0 -72
- package/src/normalizers/SESNormalizer.ts +0 -117
- package/src/normalizers/SMTP2GONormalizer.ts +0 -54
- package/src/normalizers/SendGridNormalizer.ts +0 -63
- package/src/persistence/InMemoryPersistenceAdapter.ts +0 -68
- package/src/persistence/PersistenceAdapter.ts +0 -15
- package/src/types.ts +0 -261
- package/tsconfig.json +0 -31
|
@@ -1,290 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
Copyright (c) 2025 Bernier LLC
|
|
3
|
-
|
|
4
|
-
This file is licensed to the client under a limited-use license.
|
|
5
|
-
The client may use and modify this code *only within the scope of the project it was delivered for*.
|
|
6
|
-
Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
import {
|
|
10
|
-
EmailWebhookEventsConfig,
|
|
11
|
-
EmailWebhookResult,
|
|
12
|
-
WebhookPayload,
|
|
13
|
-
EmailEvent,
|
|
14
|
-
EmailAnalytics,
|
|
15
|
-
EmailEventType,
|
|
16
|
-
EmailProvider,
|
|
17
|
-
AnalyticsFilters,
|
|
18
|
-
EventQuery,
|
|
19
|
-
NotificationChannel
|
|
20
|
-
} from './types';
|
|
21
|
-
import { AnalyticsEngine } from './analytics/AnalyticsEngine';
|
|
22
|
-
import { PersistenceAdapter } from './persistence/PersistenceAdapter';
|
|
23
|
-
import { InMemoryPersistenceAdapter } from './persistence/InMemoryPersistenceAdapter';
|
|
24
|
-
import { EventNormalizer } from './normalizers/EventNormalizer';
|
|
25
|
-
import { SendGridNormalizer } from './normalizers/SendGridNormalizer';
|
|
26
|
-
import { MailgunNormalizer } from './normalizers/MailgunNormalizer';
|
|
27
|
-
import { SESNormalizer } from './normalizers/SESNormalizer';
|
|
28
|
-
import { PostmarkNormalizer } from './normalizers/PostmarkNormalizer';
|
|
29
|
-
import { SMTP2GONormalizer } from './normalizers/SMTP2GONormalizer';
|
|
30
|
-
|
|
31
|
-
// Mock logger interface (since @bernierllc/logger is not published yet)
|
|
32
|
-
interface Logger {
|
|
33
|
-
info(message: string, meta?: Record<string, unknown>): void;
|
|
34
|
-
warn(message: string, meta?: Record<string, unknown>): void;
|
|
35
|
-
error(message: string, meta?: Record<string, unknown>): void;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
class MockLogger implements Logger {
|
|
39
|
-
info(message: string, meta?: Record<string, unknown>): void {
|
|
40
|
-
console.log(`[INFO] ${message}`, meta || '');
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
warn(message: string, meta?: Record<string, unknown>): void {
|
|
44
|
-
console.warn(`[WARN] ${message}`, meta || '');
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
error(message: string, meta?: Record<string, unknown>): void {
|
|
48
|
-
console.error(`[ERROR] ${message}`, meta || '');
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export class EmailWebhookEventsService {
|
|
53
|
-
private logger: Logger;
|
|
54
|
-
private persistenceAdapter?: PersistenceAdapter;
|
|
55
|
-
private analyticsEngine: AnalyticsEngine;
|
|
56
|
-
|
|
57
|
-
constructor(private config: EmailWebhookEventsConfig) {
|
|
58
|
-
this.logger = new MockLogger();
|
|
59
|
-
this.analyticsEngine = new AnalyticsEngine(config.analytics);
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* Initialize the service
|
|
64
|
-
*/
|
|
65
|
-
async initialize(): Promise<void> {
|
|
66
|
-
// Initialize persistence
|
|
67
|
-
if (this.config.persistence?.enabled) {
|
|
68
|
-
this.persistenceAdapter = await this.createPersistenceAdapter();
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
this.logger.info('Email webhook events service initialized');
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* Process incoming webhook
|
|
76
|
-
*/
|
|
77
|
-
async processWebhook(webhook: WebhookPayload): Promise<EmailWebhookResult> {
|
|
78
|
-
try {
|
|
79
|
-
// Validate webhook signature would happen here
|
|
80
|
-
// For now, we'll assume validation passes
|
|
81
|
-
|
|
82
|
-
// Normalize event
|
|
83
|
-
const normalizedEvent = await this.normalizeEvent(webhook);
|
|
84
|
-
if (!normalizedEvent) {
|
|
85
|
-
this.logger.warn('Failed to normalize webhook event', {
|
|
86
|
-
provider: webhook.provider
|
|
87
|
-
});
|
|
88
|
-
return { success: false, error: 'Event normalization failed' };
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// Persist event
|
|
92
|
-
if (this.persistenceAdapter) {
|
|
93
|
-
await this.persistenceAdapter.saveEvent(normalizedEvent);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// Update analytics
|
|
97
|
-
await this.analyticsEngine.recordEvent(normalizedEvent);
|
|
98
|
-
|
|
99
|
-
// Invoke event callbacks
|
|
100
|
-
await this.invokeCallbacks(normalizedEvent);
|
|
101
|
-
|
|
102
|
-
// Publish critical events
|
|
103
|
-
if (this.isCriticalEvent(normalizedEvent)) {
|
|
104
|
-
await this.publishCriticalEvent(normalizedEvent);
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
this.logger.info('Email event processed successfully', {
|
|
108
|
-
eventId: normalizedEvent.id,
|
|
109
|
-
type: normalizedEvent.type,
|
|
110
|
-
recipient: normalizedEvent.recipient
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
return { success: true, event: normalizedEvent };
|
|
114
|
-
|
|
115
|
-
} catch (error) {
|
|
116
|
-
this.logger.error('Error processing email webhook', {
|
|
117
|
-
error: error instanceof Error ? error.message : 'Unknown error',
|
|
118
|
-
provider: webhook.provider
|
|
119
|
-
});
|
|
120
|
-
return {
|
|
121
|
-
success: false,
|
|
122
|
-
error: error instanceof Error ? error.message : 'Unknown error'
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
* Get analytics for date range
|
|
129
|
-
*/
|
|
130
|
-
async getAnalytics(
|
|
131
|
-
startDate: Date,
|
|
132
|
-
endDate: Date,
|
|
133
|
-
filters?: AnalyticsFilters
|
|
134
|
-
): Promise<EmailAnalytics> {
|
|
135
|
-
return this.analyticsEngine.getAnalytics(startDate, endDate, filters);
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* Query events
|
|
140
|
-
*/
|
|
141
|
-
async queryEvents(query: EventQuery): Promise<EmailEvent[]> {
|
|
142
|
-
if (!this.persistenceAdapter) {
|
|
143
|
-
throw new Error('Event persistence not enabled');
|
|
144
|
-
}
|
|
145
|
-
return this.persistenceAdapter.queryEvents(query);
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* Get events for specific email
|
|
150
|
-
*/
|
|
151
|
-
async getEventsForEmail(emailId: string): Promise<EmailEvent[]> {
|
|
152
|
-
return this.queryEvents({ emailId });
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Normalize webhook event to unified format
|
|
157
|
-
*/
|
|
158
|
-
private async normalizeEvent(webhook: WebhookPayload): Promise<EmailEvent | null> {
|
|
159
|
-
const normalizer = this.getNormalizerForProvider(webhook.provider);
|
|
160
|
-
if (!normalizer) {
|
|
161
|
-
this.logger.error('No normalizer found for provider', {
|
|
162
|
-
provider: webhook.provider
|
|
163
|
-
});
|
|
164
|
-
return null;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
return normalizer.normalize(webhook);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/**
|
|
171
|
-
* Get normalizer for provider
|
|
172
|
-
*/
|
|
173
|
-
private getNormalizerForProvider(provider: EmailProvider): EventNormalizer | null {
|
|
174
|
-
switch (provider) {
|
|
175
|
-
case EmailProvider.SENDGRID:
|
|
176
|
-
return new SendGridNormalizer();
|
|
177
|
-
case EmailProvider.MAILGUN:
|
|
178
|
-
return new MailgunNormalizer();
|
|
179
|
-
case EmailProvider.AWS_SES:
|
|
180
|
-
return new SESNormalizer();
|
|
181
|
-
case EmailProvider.POSTMARK:
|
|
182
|
-
return new PostmarkNormalizer();
|
|
183
|
-
case EmailProvider.SMTP2GO:
|
|
184
|
-
return new SMTP2GONormalizer();
|
|
185
|
-
default:
|
|
186
|
-
return null;
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
/**
|
|
191
|
-
* Check if event is critical (requires notification)
|
|
192
|
-
*/
|
|
193
|
-
private isCriticalEvent(event: EmailEvent): boolean {
|
|
194
|
-
const criticalTypes = this.config.notifications?.criticalEvents || [
|
|
195
|
-
EmailEventType.BOUNCED,
|
|
196
|
-
EmailEventType.COMPLAINED,
|
|
197
|
-
EmailEventType.FAILED
|
|
198
|
-
];
|
|
199
|
-
return criticalTypes.includes(event.type);
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
/**
|
|
203
|
-
* Publish critical event to notification channels
|
|
204
|
-
*/
|
|
205
|
-
private async publishCriticalEvent(event: EmailEvent): Promise<void> {
|
|
206
|
-
if (!this.config.notifications?.enabled) return;
|
|
207
|
-
|
|
208
|
-
for (const channel of this.config.notifications.channels) {
|
|
209
|
-
try {
|
|
210
|
-
await this.sendNotification(channel, event);
|
|
211
|
-
} catch (error) {
|
|
212
|
-
this.logger.error('Failed to send notification', {
|
|
213
|
-
channel: channel.type,
|
|
214
|
-
error: error instanceof Error ? error.message : 'Unknown error'
|
|
215
|
-
});
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
/**
|
|
221
|
-
* Send notification via channel
|
|
222
|
-
*/
|
|
223
|
-
private async sendNotification(
|
|
224
|
-
channel: NotificationChannel,
|
|
225
|
-
event: EmailEvent
|
|
226
|
-
): Promise<void> {
|
|
227
|
-
// In a real implementation, this would send notifications
|
|
228
|
-
// For now, just log
|
|
229
|
-
this.logger.info('Critical event notification', {
|
|
230
|
-
channel: channel.type,
|
|
231
|
-
eventType: event.type,
|
|
232
|
-
recipient: event.recipient
|
|
233
|
-
});
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
/**
|
|
237
|
-
* Invoke registered event callbacks
|
|
238
|
-
*/
|
|
239
|
-
private async invokeCallbacks(event: EmailEvent): Promise<void> {
|
|
240
|
-
const callbacks = this.config.callbacks;
|
|
241
|
-
if (!callbacks) return;
|
|
242
|
-
|
|
243
|
-
try {
|
|
244
|
-
switch (event.type) {
|
|
245
|
-
case EmailEventType.BOUNCED:
|
|
246
|
-
await callbacks.onBounce?.(event);
|
|
247
|
-
break;
|
|
248
|
-
case EmailEventType.COMPLAINED:
|
|
249
|
-
await callbacks.onComplaint?.(event);
|
|
250
|
-
break;
|
|
251
|
-
case EmailEventType.UNSUBSCRIBED:
|
|
252
|
-
await callbacks.onUnsubscribe?.(event);
|
|
253
|
-
break;
|
|
254
|
-
case EmailEventType.DELIVERED:
|
|
255
|
-
await callbacks.onDelivery?.(event);
|
|
256
|
-
break;
|
|
257
|
-
case EmailEventType.OPENED:
|
|
258
|
-
await callbacks.onOpen?.(event);
|
|
259
|
-
break;
|
|
260
|
-
case EmailEventType.CLICKED:
|
|
261
|
-
await callbacks.onClick?.(event);
|
|
262
|
-
break;
|
|
263
|
-
case EmailEventType.FAILED:
|
|
264
|
-
await callbacks.onFailure?.(event);
|
|
265
|
-
break;
|
|
266
|
-
}
|
|
267
|
-
} catch (error) {
|
|
268
|
-
this.logger.error('Event callback failed', {
|
|
269
|
-
eventType: event.type,
|
|
270
|
-
eventId: event.id,
|
|
271
|
-
error: error instanceof Error ? error.message : 'Unknown error'
|
|
272
|
-
});
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
/**
|
|
277
|
-
* Create persistence adapter
|
|
278
|
-
*/
|
|
279
|
-
private async createPersistenceAdapter(): Promise<PersistenceAdapter> {
|
|
280
|
-
const adapter = this.config.persistence?.adapter || 'memory';
|
|
281
|
-
|
|
282
|
-
switch (adapter) {
|
|
283
|
-
case 'memory':
|
|
284
|
-
return new InMemoryPersistenceAdapter();
|
|
285
|
-
// Other adapters would be implemented here
|
|
286
|
-
default:
|
|
287
|
-
throw new Error(`Unsupported persistence adapter: ${adapter}`);
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
}
|
|
@@ -1,230 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
Copyright (c) 2025 Bernier LLC
|
|
3
|
-
|
|
4
|
-
This file is licensed to the client under a limited-use license.
|
|
5
|
-
The client may use and modify this code *only within the scope of the project it was delivered for*.
|
|
6
|
-
Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
import {
|
|
10
|
-
EmailEvent,
|
|
11
|
-
EmailAnalytics,
|
|
12
|
-
EmailEventType,
|
|
13
|
-
EmailProvider,
|
|
14
|
-
ProviderAnalytics,
|
|
15
|
-
AnalyticsFilters
|
|
16
|
-
} from '../types';
|
|
17
|
-
|
|
18
|
-
export class AnalyticsEngine {
|
|
19
|
-
private events: EmailEvent[] = [];
|
|
20
|
-
private config?: {
|
|
21
|
-
realTimeEnabled: boolean;
|
|
22
|
-
aggregationInterval: number;
|
|
23
|
-
retentionDays: number;
|
|
24
|
-
};
|
|
25
|
-
|
|
26
|
-
constructor(config?: { realTimeEnabled: boolean; aggregationInterval: number; retentionDays: number }) {
|
|
27
|
-
this.config = config;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
async recordEvent(event: EmailEvent): Promise<void> {
|
|
31
|
-
this.events.push(event);
|
|
32
|
-
|
|
33
|
-
// Cleanup old events based on retention policy
|
|
34
|
-
if (this.config?.retentionDays) {
|
|
35
|
-
const cutoffDate = new Date();
|
|
36
|
-
cutoffDate.setDate(cutoffDate.getDate() - this.config.retentionDays);
|
|
37
|
-
this.events = this.events.filter(e => e.timestamp >= cutoffDate);
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
async getAnalytics(
|
|
42
|
-
startDate: Date,
|
|
43
|
-
endDate: Date,
|
|
44
|
-
filters?: AnalyticsFilters
|
|
45
|
-
): Promise<EmailAnalytics> {
|
|
46
|
-
// Filter events by date range and filters
|
|
47
|
-
let filteredEvents = this.events.filter(
|
|
48
|
-
e => e.timestamp >= startDate && e.timestamp <= endDate
|
|
49
|
-
);
|
|
50
|
-
|
|
51
|
-
if (filters?.provider) {
|
|
52
|
-
filteredEvents = filteredEvents.filter(e => e.provider === filters.provider);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
if (filters?.emailId) {
|
|
56
|
-
filteredEvents = filteredEvents.filter(e => e.emailId === filters.emailId);
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
if (filters?.recipient) {
|
|
60
|
-
filteredEvents = filteredEvents.filter(e => e.recipient === filters.recipient);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
if (filters?.eventTypes && filters.eventTypes.length > 0) {
|
|
64
|
-
filteredEvents = filteredEvents.filter(e => filters.eventTypes!.includes(e.type));
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
// Calculate counts
|
|
68
|
-
const counts = this.calculateCounts(filteredEvents);
|
|
69
|
-
|
|
70
|
-
// Calculate rates
|
|
71
|
-
const rates = this.calculateRates(counts);
|
|
72
|
-
|
|
73
|
-
// Calculate breakdowns
|
|
74
|
-
const byProvider = this.calculateProviderBreakdown(filteredEvents);
|
|
75
|
-
const byEventType = this.calculateEventTypeBreakdown(filteredEvents);
|
|
76
|
-
const byBounceType = this.calculateBounceTypeBreakdown(filteredEvents);
|
|
77
|
-
const topLinks = this.calculateTopLinks(filteredEvents);
|
|
78
|
-
const byDevice = this.calculateDeviceBreakdown(filteredEvents);
|
|
79
|
-
|
|
80
|
-
return {
|
|
81
|
-
startDate,
|
|
82
|
-
endDate,
|
|
83
|
-
...counts,
|
|
84
|
-
...rates,
|
|
85
|
-
byProvider,
|
|
86
|
-
byEventType,
|
|
87
|
-
byBounceType,
|
|
88
|
-
topLinks,
|
|
89
|
-
byDevice
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
private calculateCounts(events: EmailEvent[]): {
|
|
94
|
-
totalSent: number;
|
|
95
|
-
totalDelivered: number;
|
|
96
|
-
totalOpened: number;
|
|
97
|
-
totalClicked: number;
|
|
98
|
-
totalBounced: number;
|
|
99
|
-
totalComplained: number;
|
|
100
|
-
totalUnsubscribed: number;
|
|
101
|
-
totalFailed: number;
|
|
102
|
-
} {
|
|
103
|
-
return {
|
|
104
|
-
totalSent: events.length, // Simplified - in real implementation, would track sent separately
|
|
105
|
-
totalDelivered: events.filter(e => e.type === EmailEventType.DELIVERED).length,
|
|
106
|
-
totalOpened: events.filter(e => e.type === EmailEventType.OPENED).length,
|
|
107
|
-
totalClicked: events.filter(e => e.type === EmailEventType.CLICKED).length,
|
|
108
|
-
totalBounced: events.filter(e => e.type === EmailEventType.BOUNCED).length,
|
|
109
|
-
totalComplained: events.filter(e => e.type === EmailEventType.COMPLAINED).length,
|
|
110
|
-
totalUnsubscribed: events.filter(e => e.type === EmailEventType.UNSUBSCRIBED).length,
|
|
111
|
-
totalFailed: events.filter(e => e.type === EmailEventType.FAILED).length
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
private calculateRates(counts: {
|
|
116
|
-
totalSent: number;
|
|
117
|
-
totalDelivered: number;
|
|
118
|
-
totalOpened: number;
|
|
119
|
-
totalClicked: number;
|
|
120
|
-
totalBounced: number;
|
|
121
|
-
totalComplained: number;
|
|
122
|
-
totalUnsubscribed: number;
|
|
123
|
-
}): {
|
|
124
|
-
deliveryRate: number;
|
|
125
|
-
openRate: number;
|
|
126
|
-
clickRate: number;
|
|
127
|
-
clickToOpenRate: number;
|
|
128
|
-
bounceRate: number;
|
|
129
|
-
complaintRate: number;
|
|
130
|
-
unsubscribeRate: number;
|
|
131
|
-
} {
|
|
132
|
-
const safeDiv = (num: number, denom: number): number => (denom === 0 ? 0 : num / denom);
|
|
133
|
-
|
|
134
|
-
return {
|
|
135
|
-
deliveryRate: safeDiv(counts.totalDelivered, counts.totalSent),
|
|
136
|
-
openRate: safeDiv(counts.totalOpened, counts.totalDelivered),
|
|
137
|
-
clickRate: safeDiv(counts.totalClicked, counts.totalDelivered),
|
|
138
|
-
clickToOpenRate: safeDiv(counts.totalClicked, counts.totalOpened),
|
|
139
|
-
bounceRate: safeDiv(counts.totalBounced, counts.totalSent),
|
|
140
|
-
complaintRate: safeDiv(counts.totalComplained, counts.totalSent),
|
|
141
|
-
unsubscribeRate: safeDiv(counts.totalUnsubscribed, counts.totalDelivered)
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
private calculateProviderBreakdown(events: EmailEvent[]): Record<EmailProvider, ProviderAnalytics> {
|
|
146
|
-
const providers = Object.values(EmailProvider);
|
|
147
|
-
const breakdown = {} as Record<EmailProvider, ProviderAnalytics>;
|
|
148
|
-
|
|
149
|
-
for (const provider of providers) {
|
|
150
|
-
const providerEvents = events.filter(e => e.provider === provider);
|
|
151
|
-
const counts = this.calculateCounts(providerEvents);
|
|
152
|
-
const rates = this.calculateRates(counts);
|
|
153
|
-
|
|
154
|
-
breakdown[provider] = {
|
|
155
|
-
sent: counts.totalSent,
|
|
156
|
-
delivered: counts.totalDelivered,
|
|
157
|
-
opened: counts.totalOpened,
|
|
158
|
-
clicked: counts.totalClicked,
|
|
159
|
-
bounced: counts.totalBounced,
|
|
160
|
-
complained: counts.totalComplained,
|
|
161
|
-
failed: counts.totalFailed,
|
|
162
|
-
deliveryRate: rates.deliveryRate,
|
|
163
|
-
openRate: rates.openRate,
|
|
164
|
-
clickRate: rates.clickRate
|
|
165
|
-
};
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
return breakdown;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
private calculateEventTypeBreakdown(events: EmailEvent[]): Record<EmailEventType, number> {
|
|
172
|
-
const eventTypes = Object.values(EmailEventType);
|
|
173
|
-
const breakdown = {} as Record<EmailEventType, number>;
|
|
174
|
-
|
|
175
|
-
for (const eventType of eventTypes) {
|
|
176
|
-
breakdown[eventType] = events.filter(e => e.type === eventType).length;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
return breakdown;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
private calculateBounceTypeBreakdown(events: EmailEvent[]): { hard: number; soft: number } | undefined {
|
|
183
|
-
const bounceEvents = events.filter(e => e.type === EmailEventType.BOUNCED);
|
|
184
|
-
if (bounceEvents.length === 0) return undefined;
|
|
185
|
-
|
|
186
|
-
return {
|
|
187
|
-
hard: bounceEvents.filter(e => e.metadata.bounceType === 'hard').length,
|
|
188
|
-
soft: bounceEvents.filter(e => e.metadata.bounceType === 'soft').length
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
private calculateTopLinks(events: EmailEvent[]): Array<{ url: string; clicks: number; uniqueClicks: number }> | undefined {
|
|
193
|
-
const clickEvents = events.filter(e => e.type === EmailEventType.CLICKED && e.metadata.url);
|
|
194
|
-
if (clickEvents.length === 0) return undefined;
|
|
195
|
-
|
|
196
|
-
const linkStats = new Map<string, { clicks: number; recipients: Set<string> }>();
|
|
197
|
-
|
|
198
|
-
for (const event of clickEvents) {
|
|
199
|
-
const url = event.metadata.url!;
|
|
200
|
-
const existing = linkStats.get(url) || { clicks: 0, recipients: new Set<string>() };
|
|
201
|
-
existing.clicks++;
|
|
202
|
-
existing.recipients.add(event.recipient);
|
|
203
|
-
linkStats.set(url, existing);
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
return Array.from(linkStats.entries())
|
|
207
|
-
.map(([url, stats]) => ({
|
|
208
|
-
url,
|
|
209
|
-
clicks: stats.clicks,
|
|
210
|
-
uniqueClicks: stats.recipients.size
|
|
211
|
-
}))
|
|
212
|
-
.sort((a, b) => b.clicks - a.clicks)
|
|
213
|
-
.slice(0, 10);
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
private calculateDeviceBreakdown(events: EmailEvent[]): { desktop: number; mobile: number; tablet: number; unknown: number } | undefined {
|
|
217
|
-
const interactionEvents = events.filter(
|
|
218
|
-
e => (e.type === EmailEventType.OPENED || e.type === EmailEventType.CLICKED) && e.metadata.deviceType
|
|
219
|
-
);
|
|
220
|
-
|
|
221
|
-
if (interactionEvents.length === 0) return undefined;
|
|
222
|
-
|
|
223
|
-
return {
|
|
224
|
-
desktop: interactionEvents.filter(e => e.metadata.deviceType === 'desktop').length,
|
|
225
|
-
mobile: interactionEvents.filter(e => e.metadata.deviceType === 'mobile').length,
|
|
226
|
-
tablet: interactionEvents.filter(e => e.metadata.deviceType === 'tablet').length,
|
|
227
|
-
unknown: interactionEvents.filter(e => e.metadata.deviceType === 'unknown').length
|
|
228
|
-
};
|
|
229
|
-
}
|
|
230
|
-
}
|
package/src/index.ts
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
Copyright (c) 2025 Bernier LLC
|
|
3
|
-
|
|
4
|
-
This file is licensed to the client under a limited-use license.
|
|
5
|
-
The client may use and modify this code *only within the scope of the project it was delivered for*.
|
|
6
|
-
Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
export { EmailWebhookEventsService } from './EmailWebhookEventsService';
|
|
10
|
-
|
|
11
|
-
export {
|
|
12
|
-
EmailEvent,
|
|
13
|
-
EmailEventType,
|
|
14
|
-
EmailProvider,
|
|
15
|
-
EmailEventMetadata,
|
|
16
|
-
EmailAnalytics,
|
|
17
|
-
ProviderAnalytics,
|
|
18
|
-
EmailWebhookEventsConfig,
|
|
19
|
-
ProviderWebhookConfig,
|
|
20
|
-
NotificationChannel,
|
|
21
|
-
EmailWebhookResult,
|
|
22
|
-
WebhookPayload,
|
|
23
|
-
AnalyticsFilters,
|
|
24
|
-
EventQuery,
|
|
25
|
-
EmailWebhookError,
|
|
26
|
-
EmailWebhookErrorCode,
|
|
27
|
-
WebhookEventCallbacks
|
|
28
|
-
} from './types';
|
|
29
|
-
|
|
30
|
-
export { EventNormalizer } from './normalizers/EventNormalizer';
|
|
31
|
-
export { SendGridNormalizer } from './normalizers/SendGridNormalizer';
|
|
32
|
-
export { MailgunNormalizer } from './normalizers/MailgunNormalizer';
|
|
33
|
-
export { SESNormalizer } from './normalizers/SESNormalizer';
|
|
34
|
-
export { PostmarkNormalizer } from './normalizers/PostmarkNormalizer';
|
|
35
|
-
export { SMTP2GONormalizer } from './normalizers/SMTP2GONormalizer';
|
|
36
|
-
|
|
37
|
-
export { AnalyticsEngine } from './analytics/AnalyticsEngine';
|
|
38
|
-
|
|
39
|
-
export { PersistenceAdapter } from './persistence/PersistenceAdapter';
|
|
40
|
-
export { InMemoryPersistenceAdapter } from './persistence/InMemoryPersistenceAdapter';
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
Copyright (c) 2025 Bernier LLC
|
|
3
|
-
|
|
4
|
-
This file is licensed to the client under a limited-use license.
|
|
5
|
-
The client may use and modify this code *only within the scope of the project it was delivered for*.
|
|
6
|
-
Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
import { EmailEvent, WebhookPayload } from '../types';
|
|
10
|
-
|
|
11
|
-
export interface EventNormalizer {
|
|
12
|
-
normalize(webhook: WebhookPayload): EmailEvent;
|
|
13
|
-
}
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
Copyright (c) 2025 Bernier LLC
|
|
3
|
-
|
|
4
|
-
This file is licensed to the client under a limited-use license.
|
|
5
|
-
The client may use and modify this code *only within the scope of the project it was delivered for*.
|
|
6
|
-
Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
import { EventNormalizer } from './EventNormalizer';
|
|
10
|
-
import { EmailEvent, EmailEventType, EmailProvider, WebhookPayload } from '../types';
|
|
11
|
-
|
|
12
|
-
export class MailgunNormalizer implements EventNormalizer {
|
|
13
|
-
normalize(webhook: WebhookPayload): EmailEvent {
|
|
14
|
-
const payload = webhook.payload as Record<string, unknown>;
|
|
15
|
-
const event = payload['event-data'] as Record<string, unknown>;
|
|
16
|
-
const message = (event.message as Record<string, unknown>) || {};
|
|
17
|
-
const headers = (message.headers as Record<string, string>) || {};
|
|
18
|
-
const deliveryStatus = event['delivery-status'] as Record<string, unknown> | undefined;
|
|
19
|
-
const clientInfo = event['client-info'] as Record<string, unknown> | undefined;
|
|
20
|
-
const geolocation = event.geolocation as Record<string, string> | undefined;
|
|
21
|
-
|
|
22
|
-
return {
|
|
23
|
-
id: this.generateEventId(event),
|
|
24
|
-
emailId: headers['message-id'] || '',
|
|
25
|
-
messageId: (event.id as string) || '',
|
|
26
|
-
type: this.mapEventType(event.event as string),
|
|
27
|
-
recipient: (event.recipient as string) || '',
|
|
28
|
-
timestamp: new Date((event.timestamp as number) * 1000),
|
|
29
|
-
provider: EmailProvider.MAILGUN,
|
|
30
|
-
metadata: {
|
|
31
|
-
url: event.url as string | undefined,
|
|
32
|
-
bounceType: (event.severity as string) === 'permanent' ? 'hard' : 'soft',
|
|
33
|
-
bounceReason: deliveryStatus?.message as string | undefined,
|
|
34
|
-
bounceCode: deliveryStatus?.code?.toString(),
|
|
35
|
-
ipAddress: clientInfo?.['client-ip'] as string | undefined,
|
|
36
|
-
userAgent: clientInfo?.['user-agent'] as string | undefined,
|
|
37
|
-
deviceType: this.detectDeviceType(clientInfo?.['user-agent'] as string | undefined),
|
|
38
|
-
location: {
|
|
39
|
-
country: geolocation?.country,
|
|
40
|
-
region: geolocation?.region,
|
|
41
|
-
city: geolocation?.city
|
|
42
|
-
}
|
|
43
|
-
},
|
|
44
|
-
rawEvent: event
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
private mapEventType(mailgunEvent: string): EmailEventType {
|
|
49
|
-
const mapping: Record<string, EmailEventType> = {
|
|
50
|
-
'delivered': EmailEventType.DELIVERED,
|
|
51
|
-
'opened': EmailEventType.OPENED,
|
|
52
|
-
'clicked': EmailEventType.CLICKED,
|
|
53
|
-
'bounced': EmailEventType.BOUNCED,
|
|
54
|
-
'complained': EmailEventType.COMPLAINED,
|
|
55
|
-
'unsubscribed': EmailEventType.UNSUBSCRIBED,
|
|
56
|
-
'failed': EmailEventType.FAILED
|
|
57
|
-
};
|
|
58
|
-
return mapping[mailgunEvent] || EmailEventType.FAILED;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
private generateEventId(event: Record<string, unknown>): string {
|
|
62
|
-
return `mailgun-${event.id as string}`;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
private detectDeviceType(userAgent?: string): 'desktop' | 'mobile' | 'tablet' | 'unknown' {
|
|
66
|
-
if (!userAgent) return 'unknown';
|
|
67
|
-
const ua = userAgent.toLowerCase();
|
|
68
|
-
if (ua.includes('mobile')) return 'mobile';
|
|
69
|
-
if (ua.includes('tablet') || ua.includes('ipad')) return 'tablet';
|
|
70
|
-
return 'desktop';
|
|
71
|
-
}
|
|
72
|
-
}
|