@bernierllc/email-manager 0.12.0 → 0.12.2

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.
Files changed (93) hide show
  1. package/package.json +12 -12
  2. package/dist/capabilities/degradation-logger.d.ts +0 -59
  3. package/dist/capabilities/degradation-logger.d.ts.map +0 -1
  4. package/dist/capabilities/degradation-logger.js +0 -106
  5. package/dist/capabilities/degradation-logger.js.map +0 -1
  6. package/dist/capabilities/feature-router.d.ts +0 -55
  7. package/dist/capabilities/feature-router.d.ts.map +0 -1
  8. package/dist/capabilities/feature-router.js +0 -143
  9. package/dist/capabilities/feature-router.js.map +0 -1
  10. package/dist/capabilities/in-memory-resolver.d.ts +0 -27
  11. package/dist/capabilities/in-memory-resolver.d.ts.map +0 -1
  12. package/dist/capabilities/in-memory-resolver.js +0 -79
  13. package/dist/capabilities/in-memory-resolver.js.map +0 -1
  14. package/dist/capabilities/index.d.ts +0 -13
  15. package/dist/capabilities/index.d.ts.map +0 -1
  16. package/dist/capabilities/index.js +0 -21
  17. package/dist/capabilities/index.js.map +0 -1
  18. package/dist/capabilities/matrix.d.ts +0 -67
  19. package/dist/capabilities/matrix.d.ts.map +0 -1
  20. package/dist/capabilities/matrix.js +0 -312
  21. package/dist/capabilities/matrix.js.map +0 -1
  22. package/dist/capabilities/redis-resolver.d.ts +0 -95
  23. package/dist/capabilities/redis-resolver.d.ts.map +0 -1
  24. package/dist/capabilities/redis-resolver.js +0 -227
  25. package/dist/capabilities/redis-resolver.js.map +0 -1
  26. package/dist/capabilities/resolver-factory.d.ts +0 -30
  27. package/dist/capabilities/resolver-factory.d.ts.map +0 -1
  28. package/dist/capabilities/resolver-factory.js +0 -70
  29. package/dist/capabilities/resolver-factory.js.map +0 -1
  30. package/dist/capabilities/resolver.d.ts +0 -40
  31. package/dist/capabilities/resolver.d.ts.map +0 -1
  32. package/dist/capabilities/resolver.js +0 -18
  33. package/dist/capabilities/resolver.js.map +0 -1
  34. package/dist/capabilities/routing-metadata.d.ts +0 -16
  35. package/dist/capabilities/routing-metadata.d.ts.map +0 -1
  36. package/dist/capabilities/routing-metadata.js +0 -17
  37. package/dist/capabilities/routing-metadata.js.map +0 -1
  38. package/dist/capabilities/safe-resolver.d.ts +0 -24
  39. package/dist/capabilities/safe-resolver.d.ts.map +0 -1
  40. package/dist/capabilities/safe-resolver.js +0 -48
  41. package/dist/capabilities/safe-resolver.js.map +0 -1
  42. package/dist/config/loadConfiguration.d.ts +0 -60
  43. package/dist/config/loadConfiguration.d.ts.map +0 -1
  44. package/dist/config/loadConfiguration.js +0 -468
  45. package/dist/config/loadConfiguration.js.map +0 -1
  46. package/dist/config/schema.d.ts +0 -962
  47. package/dist/config/schema.d.ts.map +0 -1
  48. package/dist/config/schema.js +0 -318
  49. package/dist/config/schema.js.map +0 -1
  50. package/dist/config/types.d.ts +0 -826
  51. package/dist/config/types.d.ts.map +0 -1
  52. package/dist/config/types.js +0 -9
  53. package/dist/config/types.js.map +0 -1
  54. package/dist/email-manager.d.ts +0 -143
  55. package/dist/email-manager.d.ts.map +0 -1
  56. package/dist/email-manager.js +0 -365
  57. package/dist/email-manager.js.map +0 -1
  58. package/dist/enhanced-email-manager.d.ts +0 -349
  59. package/dist/enhanced-email-manager.d.ts.map +0 -1
  60. package/dist/enhanced-email-manager.js +0 -1396
  61. package/dist/enhanced-email-manager.js.map +0 -1
  62. package/dist/errors.d.ts +0 -154
  63. package/dist/errors.d.ts.map +0 -1
  64. package/dist/errors.js +0 -251
  65. package/dist/errors.js.map +0 -1
  66. package/dist/index.d.ts +0 -25
  67. package/dist/index.d.ts.map +0 -1
  68. package/dist/index.js +0 -30
  69. package/dist/index.js.map +0 -1
  70. package/dist/managers/email-analytics.d.ts +0 -92
  71. package/dist/managers/email-analytics.d.ts.map +0 -1
  72. package/dist/managers/email-analytics.js +0 -375
  73. package/dist/managers/email-analytics.js.map +0 -1
  74. package/dist/managers/email-scheduler.d.ts +0 -81
  75. package/dist/managers/email-scheduler.d.ts.map +0 -1
  76. package/dist/managers/email-scheduler.js +0 -288
  77. package/dist/managers/email-scheduler.js.map +0 -1
  78. package/dist/managers/provider-manager.d.ts +0 -152
  79. package/dist/managers/provider-manager.d.ts.map +0 -1
  80. package/dist/managers/provider-manager.js +0 -592
  81. package/dist/managers/provider-manager.js.map +0 -1
  82. package/dist/managers/template-manager.d.ts +0 -65
  83. package/dist/managers/template-manager.d.ts.map +0 -1
  84. package/dist/managers/template-manager.js +0 -314
  85. package/dist/managers/template-manager.js.map +0 -1
  86. package/dist/types.d.ts +0 -1029
  87. package/dist/types.d.ts.map +0 -1
  88. package/dist/types.js +0 -62
  89. package/dist/types.js.map +0 -1
  90. package/dist/utils/simple-template-engine.d.ts +0 -27
  91. package/dist/utils/simple-template-engine.d.ts.map +0 -1
  92. package/dist/utils/simple-template-engine.js +0 -61
  93. package/dist/utils/simple-template-engine.js.map +0 -1
