@contentgrowth/content-emailing 0.4.1 → 0.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.
Files changed (66) hide show
  1. package/dist/TemplateManager-Db41KyPN.d.cts +77 -0
  2. package/dist/TemplateManager-Db41KyPN.d.ts +77 -0
  3. package/dist/backend/EmailService.cjs +737 -0
  4. package/dist/backend/EmailService.cjs.map +1 -0
  5. package/dist/backend/EmailService.d.cts +101 -0
  6. package/dist/backend/EmailService.d.ts +101 -0
  7. package/dist/backend/EmailService.js +703 -0
  8. package/dist/backend/EmailService.js.map +1 -0
  9. package/dist/backend/EmailingCacheDO.cjs +389 -0
  10. package/dist/backend/EmailingCacheDO.cjs.map +1 -0
  11. package/dist/backend/EmailingCacheDO.d.cts +66 -0
  12. package/dist/backend/EmailingCacheDO.d.ts +66 -0
  13. package/dist/backend/EmailingCacheDO.js +364 -0
  14. package/dist/backend/EmailingCacheDO.js.map +1 -0
  15. package/dist/backend/routes/index.cjs +1001 -0
  16. package/dist/backend/routes/index.cjs.map +1 -0
  17. package/dist/backend/routes/index.d.cts +32 -0
  18. package/dist/backend/routes/index.d.ts +32 -0
  19. package/dist/backend/routes/index.js +965 -0
  20. package/dist/backend/routes/index.js.map +1 -0
  21. package/dist/cli.cjs +53 -0
  22. package/dist/cli.cjs.map +1 -0
  23. package/dist/cli.d.cts +1 -0
  24. package/dist/cli.d.ts +1 -0
  25. package/dist/cli.js +53 -0
  26. package/dist/cli.js.map +1 -0
  27. package/dist/common/index.cjs +267 -0
  28. package/dist/common/index.cjs.map +1 -0
  29. package/dist/common/index.d.cts +46 -0
  30. package/dist/common/index.d.ts +46 -0
  31. package/{src/common/htmlWrapper.js → dist/common/index.js} +75 -18
  32. package/dist/common/index.js.map +1 -0
  33. package/dist/frontend/index.cjs +665 -0
  34. package/dist/frontend/index.cjs.map +1 -0
  35. package/dist/frontend/index.d.cts +32 -0
  36. package/dist/frontend/index.d.ts +32 -0
  37. package/dist/frontend/index.js +626 -0
  38. package/dist/frontend/index.js.map +1 -0
  39. package/dist/index.cjs +1842 -0
  40. package/dist/index.cjs.map +1 -0
  41. package/dist/index.d.cts +7 -0
  42. package/dist/index.d.ts +7 -0
  43. package/dist/index.js +1793 -0
  44. package/dist/index.js.map +1 -0
  45. package/package.json +31 -13
  46. package/examples/.env.example +0 -16
  47. package/examples/README.md +0 -55
  48. package/examples/mocks/MockD1.js +0 -311
  49. package/examples/mocks/MockEmailSender.js +0 -64
  50. package/examples/mocks/index.js +0 -5
  51. package/examples/package-lock.json +0 -73
  52. package/examples/package.json +0 -18
  53. package/examples/portal/index.html +0 -919
  54. package/examples/server.js +0 -314
  55. package/release.sh +0 -56
  56. package/src/backend/EmailService.js +0 -537
  57. package/src/backend/EmailingCacheDO.js +0 -466
  58. package/src/backend/routes/index.js +0 -30
  59. package/src/backend/routes/templates.js +0 -98
  60. package/src/backend/routes/tracking.js +0 -215
  61. package/src/backend/routes.js +0 -98
  62. package/src/common/index.js +0 -11
  63. package/src/common/utils.js +0 -141
  64. package/src/frontend/TemplateEditor.jsx +0 -117
  65. package/src/frontend/TemplateManager.jsx +0 -117
  66. package/src/index.js +0 -24