@@ -1,1396 +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
- import { EmailManager } from './email-manager.js';
9
- import { v4 as uuidv4 } from 'uuid';
10
- import { createCalendarInvite, createCalendarCancel, toCalendarAttachment } from '@bernierllc/email-calendar';
11
- import { createBatchSender } from '@bernierllc/email-batch-sender';
12
- import { SubscriptionListManager, UnsubscribeManager, SuppressionManager, InMemorySubscriptionStore, } from '@bernierllc/email-subscription';
13
- import { createListUnsubscribeHeaders } from '@bernierllc/email-headers';
14
- /**
15
- * EnhancedEmailManager - Extended email management with template service,
16
- * sender management, and variable validation integration.
17
- *
18
- * This class extends EmailManager to provide:
19
- * - Advanced template management
20
- * - Sender configuration and selection
21
- * - Template variable validation
22
- * - System bootstrap and health monitoring
23
- *
24
- * Note: This implementation provides built-in functionality that can be
25
- * replaced with external services when available.
26
- */
27
- export class EnhancedEmailManager extends EmailManager {
28
- constructor(config) {
29
- super(config);
30
- this.templateStore = new Map();
31
- this.senderStore = new Map();
32
- this.variableContexts = new Map();
33
- this.initialized = false;
34
- this.unsubscribeManager = null;
35
- this.enhancedConfig = config;
36
- // Wire sender service if provided
37
- if (config.senderService) {
38
- this.senderService = config.senderService;
39
- }
40
- // Initialize subscription components
41
- this.subscriptionStore = new InMemorySubscriptionStore();
42
- this.subscriptionListManager = new SubscriptionListManager(this.subscriptionStore);
43
- this.suppressionManager = new SuppressionManager(this.subscriptionStore);
44
- if (config.subscription?.unsubscribe) {
45
- this.unsubscribeManager = new UnsubscribeManager(this.subscriptionStore, config.subscription.unsubscribe);
46
- }
47
- }
48
- // ======================
49
- // Enhanced Email Sending
50
- // ======================
51
- /**
52
- * Send a templated email with variable validation and smart sender selection
53
- */
54
- async sendEnhancedTemplatedEmail(templateId, templateData, recipients, options = {}) {
55
- const results = [];
56
- try {
57
- // 1. Get template from internal store
58
- const template = this.templateStore.get(templateId);
59
- if (!template) {
60
- throw new Error(`Template not found: ${templateId}`);
61
- }
62
- // 2. Validate template variables if enabled
63
- if (options.validateVariables && template.context) {
64
- const validation = await this.validateTemplateData(template.context, templateData);
65
- if (!validation.isValid && options.strictMode) {
66
- return [{
67
- success: false,
68
- provider: 'none',
69
- sentAt: new Date(),
70
- errors: validation.errors.map(e => ({
71
- code: 'VALIDATION_ERROR',
72
- message: e.message
73
- }))
74
- }];
75
- }
76
- }
77
- // 3. Send to all recipients
78
- for (const recipient of recipients) {
79
- // Select best sender for this recipient
80
- let sender = options.senderOverride;
81
- if (!sender && options.selectBestSender) {
82
- const selectedSender = await this.selectBestSender(recipient.email, options.preferredProvider, { allowUnverified: false });
83
- sender = selectedSender || undefined;
84
- }
85
- // Create email data
86
- const emailData = {
87
- to: recipient.email,
88
- subject: this.renderSimpleTemplate(template.subject, templateData),
89
- html: this.renderSimpleTemplate(template.htmlContent, templateData),
90
- text: template.textContent ? this.renderSimpleTemplate(template.textContent, templateData) : undefined,
91
- templateId,
92
- metadata: {
93
- templateVersion: template.version,
94
- senderId: sender?.id,
95
- context: template.context,
96
- recipientMetadata: recipient.metadata
97
- }
98
- };
99
- // Send email
100
- const result = await this.sendEmail(emailData);
101
- results.push(result);
102
- }
103
- return results;
104
- }
105
- catch (error) {
106
- return [{
107
- success: false,
108
- provider: 'none',
109
- sentAt: new Date(),
110
- errors: [{
111
- code: 'ENHANCED_SEND_ERROR',
112
- message: error instanceof Error ? error.message : 'Unknown error occurred'
113
- }]
114
- }];
115
- }
116
- }
117
- /**
118
- * Send email with variable validation
119
- */
120
- async sendWithVariableValidation(email, context, _options) {
121
- if (context && email.templateContext) {
122
- const validation = await this.validateTemplateData(context, email.templateContext);
123
- if (!validation.isValid) {
124
- return {
125
- success: false,
126
- provider: 'none',
127
- sentAt: new Date(),
128
- errors: validation.errors.map(e => ({
129
- code: 'VALIDATION_ERROR',
130
- message: e.message
131
- }))
132
- };
133
- }
134
- }
135
- return await this.sendEmail(email);
136
- }
137
- // ======================
138
- // Template Management
139
- // ======================
140
- /**
141
- * Create a template with validation
142
- */
143
- async createEnhancedTemplate(template) {
144
- try {
145
- // Validate template if context is provided
146
- if (template.context) {
147
- const validation = await this.validateEnhancedTemplate(template.htmlContent, template.context);
148
- if (!validation.isValid) {
149
- return {
150
- success: false,
151
- errors: validation.errors.map(e => e.message)
152
- };
153
- }
154
- }
155
- const id = uuidv4();
156
- const now = new Date();
157
- const internalTemplate = {
158
- id,
159
- name: template.name,
160
- subject: template.subject,
161
- htmlContent: template.htmlContent,
162
- textContent: template.textContent,
163
- context: template.context,
164
- category: template.category,
165
- version: '1.0.0',
166
- isActive: true,
167
- createdAt: now,
168
- updatedAt: now
169
- };
170
- this.templateStore.set(id, internalTemplate);
171
- return { success: true, templateId: id };
172
- }
173
- catch (error) {
174
- return {
175
- success: false,
176
- errors: [error instanceof Error ? error.message : 'Failed to create template']
177
- };
178
- }
179
- }
180
- /**
181
- * Get a template by ID from enhanced store
182
- */
183
- async getEnhancedTemplate(templateId) {
184
- return this.templateStore.get(templateId) || null;
185
- }
186
- /**
187
- * List all enhanced templates
188
- */
189
- async listEnhancedTemplates() {
190
- const items = Array.from(this.templateStore.values());
191
- return { items, total: items.length };
192
- }
193
- /**
194
- * Sync a template to providers (placeholder for future integration)
195
- */
196
- async syncTemplate(templateId, providerId) {
197
- const template = this.templateStore.get(templateId);
198
- if (!template) {
199
- return {
200
- success: false,
201
- action: 'failed',
202
- localTemplateId: templateId,
203
- error: 'Template not found'
204
- };
205
- }
206
- // Placeholder - would integrate with actual provider plugins
207
- return {
208
- success: true,
209
- action: providerId ? 'updated' : 'synced_all',
210
- localTemplateId: templateId,
211
- providerId,
212
- metadata: { note: 'Sync placeholder - integrate with provider plugins' }
213
- };
214
- }
215
- /**
216
- * Validate a template against a variable context
217
- */
218
- async validateEnhancedTemplate(templateContent, context) {
219
- const variableContext = this.variableContexts.get(context);
220
- if (!variableContext) {
221
- return {
222
- isValid: true,
223
- errors: [],
224
- warnings: [],
225
- info: [`No variable context '${context}' registered, validation skipped`]
226
- };
227
- }
228
- // Extract variables from template (simple Handlebars-style extraction)
229
- const variablePattern = /\{\{\s*([a-zA-Z_][a-zA-Z0-9_.]*)\s*\}\}/g;
230
- const usedVariables = [];
231
- let match;
232
- while ((match = variablePattern.exec(templateContent)) !== null) {
233
- usedVariables.push(match[1]);
234
- }
235
- // Check for required variables
236
- const errors = [];
237
- const definedPaths = variableContext.variables.map(v => v.path);
238
- for (const variable of usedVariables) {
239
- if (!definedPaths.includes(variable) && !this.isNestedPath(variable, definedPaths)) {
240
- errors.push({
241
- message: `Undefined variable: ${variable}`,
242
- path: variable
243
- });
244
- }
245
- }
246
- return {
247
- isValid: errors.length === 0,
248
- errors,
249
- warnings: []
250
- };
251
- }
252
- /**
253
- * Sync all templates to providers
254
- */
255
- async syncAllTemplates() {
256
- const templates = Array.from(this.templateStore.values());
257
- const results = [];
258
- for (const template of templates) {
259
- const result = await this.syncTemplate(template.id);
260
- results.push(result);
261
- }
262
- const synced = results.filter(r => r.success).length;
263
- return {
264
- success: synced > 0,
265
- total: results.length,
266
- synced,
267
- failed: results.length - synced,
268
- results
269
- };
270
- }
271
- // ======================
272
- // Sender Management
273
- // ======================
274
- /**
275
- * Create a new sender configuration.
276
- * Delegates to senderService if available, falls back to in-memory store.
277
- */
278
- async createSender(sender) {
279
- try {
280
- // Validate email format
281
- if (!this.validateEmail(sender.fromEmail)) {
282
- throw new Error(`Invalid email format: ${sender.fromEmail}`);
283
- }
284
- if (this.senderService) {
285
- const result = await this.senderService.createSender({
286
- email: sender.fromEmail,
287
- name: sender.fromName,
288
- replyToEmail: sender.replyToEmail,
289
- provider: sender.provider,
290
- isDefault: sender.isDefault,
291
- providerFields: sender.providerMetadata,
292
- });
293
- if (!result.success || !result.data)
294
- return null;
295
- return this.serviceDataToEnhancedSender(result.data, sender);
296
- }
297
- const id = uuidv4();
298
- const now = new Date();
299
- const internalSender = {
300
- id,
301
- name: sender.name,
302
- fromEmail: sender.fromEmail,
303
- fromName: sender.fromName,
304
- replyToEmail: sender.replyToEmail,
305
- provider: sender.provider,
306
- priority: sender.priority ?? 100,
307
- isDefault: sender.isDefault ?? false,
308
- isActive: true,
309
- isVerified: sender.isVerified ?? false,
310
- verificationStatus: sender.verificationStatus ?? 'pending',
311
- createdAt: now,
312
- updatedAt: now
313
- };
314
- this.senderStore.set(id, internalSender);
315
- return this.mapToEnhancedSender(internalSender);
316
- }
317
- catch (error) {
318
- console.error('Failed to create sender:', error);
319
- return null;
320
- }
321
- }
322
- /**
323
- * Get a sender by ID
324
- */
325
- async getSender(senderId) {
326
- if (this.senderService) {
327
- const result = await this.senderService.getSender(senderId);
328
- if (!result.success || !result.data)
329
- return null;
330
- return this.serviceDataToEnhancedSender(result.data);
331
- }
332
- const sender = this.senderStore.get(senderId);
333
- return sender ? this.mapToEnhancedSender(sender) : null;
334
- }
335
- /**
336
- * List all senders
337
- */
338
- async listSenders() {
339
- if (this.senderService) {
340
- const result = await this.senderService.listSenders();
341
- if (!result.success || !result.data)
342
- return { items: [], total: 0 };
343
- const items = result.data.map(d => this.serviceDataToEnhancedSender(d));
344
- return { items, total: items.length };
345
- }
346
- const items = Array.from(this.senderStore.values()).map(s => this.mapToEnhancedSender(s));
347
- return { items, total: items.length };
348
- }
349
- /**
350
- * Update an existing sender configuration.
351
- * Delegates to senderService if available, falls back to in-memory store.
352
- */
353
- async updateSender(senderId, updates) {
354
- if (this.senderService) {
355
- const result = await this.senderService.updateSender(senderId, updates);
356
- if (!result.success || !result.data)
357
- return null;
358
- return this.serviceDataToEnhancedSender(result.data);
359
- }
360
- const sender = this.senderStore.get(senderId);
361
- if (!sender)
362
- return null;
363
- if (updates.name !== undefined)
364
- sender.name = updates.name;
365
- if (updates.fromName !== undefined)
366
- sender.fromName = updates.fromName;
367
- if (updates.replyToEmail !== undefined)
368
- sender.replyToEmail = updates.replyToEmail;
369
- if (updates.provider !== undefined)
370
- sender.provider = updates.provider;
371
- if (updates.priority !== undefined)
372
- sender.priority = updates.priority;
373
- if (updates.isDefault !== undefined)
374
- sender.isDefault = updates.isDefault;
375
- if (updates.isVerified !== undefined)
376
- sender.isVerified = updates.isVerified;
377
- if (updates.verificationStatus !== undefined)
378
- sender.verificationStatus = updates.verificationStatus;
379
- sender.updatedAt = new Date();
380
- return this.mapToEnhancedSender(sender);
381
- }
382
- /**
383
- * Delete a sender configuration.
384
- * Delegates to senderService if available, falls back to in-memory store.
385
- */
386
- async deleteSender(senderId) {
387
- if (this.senderService) {
388
- const result = await this.senderService.deleteSender(senderId);
389
- return result.success;
390
- }
391
- return this.senderStore.delete(senderId);
392
- }
393
- /**
394
- * Select the best sender for an email
395
- */
396
- async selectBestSender(fromEmail, provider, options = {}) {
397
- // Get candidates — from service or local store
398
- let candidates;
399
- if (this.senderService) {
400
- const result = await this.senderService.listSenders();
401
- if (!result.success || !result.data)
402
- return null;
403
- candidates = result.data.map(d => this.serviceDataToEnhancedSender(d));
404
- }
405
- else {
406
- candidates = Array.from(this.senderStore.values()).map(s => this.mapToEnhancedSender(s));
407
- }
408
- const senders = candidates
409
- .filter(s => s.isActive)
410
- .filter(s => !options.excludeIds?.includes(s.id))
411
- .filter(s => options.allowUnverified || s.isVerified)
412
- .filter(s => !provider || s.provider === provider);
413
- if (senders.length === 0) {
414
- return null;
415
- }
416
- // Strategy selection
417
- let selected;
418
- const strategy = options.strategy || 'domain_match';
419
- if (strategy === 'domain_match') {
420
- const domain = this.extractDomain(fromEmail);
421
- selected = senders.find(s => this.extractDomain(s.fromEmail) === domain);
422
- }
423
- // Fallback to priority-based selection
424
- if (!selected) {
425
- senders.sort((a, b) => a.priority - b.priority);
426
- selected = senders[0];
427
- }
428
- return selected || null;
429
- }
430
- /**
431
- * Validate a sender configuration.
432
- * When senderService is available, delegates verification status check.
433
- */
434
- async validateSender(senderId) {
435
- const sender = this.senderService
436
- ? (await this.getSender(senderId))
437
- : (() => { const s = this.senderStore.get(senderId); return s ? this.mapToEnhancedSender(s) : null; })();
438
- if (!sender) {
439
- return {
440
- isValid: false,
441
- errors: [{ field: 'id', message: `Sender not found: ${senderId}` }],
442
- warnings: []
443
- };
444
- }
445
- const errors = [];
446
- const warnings = [];
447
- // Basic validation
448
- if (!sender.fromEmail) {
449
- errors.push({ field: 'fromEmail', message: 'From email is required' });
450
- }
451
- else if (!this.validateEmail(sender.fromEmail)) {
452
- errors.push({ field: 'fromEmail', message: 'Invalid email format' });
453
- }
454
- if (!sender.fromName) {
455
- warnings.push({ field: 'fromName', message: 'From name is recommended' });
456
- }
457
- if (!sender.isVerified) {
458
- warnings.push({ field: 'isVerified', message: 'Sender is not verified' });
459
- }
460
- // Check provider verification status if service is available
461
- if (this.senderService?.checkVerificationStatus) {
462
- const verResult = await this.senderService.checkVerificationStatus(senderId);
463
- if (verResult.success && verResult.data) {
464
- return {
465
- isValid: errors.length === 0,
466
- errors,
467
- warnings,
468
- providerValidation: {
469
- isVerified: verResult.data.status === 'verified',
470
- verificationStatus: verResult.data.status,
471
- },
472
- metadata: {
473
- lastValidated: new Date(),
474
- validatedBy: 'email-manager',
475
- checks: ['basic', 'email-format', 'verification-status', 'provider-check']
476
- }
477
- };
478
- }
479
- }
480
- return {
481
- isValid: errors.length === 0,
482
- errors,
483
- warnings,
484
- metadata: {
485
- lastValidated: new Date(),
486
- validatedBy: 'email-manager',
487
- checks: ['basic', 'email-format', 'verification-status']
488
- }
489
- };
490
- }
491
- // ======================
492
- // Variable Management
493
- // ======================
494
- /**
495
- * Register a variable context
496
- */
497
- async registerVariableContext(name, contextDef) {
498
- this.variableContexts.set(name, {
499
- name,
500
- description: contextDef.description,
501
- variables: contextDef.variables
502
- });
503
- }
504
- /**
505
- * Get a variable context
506
- */
507
- async getVariableContext(name) {
508
- return this.variableContexts.get(name) || null;
509
- }
510
- /**
511
- * Get variable suggestions for a context
512
- */
513
- async getVariableSuggestions(context, prefix) {
514
- const variableContext = this.variableContexts.get(context);
515
- if (!variableContext) {
516
- return [];
517
- }
518
- let variables = variableContext.variables;
519
- if (prefix) {
520
- variables = variables.filter(v => v.path.startsWith(prefix));
521
- }
522
- return variables.map((v, index) => ({
523
- path: v.path,
524
- type: v.type,
525
- description: v.description,
526
- required: v.required ?? false,
527
- score: 100 - index // Simple scoring based on order
528
- }));
529
- }
530
- /**
531
- * Validate template data against a context
532
- */
533
- async validateTemplateData(context, data) {
534
- const variableContext = this.variableContexts.get(context);
535
- if (!variableContext) {
536
- return {
537
- isValid: true,
538
- errors: [],
539
- warnings: [],
540
- info: [`Variable context '${context}' not registered`]
541
- };
542
- }
543
- const errors = [];
544
- // Check required variables
545
- for (const variable of variableContext.variables) {
546
- if (variable.required) {
547
- const value = this.getNestedValue(data, variable.path);
548
- if (value === undefined) {
549
- errors.push({
550
- message: `Required variable missing: ${variable.path}`,
551
- path: variable.path
552
- });
553
- }
554
- }
555
- }
556
- return {
557
- isValid: errors.length === 0,
558
- errors,
559
- warnings: []
560
- };
561
- }
562
- // ======================
563
- // Calendar Invite Methods
564
- // ======================
565
- /**
566
- * Send a calendar invite email to recipients.
567
- *
568
- * Generates an ICS file from the CalendarEvent and attaches it to the email.
569
- * The ICS attachment uses METHOD:REQUEST by default.
570
- *
571
- * @param event - The calendar event to send
572
- * @param recipients - Array of recipient email addresses
573
- * @param options - Optional subject, body, and provider overrides
574
- * @returns SendResult from the email send operation
575
- *
576
- * @throws {Error} When the calendar event is invalid (missing title, bad dates, no attendees)
577
- * @throws {EmailValidationError} When recipient validation fails
578
- */
579
- async sendCalendarInvite(event, recipients, options) {
580
- if (!recipients || recipients.length === 0) {
581
- throw new Error('At least one recipient is required');
582
- }
583
- // Generate ICS content
584
- const icsContent = createCalendarInvite(event);
585
- // Convert to email attachment
586
- const calendarAttachment = toCalendarAttachment(icsContent, 'REQUEST');
587
- // Build subject line
588
- const subject = options?.subject ?? `Calendar Invite: ${event.title}`;
589
- // Build default body
590
- const textBody = options?.textBody ??
591
- `You have been invited to: ${event.title}\nWhen: ${event.start.toISOString()} - ${event.end.toISOString()}${event.location ? `\nWhere: ${event.location}` : ''}${event.description ? `\n\n${event.description}` : ''}`;
592
- const htmlBody = options?.htmlBody ??
593
- `<h2>${event.title}</h2><p><strong>When:</strong> ${event.start.toISOString()} - ${event.end.toISOString()}</p>${event.location ? `<p><strong>Where:</strong> ${event.location}</p>` : ''}${event.description ? `<p>${event.description}</p>` : ''}`;
594
- // Build email data with calendar attachment
595
- const emailData = {
596
- to: recipients,
597
- subject,
598
- text: textBody,
599
- html: htmlBody,
600
- attachments: [{
601
- filename: calendarAttachment.filename,
602
- content: calendarAttachment.content,
603
- contentType: calendarAttachment.contentType,
604
- }],
605
- provider: options?.provider,
606
- metadata: {
607
- ...options?.metadata,
608
- calendarEvent: true,
609
- eventTitle: event.title,
610
- },
611
- };
612
- return this.sendEmail(emailData);
613
- }
614
- /**
615
- * Send a calendar cancellation email.
616
- *
617
- * Generates a METHOD:CANCEL ICS and sends it to the specified attendees.
618
- *
619
- * @param eventUid - The UID of the event to cancel
620
- * @param organizer - The organizer attendee
621
- * @param attendees - The attendees to notify
622
- * @param options - Optional subject and body overrides
623
- * @returns SendResult from the email send operation
624
- */
625
- async sendCalendarCancel(eventUid, organizer, attendees, options) {
626
- if (!attendees || attendees.length === 0) {
627
- throw new Error('At least one attendee is required');
628
- }
629
- const icsContent = createCalendarCancel(eventUid, organizer, attendees);
630
- const calendarAttachment = toCalendarAttachment(icsContent, 'CANCEL');
631
- const subject = options?.subject ?? 'Event Cancelled';
632
- const recipients = attendees.map(a => a.email);
633
- const emailData = {
634
- to: recipients,
635
- subject,
636
- text: options?.textBody ?? 'This event has been cancelled.',
637
- html: options?.htmlBody ?? '<p>This event has been cancelled.</p>',
638
- attachments: [{
639
- filename: calendarAttachment.filename,
640
- content: calendarAttachment.content,
641
- contentType: calendarAttachment.contentType,
642
- }],
643
- provider: options?.provider,
644
- metadata: {
645
- ...options?.metadata,
646
- calendarCancel: true,
647
- eventUid,
648
- },
649
- };
650
- return this.sendEmail(emailData);
651
- }
652
- // ======================
653
- // Batch Send Methods
654
- // ======================
655
- /**
656
- * Send a batch of emails with concurrency control, rate limiting, and retry.
657
- *
658
- * Wraps the existing email sending mechanism with the BatchSender from
659
- * @bernierllc/email-batch-sender, providing efficient bulk email operations.
660
- *
661
- * @param emails - Array of batch email inputs
662
- * @param options - Batch sender configuration (concurrency, rate limits, retry, etc.)
663
- * @returns BatchResult with per-recipient results, timing, and abort status
664
- *
665
- * @throws {BatchSenderError} When batch input is invalid (missing toEmail/subject)
666
- */
667
- async sendBatch(emails, options) {
668
- // Create an adapter that wraps our sendEmail into the EmailSenderInterface
669
- const senderAdapter = {
670
- send: async (message) => {
671
- try {
672
- const emailData = {
673
- to: message.toEmail,
674
- subject: message.subject,
675
- html: message.htmlContent,
676
- text: message.textContent,
677
- metadata: message.metadata,
678
- };
679
- const result = await this.sendEmail(emailData);
680
- return {
681
- success: result.success,
682
- messageId: result.messageId,
683
- provider: result.provider,
684
- };
685
- }
686
- catch (error) {
687
- return {
688
- success: false,
689
- errorMessage: error instanceof Error ? error.message : 'Unknown send error',
690
- };
691
- }
692
- }
693
- };
694
- const batchSender = createBatchSender(senderAdapter, options);
695
- return batchSender.send(emails);
696
- }
697
- // ======================
698
- // Subscription Management Methods
699
- // ======================
700
- /**
701
- * Create a new subscriber list.
702
- *
703
- * @param name - The list name
704
- * @param options - Optional description and metadata
705
- * @returns The created SubscriberList
706
- */
707
- async createSubscriberList(name, options) {
708
- return this.subscriptionListManager.createList(name, options);
709
- }
710
- /**
711
- * Get a subscriber list by ID.
712
- *
713
- * @param listId - The list ID
714
- * @returns The SubscriberList or null if not found
715
- */
716
- async getSubscriberList(listId) {
717
- return this.subscriptionListManager.getList(listId);
718
- }
719
- /**
720
- * Delete a subscriber list and all its subscribers.
721
- *
722
- * @param listId - The list ID
723
- * @returns true if the list was deleted
724
- */
725
- async deleteSubscriberList(listId) {
726
- return this.subscriptionListManager.deleteList(listId);
727
- }
728
- /**
729
- * Add a subscriber to a list.
730
- *
731
- * Checks for suppression and duplicates before adding.
732
- *
733
- * @param listId - The list ID
734
- * @param input - Subscriber email, name, and metadata
735
- * @throws {SubscriptionError} If list not found, email suppressed, or duplicate
736
- */
737
- async addSubscriber(listId, input) {
738
- return this.subscriptionListManager.addSubscriber(listId, input);
739
- }
740
- /**
741
- * Add multiple subscribers to a list in bulk.
742
- *
743
- * Skips duplicates and suppressed emails without throwing.
744
- *
745
- * @param listId - The list ID
746
- * @param subscribers - Array of subscriber inputs
747
- * @returns BulkAddResult with added/skipped counts
748
- */
749
- async addSubscribers(listId, subscribers) {
750
- return this.subscriptionListManager.addSubscribers(listId, subscribers);
751
- }
752
- /**
753
- * Remove a subscriber from a list.
754
- *
755
- * @param listId - The list ID
756
- * @param email - The subscriber email
757
- * @returns true if the subscriber was removed
758
- */
759
- async removeSubscriber(listId, email) {
760
- return this.subscriptionListManager.removeSubscriber(listId, email);
761
- }
762
- /**
763
- * Get a subscriber from a list.
764
- *
765
- * @param listId - The list ID
766
- * @param email - The subscriber email
767
- * @returns The Subscriber or null if not found
768
- */
769
- async getSubscriber(listId, email) {
770
- return this.subscriptionListManager.getSubscriber(listId, email);
771
- }
772
- /**
773
- * Generate an unsubscribe URL for a subscriber.
774
- *
775
- * Requires subscription.unsubscribe configuration in the manager config.
776
- *
777
- * @param email - The subscriber email
778
- * @param listId - The list ID
779
- * @returns The signed unsubscribe URL
780
- * @throws {Error} If unsubscribe manager is not configured
781
- */
782
- generateUnsubscribeUrl(email, listId) {
783
- if (!this.unsubscribeManager) {
784
- throw new Error('UnsubscribeManager is not configured. Provide subscription.unsubscribe config.');
785
- }
786
- return this.unsubscribeManager.generateUnsubscribeUrl(email, listId);
787
- }
788
- /**
789
- * Process an unsubscribe request from a signed token.
790
- *
791
- * Verifies the token, updates subscriber status, and adds suppression.
792
- *
793
- * @param token - The unsubscribe token from the URL
794
- * @throws {Error} If unsubscribe manager is not configured
795
- * @throws {SubscriptionError} If token is invalid or expired
796
- */
797
- async processUnsubscribe(token) {
798
- if (!this.unsubscribeManager) {
799
- throw new Error('UnsubscribeManager is not configured. Provide subscription.unsubscribe config.');
800
- }
801
- return this.unsubscribeManager.processUnsubscribe(token);
802
- }
803
- /**
804
- * Check if an email address is suppressed.
805
- *
806
- * @param email - The email address to check
807
- * @param listId - Optional list ID for scope-specific checks
808
- * @returns true if the email is suppressed
809
- */
810
- async isSuppressed(email, listId) {
811
- return this.suppressionManager.isSuppressed(email, listId);
812
- }
813
- /**
814
- * Send an email with List-Unsubscribe headers automatically added.
815
- *
816
- * Generates unsubscribe URL and adds RFC 2369/8058 headers to the email.
817
- * Requires subscription.unsubscribe configuration.
818
- *
819
- * @param email - The email data to send
820
- * @param listId - The list ID for unsubscribe scoping
821
- * @param recipientEmail - The recipient email for unsubscribe token
822
- * @param oneClick - Whether to include RFC 8058 one-click unsubscribe
823
- * @returns SendResult from the email send operation
824
- * @throws {Error} If unsubscribe manager is not configured
825
- */
826
- async sendWithUnsubscribe(email, listId, recipientEmail, oneClick = true) {
827
- if (!this.unsubscribeManager) {
828
- throw new Error('UnsubscribeManager is not configured. Provide subscription.unsubscribe config.');
829
- }
830
- // Generate unsubscribe URL
831
- const unsubscribeUrl = this.unsubscribeManager.generateUnsubscribeUrl(recipientEmail, listId);
832
- // Create List-Unsubscribe headers
833
- const unsubscribeHeaders = createListUnsubscribeHeaders(unsubscribeUrl, undefined, oneClick);
834
- // Merge unsubscribe headers into email metadata (headers)
835
- const emailWithHeaders = {
836
- ...email,
837
- metadata: {
838
- ...email.metadata,
839
- unsubscribeHeaders,
840
- listId,
841
- },
842
- };
843
- return this.sendEmail(emailWithHeaders);
844
- }
845
- /**
846
- * Set a custom subscription store (e.g., database-backed).
847
- *
848
- * Replaces the default InMemorySubscriptionStore and reinitializes
849
- * all subscription managers to use the new store.
850
- *
851
- * @param store - A SubscriptionStore implementation
852
- */
853
- setSubscriptionStore(store) {
854
- this.subscriptionStore = store;
855
- this.subscriptionListManager = new SubscriptionListManager(store);
856
- this.suppressionManager = new SuppressionManager(store);
857
- if (this.enhancedConfig.subscription?.unsubscribe) {
858
- this.unsubscribeManager = new UnsubscribeManager(store, this.enhancedConfig.subscription.unsubscribe);
859
- }
860
- }
861
- // ======================
862
- // System Operations
863
- // ======================
864
- /**
865
- * Bootstrap the email manager system
866
- */
867
- async bootstrap() {
868
- const result = {
869
- success: true,
870
- components: {},
871
- errors: [],
872
- warnings: []
873
- };
874
- try {
875
- // 1. Bootstrap senders
876
- if (this.enhancedConfig.bootstrap?.senders?.enabled) {
877
- const senderResult = await this.bootstrapSenders();
878
- result.components.senders = senderResult;
879
- if (!senderResult.success) {
880
- result.errors.push(...senderResult.errors);
881
- }
882
- }
883
- // 2. Bootstrap variable contexts
884
- if (this.enhancedConfig.bootstrap?.variables?.enabled) {
885
- const variableResult = await this.bootstrapVariableContexts();
886
- result.components.variables = variableResult;
887
- if (!variableResult.success) {
888
- result.errors.push(...variableResult.errors);
889
- }
890
- }
891
- // 3. Bootstrap templates
892
- if (this.enhancedConfig.bootstrap?.templates?.enabled) {
893
- const templateResult = await this.bootstrapTemplates();
894
- result.components.templates = templateResult;
895
- if (!templateResult.success) {
896
- result.errors.push(...templateResult.errors);
897
- }
898
- }
899
- // 4. Bootstrap providers
900
- if (this.enhancedConfig.bootstrap?.providers?.enabled) {
901
- const providerResult = await this.bootstrapProviders();
902
- result.components.providers = providerResult;
903
- if (!providerResult.success) {
904
- result.warnings.push(...providerResult.errors);
905
- }
906
- }
907
- // 5. Final health check
908
- const health = await this.getSystemHealth();
909
- if (health.overall.status === 'unhealthy') {
910
- result.warnings.push('System health check indicates issues after bootstrap');
911
- }
912
- this.initialized = true;
913
- return result;
914
- }
915
- catch (error) {
916
- result.success = false;
917
- result.errors.push(`Bootstrap failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
918
- return result;
919
- }
920
- }
921
- /**
922
- * Get comprehensive system health report
923
- */
924
- async getSystemHealth() {
925
- const emailStats = await this.getEmailDeliveryStats();
926
- const templateStats = await this.getTemplateSystemStats();
927
- const senderStats = await this.getSenderSystemStats();
928
- const providerStats = await this.getProviderHealthStats();
929
- const subscriptionStats = await this.getSubscriptionHealthStats();
930
- const batchSenderStats = this.getBatchSenderHealthStats();
931
- const allComponents = [
932
- emailStats,
933
- templateStats,
934
- senderStats,
935
- providerStats
936
- ];
937
- // Only include subscription and batch sender in overall health
938
- // calculation if they are configured
939
- if (subscriptionStats) {
940
- allComponents.push(subscriptionStats);
941
- }
942
- if (batchSenderStats) {
943
- allComponents.push(batchSenderStats);
944
- }
945
- const overallHealth = this.calculateOverallHealth(allComponents);
946
- const components = {
947
- email: emailStats,
948
- templates: templateStats,
949
- senders: senderStats,
950
- providers: providerStats
951
- };
952
- if (subscriptionStats) {
953
- components.subscription = subscriptionStats;
954
- }
955
- if (batchSenderStats) {
956
- components.batchSender = batchSenderStats;
957
- }
958
- return {
959
- overall: overallHealth,
960
- timestamp: new Date(),
961
- components,
962
- recommendations: this.generateHealthRecommendations({
963
- emailStats,
964
- templateStats,
965
- senderStats,
966
- providerHealth: providerStats
967
- })
968
- };
969
- }
970
- // ======================
971
- // Private Helper Methods
972
- // ======================
973
- async bootstrapSenders() {
974
- const result = {
975
- success: true,
976
- created: [],
977
- updated: [],
978
- errors: []
979
- };
980
- const defaultSenders = this.enhancedConfig.bootstrap?.senders?.defaultSenders || [];
981
- for (const senderDef of defaultSenders) {
982
- try {
983
- const created = await this.createSender(senderDef);
984
- if (created) {
985
- result.created.push(created.id);
986
- }
987
- }
988
- catch (error) {
989
- result.errors.push(`Failed to bootstrap sender "${senderDef.name}": ${error instanceof Error ? error.message : 'Unknown error'}`);
990
- result.success = false;
991
- }
992
- }
993
- return result;
994
- }
995
- async bootstrapVariableContexts() {
996
- const result = {
997
- success: true,
998
- created: [],
999
- updated: [],
1000
- errors: []
1001
- };
1002
- const contexts = this.enhancedConfig.bootstrap?.variables?.contexts || [];
1003
- for (const contextDef of contexts) {
1004
- try {
1005
- await this.registerVariableContext(contextDef.name, contextDef);
1006
- result.created.push(contextDef.name);
1007
- }
1008
- catch (error) {
1009
- result.errors.push(`Failed to bootstrap context "${contextDef.name}": ${error instanceof Error ? error.message : 'Unknown error'}`);
1010
- result.success = false;
1011
- }
1012
- }
1013
- return result;
1014
- }
1015
- async bootstrapTemplates() {
1016
- const result = {
1017
- success: true,
1018
- created: [],
1019
- updated: [],
1020
- errors: []
1021
- };
1022
- const defaultTemplates = this.enhancedConfig.bootstrap?.templates?.defaultTemplates || [];
1023
- for (const templateDef of defaultTemplates) {
1024
- try {
1025
- const createResult = await this.createEnhancedTemplate(templateDef);
1026
- if (createResult.success && createResult.templateId) {
1027
- result.created.push(createResult.templateId);
1028
- // Sync to providers if enabled
1029
- if (this.enhancedConfig.bootstrap?.templates?.syncToProviders) {
1030
- await this.syncTemplate(createResult.templateId);
1031
- }
1032
- }
1033
- else {
1034
- result.errors.push(...(createResult.errors || []));
1035
- }
1036
- }
1037
- catch (error) {
1038
- result.errors.push(`Failed to bootstrap template "${templateDef.name}": ${error instanceof Error ? error.message : 'Unknown error'}`);
1039
- result.success = false;
1040
- }
1041
- }
1042
- return result;
1043
- }
1044
- async bootstrapProviders() {
1045
- const result = {
1046
- success: true,
1047
- created: [],
1048
- updated: [],
1049
- errors: []
1050
- };
1051
- // Test provider connections if enabled
1052
- if (this.enhancedConfig.bootstrap?.providers?.testConnections) {
1053
- const providers = await this.listProviders();
1054
- for (const provider of providers.providers) {
1055
- try {
1056
- const testResult = await this.testConnection(provider.id);
1057
- if (testResult.success) {
1058
- result.updated.push(provider.id);
1059
- }
1060
- else {
1061
- result.errors.push(`Provider "${provider.name}" connection test failed: ${testResult.message}`);
1062
- }
1063
- }
1064
- catch (error) {
1065
- result.errors.push(`Provider "${provider.name}" test error: ${error instanceof Error ? error.message : 'Unknown error'}`);
1066
- }
1067
- }
1068
- }
1069
- return result;
1070
- }
1071
- async getEmailDeliveryStats() {
1072
- const summary = await this.getAnalyticsSummary(7);
1073
- const bounceRate = summary.bounceRate || 0;
1074
- const issues = [];
1075
- if (bounceRate > 5) {
1076
- issues.push({
1077
- severity: 'warning',
1078
- message: 'High bounce rate detected',
1079
- details: `Current bounce rate: ${bounceRate.toFixed(2)}%`
1080
- });
1081
- }
1082
- return {
1083
- status: bounceRate > 10 ? 'unhealthy' : bounceRate > 5 ? 'degraded' : 'healthy',
1084
- score: Math.max(0, 100 - bounceRate * 10),
1085
- metrics: {
1086
- totalSent: summary.totalSent || 0,
1087
- totalDelivered: summary.totalDelivered || 0,
1088
- bounceRate,
1089
- deliveryRate: summary.deliveryRate || 100
1090
- },
1091
- issues
1092
- };
1093
- }
1094
- async getTemplateSystemStats() {
1095
- const templates = Array.from(this.templateStore.values());
1096
- const activeTemplates = templates.filter(t => t.isActive);
1097
- return {
1098
- status: 'healthy',
1099
- score: 100,
1100
- metrics: {
1101
- totalTemplates: templates.length,
1102
- activeTemplates: activeTemplates.length
1103
- },
1104
- issues: []
1105
- };
1106
- }
1107
- async getSenderSystemStats() {
1108
- const senders = Array.from(this.senderStore.values());
1109
- const activeSenders = senders.filter(s => s.isActive);
1110
- const verifiedSenders = activeSenders.filter(s => s.isVerified);
1111
- const defaultSenders = senders.filter(s => s.isDefault);
1112
- const issues = [];
1113
- if (senders.length > 0 && defaultSenders.length === 0) {
1114
- issues.push({
1115
- severity: 'error',
1116
- message: 'No default sender configured'
1117
- });
1118
- }
1119
- const verificationRate = activeSenders.length > 0 ?
1120
- (verifiedSenders.length / activeSenders.length) * 100 : 100;
1121
- if (verificationRate < 50 && activeSenders.length > 0) {
1122
- issues.push({
1123
- severity: 'warning',
1124
- message: 'Low sender verification rate',
1125
- details: `Only ${Math.round(verificationRate)}% of active senders are verified`
1126
- });
1127
- }
1128
- return {
1129
- status: issues.some(i => i.severity === 'error') ? 'unhealthy' :
1130
- issues.length > 0 ? 'degraded' : 'healthy',
1131
- score: Math.max(0, 100 - issues.length * 20),
1132
- metrics: {
1133
- totalSenders: senders.length,
1134
- activeSenders: activeSenders.length,
1135
- verifiedSenders: verifiedSenders.length,
1136
- defaultSenders: defaultSenders.length,
1137
- verificationRate: Math.round(verificationRate)
1138
- },
1139
- issues
1140
- };
1141
- }
1142
- async getProviderHealthStats() {
1143
- const providers = await this.listProviders();
1144
- const activeProviders = providers.providers.filter(p => p.isActive);
1145
- const issues = [];
1146
- if (activeProviders.length === 0) {
1147
- issues.push({
1148
- severity: 'error',
1149
- message: 'No active email providers configured'
1150
- });
1151
- }
1152
- return {
1153
- status: activeProviders.length === 0 ? 'unhealthy' : 'healthy',
1154
- score: activeProviders.length > 0 ? 100 : 0,
1155
- metrics: {
1156
- totalProviders: providers.providers.length,
1157
- activeProviders: activeProviders.length
1158
- },
1159
- issues
1160
- };
1161
- }
1162
- async getSubscriptionHealthStats() {
1163
- if (!this.enhancedConfig.subscription?.enabled) {
1164
- return null;
1165
- }
1166
- try {
1167
- const lists = await this.subscriptionListManager.listLists();
1168
- const suppressions = await this.suppressionManager.listSuppressions();
1169
- const totalSubscribers = lists.items.reduce((sum, list) => sum + list.subscriberCount, 0);
1170
- const issues = [];
1171
- if (lists.total === 0) {
1172
- issues.push({
1173
- severity: 'info',
1174
- message: 'No subscription lists configured',
1175
- details: 'Create subscription lists to manage email recipients'
1176
- });
1177
- }
1178
- if (suppressions.total > 0 && lists.total > 0) {
1179
- const suppressionRatio = suppressions.total / Math.max(totalSubscribers, 1);
1180
- if (suppressionRatio > 0.3) {
1181
- issues.push({
1182
- severity: 'warning',
1183
- message: 'High suppression ratio',
1184
- details: `${suppressions.total} suppressions vs ${totalSubscribers} subscribers`
1185
- });
1186
- }
1187
- }
1188
- const hasDegraded = issues.some(i => i.severity === 'warning');
1189
- const score = Math.max(0, 100 - issues.filter(i => i.severity === 'warning').length * 20);
1190
- return {
1191
- status: hasDegraded ? 'degraded' : 'healthy',
1192
- score,
1193
- metrics: {
1194
- listCount: lists.total,
1195
- totalSubscribers,
1196
- suppressionCount: suppressions.total
1197
- },
1198
- issues
1199
- };
1200
- }
1201
- catch (error) {
1202
- return {
1203
- status: 'degraded',
1204
- score: 50,
1205
- metrics: {
1206
- listCount: 0,
1207
- totalSubscribers: 0,
1208
- suppressionCount: 0
1209
- },
1210
- issues: [{
1211
- severity: 'warning',
1212
- message: 'Failed to retrieve subscription health',
1213
- details: error instanceof Error ? error.message : 'Unknown error'
1214
- }]
1215
- };
1216
- }
1217
- }
1218
- getBatchSenderHealthStats() {
1219
- // The batch sender is available if the email-batch-sender package is
1220
- // imported and the manager has at least one active provider configured.
1221
- // Since createBatchSender is a factory that wraps an EmailSenderInterface,
1222
- // it is always structurally available but only useful with providers.
1223
- const hasProviders = this.enhancedConfig.providers.length > 0;
1224
- if (!hasProviders) {
1225
- return null;
1226
- }
1227
- return {
1228
- status: 'healthy',
1229
- score: 100,
1230
- metrics: {
1231
- available: 1,
1232
- configured: 1
1233
- },
1234
- issues: []
1235
- };
1236
- }
1237
- calculateOverallHealth(components) {
1238
- const avgScore = components.reduce((sum, c) => sum + c.score, 0) / components.length;
1239
- const hasUnhealthy = components.some(c => c.status === 'unhealthy');
1240
- const hasDegraded = components.some(c => c.status === 'degraded');
1241
- return {
1242
- status: hasUnhealthy ? 'unhealthy' : hasDegraded ? 'degraded' : 'healthy',
1243
- score: Math.round(avgScore),
1244
- metrics: {
1245
- componentsHealthy: components.filter(c => c.status === 'healthy').length,
1246
- componentsDegraded: components.filter(c => c.status === 'degraded').length,
1247
- componentsUnhealthy: components.filter(c => c.status === 'unhealthy').length
1248
- },
1249
- issues: components.flatMap(c => c.issues)
1250
- };
1251
- }
1252
- generateHealthRecommendations(stats) {
1253
- const recommendations = [];
1254
- // Email delivery recommendations
1255
- if (stats.emailStats.metrics.bounceRate > 5) {
1256
- recommendations.push({
1257
- priority: 'high',
1258
- category: 'delivery',
1259
- title: 'High Bounce Rate Detected',
1260
- description: 'Consider reviewing sender reputation and email list quality',
1261
- action: 'Review and clean email lists, check sender verification status'
1262
- });
1263
- }
1264
- // Sender verification recommendations
1265
- if (stats.senderStats.metrics.verificationRate < 80) {
1266
- recommendations.push({
1267
- priority: 'medium',
1268
- category: 'senders',
1269
- title: 'Low Sender Verification Rate',
1270
- description: 'Improve email deliverability by verifying more senders',
1271
- action: 'Complete sender verification process with email providers'
1272
- });
1273
- }
1274
- // Provider health recommendations
1275
- if (stats.providerHealth.metrics.activeProviders === 0) {
1276
- recommendations.push({
1277
- priority: 'high',
1278
- category: 'providers',
1279
- title: 'No Active Providers',
1280
- description: 'Email sending will fail without active providers',
1281
- action: 'Configure and activate at least one email provider'
1282
- });
1283
- }
1284
- return recommendations;
1285
- }
1286
- renderSimpleTemplate(template, data) {
1287
- let result = template;
1288
- const flattenObject = (obj, prefix = '') => {
1289
- const flattened = {};
1290
- for (const [key, value] of Object.entries(obj)) {
1291
- const path = prefix ? `${prefix}.${key}` : key;
1292
- if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
1293
- Object.assign(flattened, flattenObject(value, path));
1294
- }
1295
- else {
1296
- flattened[path] = String(value ?? '');
1297
- }
1298
- }
1299
- return flattened;
1300
- };
1301
- const flatData = flattenObject(data);
1302
- for (const [key, value] of Object.entries(flatData)) {
1303
- const patterns = [
1304
- new RegExp(`\\{\\{\\s*${key.replace(/\./g, '\\.')}\\s*\\}\\}`, 'g')
1305
- ];
1306
- for (const pattern of patterns) {
1307
- result = result.replace(pattern, value);
1308
- }
1309
- }
1310
- return result;
1311
- }
1312
- mapToEnhancedSender(sender) {
1313
- return {
1314
- id: sender.id,
1315
- name: sender.name,
1316
- fromEmail: sender.fromEmail,
1317
- fromName: sender.fromName,
1318
- replyToEmail: sender.replyToEmail,
1319
- provider: sender.provider,
1320
- priority: sender.priority,
1321
- isDefault: sender.isDefault,
1322
- isActive: sender.isActive,
1323
- isVerified: sender.isVerified,
1324
- verificationStatus: sender.verificationStatus,
1325
- createdAt: sender.createdAt,
1326
- updatedAt: sender.updatedAt
1327
- };
1328
- }
1329
- serviceDataToEnhancedSender(data, request) {
1330
- const now = new Date();
1331
- return {
1332
- id: data.id,
1333
- name: data.name || request?.name || '',
1334
- fromEmail: data.email || request?.fromEmail || '',
1335
- fromName: data.name || request?.fromName || '',
1336
- replyToEmail: data.replyToEmail || request?.replyToEmail,
1337
- provider: data.provider || request?.provider,
1338
- priority: data.priority || request?.priority || 100,
1339
- isDefault: data.isDefault || request?.isDefault || false,
1340
- isActive: data.isActive !== undefined ? data.isActive : true,
1341
- isVerified: data.isVerified || false,
1342
- verificationStatus: data.status || 'pending',
1343
- createdAt: data.createdAt ? new Date(data.createdAt) : now,
1344
- updatedAt: data.updatedAt ? new Date(data.updatedAt) : now,
1345
- };
1346
- }
1347
- extractDomain(email) {
1348
- const parts = email.split('@');
1349
- return parts.length > 1 ? parts[1].toLowerCase() : '';
1350
- }
1351
- isNestedPath(path, definedPaths) {
1352
- // Check if the path is a child of any defined paths
1353
- for (const defined of definedPaths) {
1354
- if (path.startsWith(defined + '.')) {
1355
- return true;
1356
- }
1357
- }
1358
- return false;
1359
- }
1360
- getNestedValue(obj, path) {
1361
- const parts = path.split('.');
1362
- let current = obj;
1363
- for (const part of parts) {
1364
- if (current === null || current === undefined || typeof current !== 'object') {
1365
- return undefined;
1366
- }
1367
- current = current[part];
1368
- }
1369
- return current;
1370
- }
1371
- /**
1372
- * Check if the enhanced manager is initialized
1373
- */
1374
- isInitialized() {
1375
- return this.initialized;
1376
- }
1377
- /**
1378
- * Get template store size
1379
- */
1380
- getTemplateCount() {
1381
- return this.templateStore.size;
1382
- }
1383
- /**
1384
- * Get sender store size
1385
- */
1386
- getSenderCount() {
1387
- return this.senderStore.size;
1388
- }
1389
- /**
1390
- * Get variable context count
1391
- */
1392
- getVariableContextCount() {
1393
- return this.variableContexts.size;
1394
- }
1395
- }
1396
- //# sourceMappingURL=enhanced-email-manager.js.map