@@ -0,0 +1,737 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/backend/EmailService.js
30
+ var EmailService_exports = {};
31
+ __export(EmailService_exports, {
32
+ EmailService: () => EmailService
33
+ });
34
+ module.exports = __toCommonJS(EmailService_exports);
35
+ var import_marked = require("marked");
36
+ var import_mustache = __toESM(require("mustache"), 1);
37
+
38
+ // src/common/htmlWrapper.js
39
+ function wrapInEmailTemplate(contentHtml, subject, data = {}) {
40
+ const portalUrl = data.portalUrl || "https://app.x0start.com";
41
+ const unsubscribeUrl = data.unsubscribeUrl || "{{unsubscribe_url}}";
42
+ const brandName = data.brandName || "X0 Start";
43
+ return `
44
+ <!DOCTYPE html>
45
+ <html lang="en">
46
+ <head>
47
+ <meta charset="UTF-8">
48
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
49
+ <title>${subject}</title>
50
+ <style>
51
+ body {
52
+ margin: 0;
53
+ padding: 0;
54
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
55
+ background-color: #f5f5f5;
56
+ line-height: 1.6;
57
+ }
58
+ .email-wrapper {
59
+ background-color: #f5f5f5;
60
+ padding: 40px 20px;
61
+ }
62
+ .email-container {
63
+ max-width: 600px;
64
+ margin: 0 auto;
65
+ background-color: #ffffff;
66
+ border-radius: 8px;
67
+ overflow: hidden;
68
+ box-shadow: 0 2px 8px rgba(0,0,0,0.1);
69
+ }
70
+ .email-header {
71
+ padding: 40px 40px 20px;
72
+ text-align: center;
73
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
74
+ color: #ffffff;
75
+ }
76
+ .email-header h1 {
77
+ margin: 0;
78
+ font-size: 28px;
79
+ font-weight: 600;
80
+ }
81
+ .email-content {
82
+ padding: 30px 40px;
83
+ color: #333333;
84
+ }
85
+ .email-content h1 {
86
+ font-size: 24px;
87
+ margin-top: 0;
88
+ margin-bottom: 20px;
89
+ color: #333333;
90
+ }
91
+ .email-content h2 {
92
+ font-size: 20px;
93
+ margin-top: 30px;
94
+ margin-bottom: 15px;
95
+ color: #333333;
96
+ }
97
+ .email-content h3 {
98
+ font-size: 16px;
99
+ margin-top: 20px;
100
+ margin-bottom: 10px;
101
+ color: #333333;
102
+ }
103
+ .email-content p {
104
+ margin: 0 0 15px;
105
+ color: #666666;
106
+ }
107
+ .email-content a {
108
+ color: #667eea;
109
+ text-decoration: none;
110
+ }
111
+ .email-content ul, .email-content ol {
112
+ margin: 0 0 15px;
113
+ padding-left: 25px;
114
+ }
115
+ .email-content li {
116
+ margin-bottom: 8px;
117
+ color: #666666;
118
+ }
119
+ .email-content blockquote {
120
+ margin: 20px 0;
121
+ padding: 15px 20px;
122
+ background-color: #f8f9fa;
123
+ border-left: 4px solid #667eea;
124
+ color: #666666;
125
+ }
126
+ .email-content code {
127
+ padding: 2px 6px;
128
+ background-color: #f8f9fa;
129
+ border-radius: 3px;
130
+ font-family: 'Courier New', monospace;
131
+ font-size: 14px;
132
+ }
133
+ .email-content pre {
134
+ padding: 15px;
135
+ background-color: #f8f9fa;
136
+ border-radius: 6px;
137
+ overflow-x: auto;
138
+ }
139
+ .email-content pre code {
140
+ padding: 0;
141
+ background: none;
142
+ }
143
+ .btn {
144
+ display: inline-block;
145
+ padding: 12px 24px;
146
+ background-color: #667eea;
147
+ color: #ffffff !important;
148
+ text-decoration: none;
149
+ border-radius: 6px;
150
+ font-weight: 600;
151
+ margin: 10px 0;
152
+ }
153
+ .btn:hover {
154
+ background-color: #5568d3;
155
+ }
156
+ .email-footer {
157
+ padding: 20px 40px;
158
+ background-color: #f8f9fa;
159
+ text-align: center;
160
+ font-size: 12px;
161
+ color: #666666;
162
+ }
163
+ .email-footer a {
164
+ color: #667eea;
165
+ text-decoration: none;
166
+ }
167
+ hr {
168
+ border: none;
169
+ border-top: 1px solid #e0e0e0;
170
+ margin: 30px 0;
171
+ }
172
+ </style>
173
+ </head>
174
+ <body>
175
+ <div class="email-wrapper">
176
+ <div class="email-container">
177
+ <div class="email-content">
178
+ ${contentHtml}
179
+ </div>
180
+ <div class="email-footer">
181
+ <p style="margin: 0 0 10px;">
182
+ You're receiving this email from ${brandName}.
183
+ </p>
184
+ <p style="margin: 0;">
185
+ <a href="${unsubscribeUrl}">Unsubscribe</a> |
186
+ <a href="${portalUrl}/settings/notifications">Manage Preferences</a>
187
+ </p>
188
+ </div>
189
+ </div>
190
+ </div>
191
+ </body>
192
+ </html>
193
+ `.trim();
194
+ }
195
+
196
+ // src/backend/EmailingCacheDO.js
197
+ function createDOCacheProvider(doStub, instanceName = "global") {
198
+ if (!doStub) {
199
+ return null;
200
+ }
201
+ const stub = doStub.get(doStub.idFromName(instanceName));
202
+ return {
203
+ async getTemplate(templateId) {
204
+ try {
205
+ const response = await stub.fetch(`http://do/get?templateId=${templateId}`);
206
+ const data = await response.json();
207
+ return data.template || null;
208
+ } catch (e) {
209
+ return null;
210
+ }
211
+ },
212
+ async getSettings(profile, tenantId) {
213
+ const key = `${profile}:${tenantId || ""}`;
214
+ try {
215
+ const response = await stub.fetch(`http://do/settings/get?key=${encodeURIComponent(key)}`);
216
+ const data = await response.json();
217
+ return data.settings || null;
218
+ } catch (e) {
219
+ return null;
220
+ }
221
+ },
222
+ async putSettings(profile, tenantId, settings) {
223
+ const key = `${profile}:${tenantId || ""}`;
224
+ try {
225
+ await stub.fetch("http://do/settings/put", {
226
+ method: "POST",
227
+ headers: { "Content-Type": "application/json" },
228
+ body: JSON.stringify({ key, settings })
229
+ });
230
+ } catch (e) {
231
+ console.warn("[DOCacheProvider] Failed to cache settings:", e);
232
+ }
233
+ },
234
+ async putTemplate(template) {
235
+ try {
236
+ await stub.fetch("http://do/invalidate", {
237
+ method: "POST",
238
+ headers: { "Content-Type": "application/json" },
239
+ body: JSON.stringify({ templateId: template.template_id })
240
+ });
241
+ } catch (e) {
242
+ console.warn("[DOCacheProvider] Failed to invalidate template:", e);
243
+ }
244
+ },
245
+ async deleteTemplate(templateId) {
246
+ try {
247
+ await stub.fetch("http://do/invalidate", {
248
+ method: "POST",
249
+ headers: { "Content-Type": "application/json" },
250
+ body: JSON.stringify({ templateId })
251
+ });
252
+ } catch (e) {
253
+ console.warn("[DOCacheProvider] Failed to invalidate template:", e);
254
+ }
255
+ },
256
+ async invalidateSettings(profile, tenantId) {
257
+ const key = `${profile}:${tenantId || ""}`;
258
+ try {
259
+ await stub.fetch("http://do/settings/invalidate", {
260
+ method: "POST",
261
+ headers: { "Content-Type": "application/json" },
262
+ body: JSON.stringify({ key })
263
+ });
264
+ } catch (e) {
265
+ console.warn("[DOCacheProvider] Failed to invalidate settings:", e);
266
+ }
267
+ }
268
+ };
269
+ }
270
+
271
+ // src/backend/EmailService.js
272
+ var EmailService = class {
273
+ /**
274
+ * @param {Object} env - Cloudflare environment bindings (DB, etc.)
275
+ * @param {Object} config - Configuration options
276
+ * @param {string} [config.emailTablePrefix='system_email_'] - Prefix for D1 tables
277
+ * @param {Object} [config.defaults] - Default settings (fromName, fromAddress)
278
+ * @param {Object} [cacheProvider] - Optional cache interface (DO stub or KV wrapper)
279
+ */
280
+ constructor(env, config = {}, cacheProvider = null) {
281
+ this.env = env;
282
+ this.db = env.DB;
283
+ this.config = {
284
+ emailTablePrefix: config.emailTablePrefix || config.tableNamePrefix || "system_email_",
285
+ defaults: config.defaults || {
286
+ fromName: "System",
287
+ fromAddress: "noreply@example.com",
288
+ provider: "mailchannels"
289
+ },
290
+ // Loader function to fetch settings from backend (DB, KV, etc.)
291
+ // Signature: async (profile, tenantId) => SettingsObject
292
+ settingsLoader: config.settingsLoader || null,
293
+ // Updater function to save settings to backend
294
+ // Signature: async (profile, tenantId, settings) => void
295
+ settingsUpdater: config.settingsUpdater || null,
296
+ // Branding configuration for email templates
297
+ branding: {
298
+ brandName: config.branding?.brandName || "Your App",
299
+ portalUrl: config.branding?.portalUrl || "https://app.example.com",
300
+ primaryColor: config.branding?.primaryColor || "#667eea",
301
+ ...config.branding
302
+ },
303
+ ...config
304
+ };
305
+ if (!cacheProvider && env.EMAIL_TEMPLATE_CACHE) {
306
+ this.cache = createDOCacheProvider(env.EMAIL_TEMPLATE_CACHE);
307
+ } else {
308
+ this.cache = cacheProvider;
309
+ }
310
+ }
311
+ // --- Configuration & Settings ---
312
+ /**
313
+ * Load email configuration
314
+ * @param {string} profile - 'system' or 'tenant' (or custom profile string)
315
+ * @param {string} tenantId - Context ID (optional)
316
+ * @returns {Promise<Object>} Email configuration
317
+ */
318
+ async loadSettings(profile = "system", tenantId = null) {
319
+ if (this.cache && this.cache.getSettings) {
320
+ try {
321
+ const cached = await this.cache.getSettings(profile, tenantId);
322
+ if (cached) return this._normalizeConfig(cached);
323
+ } catch (e) {
324
+ }
325
+ }
326
+ let settings = null;
327
+ if (this.config.settingsLoader) {
328
+ try {
329
+ settings = await this.config.settingsLoader(profile, tenantId);
330
+ } catch (e) {
331
+ console.warn("[EmailService] settingsLoader failed:", e);
332
+ }
333
+ }
334
+ if (settings) {
335
+ if (this.cache && this.cache.putSettings) {
336
+ try {
337
+ this.cache.putSettings(profile, tenantId, settings);
338
+ } catch (e) {
339
+ }
340
+ }
341
+ return this._normalizeConfig(settings);
342
+ }
343
+ return {
344
+ ...this.config.defaults
345
+ };
346
+ }
347
+ /**
348
+ * Normalize config keys to standard format
349
+ * Handles both snake_case (DB) and camelCase inputs
350
+ */
351
+ _normalizeConfig(config) {
352
+ return {
353
+ provider: config.email_provider || config.provider || this.config.defaults.provider,
354
+ fromAddress: config.email_from_address || config.fromAddress || this.config.defaults.fromAddress,
355
+ fromName: config.email_from_name || config.fromName || this.config.defaults.fromName,
356
+ // Provider-specific settings (normalize DB keys to service keys)
357
+ sendgridApiKey: config.sendgrid_api_key || config.sendgridApiKey,
358
+ resendApiKey: config.resend_api_key || config.resendApiKey,
359
+ sendpulseClientId: config.sendpulse_client_id || config.sendpulseClientId,
360
+ sendpulseClientSecret: config.sendpulse_client_secret || config.sendpulseClientSecret,
361
+ // SMTP
362
+ smtpHost: config.smtp_host || config.smtpHost,
363
+ smtpPort: config.smtp_port || config.smtpPort,
364
+ smtpUsername: config.smtp_username || config.smtpUsername,
365
+ smtpPassword: config.smtp_password || config.smtpPassword,
366
+ // Tracking
367
+ trackingUrl: config.tracking_url || config.trackingUrl,
368
+ // Pass through others
369
+ // Pass through others
370
+ ...config,
371
+ smtpSecure: config.smtp_secure === "true"
372
+ };
373
+ }
374
+ // --- Template Management ---
375
+ async getTemplate(templateId) {
376
+ if (this.cache) {
377
+ try {
378
+ const cached = await this.cache.getTemplate(templateId);
379
+ if (cached) return cached;
380
+ } catch (e) {
381
+ console.warn("[EmailService] Template cache lookup failed:", e);
382
+ }
383
+ }
384
+ const table = `${this.config.emailTablePrefix}templates`;
385
+ return await this.db.prepare(`SELECT * FROM ${table} WHERE template_id = ?`).bind(templateId).first();
386
+ }
387
+ async getAllTemplates() {
388
+ const table = `${this.config.emailTablePrefix}templates`;
389
+ const result = await this.db.prepare(`SELECT * FROM ${table} ORDER BY template_name`).all();
390
+ return result.results || [];
391
+ }
392
+ /**
393
+ * Save email configuration
394
+ * @param {Object} settings - Config object
395
+ * @param {string} profile - 'system' or 'tenant'
396
+ * @param {string} tenantId - Context ID
397
+ */
398
+ async saveSettings(settings, profile = "system", tenantId = null) {
399
+ if (this.config.settingsUpdater) {
400
+ try {
401
+ await this.config.settingsUpdater(profile, tenantId, settings);
402
+ } catch (e) {
403
+ console.error("[EmailService] settingsUpdater failed:", e);
404
+ throw e;
405
+ }
406
+ } else if (profile === "system" && this.db) {
407
+ }
408
+ if (this.cache && this.cache.invalidateSettings) {
409
+ try {
410
+ await this.cache.invalidateSettings(profile, tenantId);
411
+ } catch (e) {
412
+ console.warn("[EmailService] Failed to invalidate settings cache:", e);
413
+ }
414
+ }
415
+ }
416
+ async saveTemplate(template, userId = "system") {
417
+ const table = `${this.config.emailTablePrefix}templates`;
418
+ const now = Math.floor(Date.now() / 1e3);
419
+ const existing = await this.getTemplate(template.template_id);
420
+ if (existing) {
421
+ await this.db.prepare(`
422
+ UPDATE ${table} SET
423
+ template_name = ?, template_type = ?, subject_template = ?,
424
+ body_markdown = ?, variables = ?, description = ?, is_active = ?,
425
+ updated_at = ?, updated_by = ?
426
+ WHERE template_id = ?
427
+ `).bind(
428
+ template.template_name,
429
+ template.template_type,
430
+ template.subject_template,
431
+ template.body_markdown,
432
+ template.variables,
433
+ template.description,
434
+ template.is_active,
435
+ now,
436
+ userId,
437
+ template.template_id
438
+ ).run();
439
+ } else {
440
+ await this.db.prepare(`
441
+ INSERT INTO ${table} (
442
+ template_id, template_name, template_type, subject_template,
443
+ body_markdown, variables, description, is_active, created_at, updated_at, updated_by
444
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
445
+ `).bind(
446
+ template.template_id,
447
+ template.template_name,
448
+ template.template_type,
449
+ template.subject_template,
450
+ template.body_markdown,
451
+ template.variables || "[]",
452
+ template.description,
453
+ template.is_active || 1,
454
+ now,
455
+ now,
456
+ userId
457
+ ).run();
458
+ }
459
+ if (this.cache) {
460
+ await this.cache.putTemplate(template);
461
+ }
462
+ }
463
+ async deleteTemplate(templateId) {
464
+ const table = `${this.config.emailTablePrefix}templates`;
465
+ await this.db.prepare(`DELETE FROM ${table} WHERE template_id = ?`).bind(templateId).run();
466
+ if (this.cache) {
467
+ await this.cache.deleteTemplate(templateId);
468
+ }
469
+ }
470
+ // --- Rendering ---
471
+ async renderTemplate(templateId, data) {
472
+ const template = await this.getTemplate(templateId);
473
+ if (!template) throw new Error(`Template not found: ${templateId}`);
474
+ const subject = import_mustache.default.render(template.subject_template, data);
475
+ let markdown = import_mustache.default.render(template.body_markdown, data);
476
+ markdown = markdown.replace(/\\n/g, "\n");
477
+ import_marked.marked.use({
478
+ mangle: false,
479
+ headerIds: false,
480
+ breaks: true
481
+ // Convert single line breaks to <br>
482
+ });
483
+ const htmlContent = import_marked.marked.parse(markdown);
484
+ const html = this.wrapInBaseTemplate(htmlContent, subject, data);
485
+ const plainText = markdown.replace(/<[^>]*>/g, "");
486
+ return { subject, html, plainText };
487
+ }
488
+ wrapInBaseTemplate(content, subject, data = {}) {
489
+ const templateData = {
490
+ ...data,
491
+ brandName: data.brandName || this.config.branding.brandName,
492
+ portalUrl: data.portalUrl || this.config.branding.portalUrl,
493
+ unsubscribeUrl: data.unsubscribeUrl || "{{unsubscribe_url}}"
494
+ };
495
+ return wrapInEmailTemplate(content, subject, templateData);
496
+ }
497
+ // --- Delivery ---
498
+ /**
499
+ * Send a single email
500
+ * @param {Object} params - Email parameters
501
+ * @param {string} params.to - Recipient email
502
+ * @param {string} params.subject - Email subject
503
+ * @param {string} params.html - HTML body
504
+ * @param {string} params.text - Plain text body
505
+ * @param {string} [params.provider] - Override provider
506
+ * @param {string} [params.profile='system'] - 'system' or 'tenant'
507
+ * @param {string} [params.tenantId] - Required if profile is 'tenant'
508
+ * @param {Object} [params.metadata] - Additional metadata
509
+ * @returns {Promise<Object>} Delivery result
510
+ */
511
+ async sendEmail({ to, subject, html, htmlBody, text, textBody, provider, profile = "system", tenantId = null, metadata = {} }) {
512
+ const htmlContent = html || htmlBody;
513
+ const textContent = text || textBody;
514
+ try {
515
+ const settings = await this.loadSettings(profile, tenantId);
516
+ const useProvider = provider || settings.provider || "mailchannels";
517
+ let result;
518
+ switch (useProvider) {
519
+ case "mailchannels":
520
+ result = await this.sendViaMailChannels(to, subject, htmlContent, textContent, settings, metadata);
521
+ break;
522
+ case "sendgrid":
523
+ result = await this.sendViaSendGrid(to, subject, htmlContent, textContent, settings, metadata);
524
+ break;
525
+ case "resend":
526
+ result = await this.sendViaResend(to, subject, htmlContent, textContent, settings, metadata);
527
+ break;
528
+ case "sendpulse":
529
+ result = await this.sendViaSendPulse(to, subject, htmlContent, textContent, settings, metadata);
530
+ break;
531
+ default:
532
+ console.error(`[EmailService] Unknown provider: ${useProvider}`);
533
+ return { success: false, error: `Unknown email provider: ${useProvider}` };
534
+ }
535
+ if (result) {
536
+ return { success: true, messageId: crypto.randomUUID() };
537
+ } else {
538
+ console.error("[EmailService] Failed to send email to:", to);
539
+ return { success: false, error: "Failed to send email" };
540
+ }
541
+ } catch (error) {
542
+ console.error("[EmailService] Error sending email:", error);
543
+ return { success: false, error: error.message };
544
+ }
545
+ }
546
+ /**
547
+ * Send multiple emails in batch
548
+ * @param {Array} emails - Array of email objects
549
+ * @returns {Promise<Array>} Array of delivery results
550
+ */
551
+ async sendBatch(emails) {
552
+ console.log("[EmailService] Sending batch of", emails.length, "emails");
553
+ const results = await Promise.all(
554
+ emails.map((email) => this.sendEmail(email))
555
+ );
556
+ return results;
557
+ }
558
+ /**
559
+ * Send email via MailChannels HTTP API
560
+ * MailChannels is specifically designed for Cloudflare Workers
561
+ */
562
+ async sendViaMailChannels(to, subject, html, text, settings, metadata) {
563
+ try {
564
+ const response = await fetch("https://api.mailchannels.net/tx/v1/send", {
565
+ method: "POST",
566
+ headers: { "Content-Type": "application/json" },
567
+ body: JSON.stringify({
568
+ personalizations: [{ to: [{ email: to, name: metadata.recipientName || "" }] }],
569
+ from: { email: settings.fromAddress, name: settings.fromName },
570
+ subject,
571
+ content: [
572
+ { type: "text/plain", value: text || html.replace(/<[^>]*>/g, "") },
573
+ { type: "text/html", value: html }
574
+ ]
575
+ })
576
+ });
577
+ if (response.status === 202) {
578
+ return true;
579
+ } else {
580
+ const contentType = response.headers.get("content-type");
581
+ const errorBody = contentType?.includes("application/json") ? await response.json() : await response.text();
582
+ console.error("[EmailService] MailChannels error:", response.status, errorBody);
583
+ return false;
584
+ }
585
+ } catch (error) {
586
+ console.error("[EmailService] MailChannels exception:", error.message);
587
+ return false;
588
+ }
589
+ }
590
+ /**
591
+ * Send email via SendGrid HTTP API
592
+ */
593
+ async sendViaSendGrid(to, subject, html, text, settings, metadata) {
594
+ try {
595
+ if (!settings.sendgridApiKey) {
596
+ console.error("[EmailService] SendGrid API key missing");
597
+ return false;
598
+ }
599
+ const response = await fetch("https://api.sendgrid.com/v3/mail/send", {
600
+ method: "POST",
601
+ headers: {
602
+ "Authorization": `Bearer ${settings.sendgridApiKey}`,
603
+ "Content-Type": "application/json"
604
+ },
605
+ body: JSON.stringify({
606
+ personalizations: [{ to: [{ email: to, name: metadata.recipientName || "" }] }],
607
+ from: { email: settings.fromAddress, name: settings.fromName },
608
+ subject,
609
+ content: [
610
+ { type: "text/html", value: html },
611
+ { type: "text/plain", value: text || html.replace(/<[^>]*>/g, "") }
612
+ ]
613
+ })
614
+ });
615
+ if (response.status === 202) {
616
+ return true;
617
+ } else {
618
+ const errorText = await response.text();
619
+ console.error("[EmailService] SendGrid error:", response.status, errorText);
620
+ return false;
621
+ }
622
+ } catch (error) {
623
+ console.error("[EmailService] SendGrid exception:", error.message);
624
+ return false;
625
+ }
626
+ }
627
+ /**
628
+ * Send email via Resend HTTP API
629
+ */
630
+ async sendViaResend(to, subject, html, text, settings, metadata) {
631
+ try {
632
+ if (!settings.resendApiKey) {
633
+ console.error("[EmailService] Resend API key missing");
634
+ return false;
635
+ }
636
+ const response = await fetch("https://api.resend.com/emails", {
637
+ method: "POST",
638
+ headers: {
639
+ "Authorization": `Bearer ${settings.resendApiKey}`,
640
+ "Content-Type": "application/json"
641
+ },
642
+ body: JSON.stringify({
643
+ from: `${settings.fromName} <${settings.fromAddress}>`,
644
+ to: [to],
645
+ subject,
646
+ html,
647
+ text: text || html.replace(/<[^>]*>/g, "")
648
+ })
649
+ });
650
+ if (response.ok) {
651
+ return true;
652
+ } else {
653
+ const errorText = await response.text();
654
+ console.error("[EmailService] Resend error:", response.status, errorText);
655
+ return false;
656
+ }
657
+ } catch (error) {
658
+ console.error("[EmailService] Resend exception:", error.message);
659
+ return false;
660
+ }
661
+ }
662
+ /**
663
+ * Send email via SendPulse HTTP API
664
+ * SendPulse offers 15,000 free emails/month
665
+ */
666
+ async sendViaSendPulse(to, subject, html, text, settings, metadata) {
667
+ try {
668
+ if (!settings.sendpulseClientId || !settings.sendpulseClientSecret) {
669
+ console.error("[EmailService] SendPulse credentials missing");
670
+ return false;
671
+ }
672
+ const tokenParams = new URLSearchParams({
673
+ grant_type: "client_credentials",
674
+ client_id: settings.sendpulseClientId,
675
+ client_secret: settings.sendpulseClientSecret
676
+ });
677
+ const tokenResponse = await fetch("https://api.sendpulse.com/oauth/access_token", {
678
+ method: "POST",
679
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
680
+ body: tokenParams.toString()
681
+ });
682
+ if (!tokenResponse.ok) {
683
+ const error = await tokenResponse.text();
684
+ console.error("[EmailService] SendPulse auth error:", error);
685
+ return false;
686
+ }
687
+ const tokenData = await tokenResponse.json();
688
+ if (!tokenData.access_token) {
689
+ console.error("[EmailService] SendPulse: No access token in response");
690
+ return false;
691
+ }
692
+ const { access_token } = tokenData;
693
+ const toBase64 = (str) => {
694
+ if (!str) return "";
695
+ try {
696
+ return btoa(unescape(encodeURIComponent(String(str))));
697
+ } catch (e) {
698
+ console.error("[EmailService] Base64 encoding failed:", e);
699
+ return "";
700
+ }
701
+ };
702
+ const htmlSafe = html || "";
703
+ const textSafe = text || (htmlSafe ? htmlSafe.replace(/<[^>]*>/g, "") : "");
704
+ const response = await fetch("https://api.sendpulse.com/smtp/emails", {
705
+ method: "POST",
706
+ headers: {
707
+ "Authorization": `Bearer ${access_token}`,
708
+ "Content-Type": "application/json"
709
+ },
710
+ body: JSON.stringify({
711
+ email: {
712
+ html: toBase64(htmlSafe),
713
+ text: toBase64(textSafe),
714
+ subject,
715
+ from: { name: settings.fromName, email: settings.fromAddress },
716
+ to: [{ name: metadata.recipientName || "", email: to }]
717
+ }
718
+ })
719
+ });
720
+ if (response.ok) {
721
+ return true;
722
+ } else {
723
+ const errorText = await response.text();
724
+ console.error("[EmailService] SendPulse send error:", response.status, errorText);
725
+ return false;
726
+ }
727
+ } catch (error) {
728
+ console.error("[EmailService] SendPulse exception:", error.message);
729
+ return false;
730
+ }
731
+ }
732
+ };
733
+ // Annotate the CommonJS export names for ESM import in node:
734
+ 0 && (module.exports = {
735
+ EmailService
736
+ });
737
+ //# sourceMappingURL=EmailService.cjs.map