@contentgrowth/content-emailing 0.6.0 → 0.6.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.
- package/dist/backend/EmailService.cjs +45 -2
- package/dist/backend/EmailService.cjs.map +1 -1
- package/dist/backend/EmailService.d.cts +13 -0
- package/dist/backend/EmailService.d.ts +13 -0
- package/dist/backend/EmailService.js +45 -2
- package/dist/backend/EmailService.js.map +1 -1
- package/dist/backend/routes/index.cjs +45 -2
- package/dist/backend/routes/index.cjs.map +1 -1
- package/dist/backend/routes/index.js +45 -2
- package/dist/backend/routes/index.js.map +1 -1
- package/dist/index.cjs +45 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +45 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -468,11 +468,28 @@ var EmailService = class {
|
|
|
468
468
|
}
|
|
469
469
|
}
|
|
470
470
|
// --- Rendering ---
|
|
471
|
+
/**
|
|
472
|
+
* Pre-process template data to auto-format URLs
|
|
473
|
+
* Scans for strings starting with http:// or https:// and wraps them in Markdown links
|
|
474
|
+
*/
|
|
475
|
+
_preprocessData(data) {
|
|
476
|
+
if (!data || typeof data !== "object") return data;
|
|
477
|
+
const processed = { ...data };
|
|
478
|
+
for (const [key, value] of Object.entries(processed)) {
|
|
479
|
+
if (typeof value === "string" && (value.startsWith("http://") || value.startsWith("https://"))) {
|
|
480
|
+
if (!value.trim().startsWith("[") && !value.includes("](")) {
|
|
481
|
+
processed[key] = `[${value}](${value})`;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return processed;
|
|
486
|
+
}
|
|
471
487
|
async renderTemplate(templateId, data) {
|
|
472
488
|
const template = await this.getTemplate(templateId);
|
|
473
489
|
if (!template) throw new Error(`Template not found: ${templateId}`);
|
|
474
|
-
const
|
|
475
|
-
|
|
490
|
+
const processedData = this._preprocessData(data);
|
|
491
|
+
const subject = import_mustache.default.render(template.subject_template, processedData);
|
|
492
|
+
let markdown = import_mustache.default.render(template.body_markdown, processedData);
|
|
476
493
|
markdown = markdown.replace(/\\n/g, "\n");
|
|
477
494
|
import_marked.marked.use({
|
|
478
495
|
mangle: false,
|
|
@@ -495,6 +512,32 @@ var EmailService = class {
|
|
|
495
512
|
return wrapInEmailTemplate(content, subject, templateData);
|
|
496
513
|
}
|
|
497
514
|
// --- Delivery ---
|
|
515
|
+
/**
|
|
516
|
+
* Send an email using a template
|
|
517
|
+
* @param {string} templateId - Template ID
|
|
518
|
+
* @param {Object} data - Template variables
|
|
519
|
+
* @param {Object} options - Sending options (to, provider, etc.)
|
|
520
|
+
* @returns {Promise<Object>} Delivery result
|
|
521
|
+
*/
|
|
522
|
+
async sendViaTemplate(templateId, data, options) {
|
|
523
|
+
try {
|
|
524
|
+
const { subject, html, plainText } = await this.renderTemplate(templateId, data);
|
|
525
|
+
return await this.sendEmail({
|
|
526
|
+
...options,
|
|
527
|
+
subject,
|
|
528
|
+
// Can be overridden by options.subject if needed, but usually template subject is preferred
|
|
529
|
+
html,
|
|
530
|
+
text: plainText,
|
|
531
|
+
metadata: {
|
|
532
|
+
...options.metadata,
|
|
533
|
+
templateId
|
|
534
|
+
}
|
|
535
|
+
});
|
|
536
|
+
} catch (error) {
|
|
537
|
+
console.error(`[EmailService] sendViaTemplate failed for ${templateId}:`, error);
|
|
538
|
+
return { success: false, error: error.message };
|
|
539
|
+
}
|
|
540
|
+
}
|
|
498
541
|
/**
|
|
499
542
|
* Send a single email
|
|
500
543
|
* @param {Object} params - Email parameters
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/backend/EmailService.js","../../src/common/htmlWrapper.js","../../src/backend/EmailingCacheDO.js"],"sourcesContent":["/**\n * Email Service\n * Unified service for email delivery and template management.\n */\nimport { marked } from 'marked';\nimport Mustache from 'mustache';\nimport { wrapInEmailTemplate } from '../common/htmlWrapper.js';\nimport { createDOCacheProvider } from './EmailingCacheDO.js';\n\nexport class EmailService {\n /**\n * @param {Object} env - Cloudflare environment bindings (DB, etc.)\n * @param {Object} config - Configuration options\n * @param {string} [config.emailTablePrefix='system_email_'] - Prefix for D1 tables\n * @param {Object} [config.defaults] - Default settings (fromName, fromAddress)\n * @param {Object} [cacheProvider] - Optional cache interface (DO stub or KV wrapper)\n */\n constructor(env, config = {}, cacheProvider = null) {\n this.env = env;\n this.db = env.DB;\n this.config = {\n emailTablePrefix: config.emailTablePrefix || config.tableNamePrefix || 'system_email_',\n defaults: config.defaults || {\n fromName: 'System',\n fromAddress: 'noreply@example.com',\n provider: 'mailchannels'\n },\n // Loader function to fetch settings from backend (DB, KV, etc.)\n // Signature: async (profile, tenantId) => SettingsObject\n settingsLoader: config.settingsLoader || null,\n\n // Updater function to save settings to backend\n // Signature: async (profile, tenantId, settings) => void\n settingsUpdater: config.settingsUpdater || null,\n\n // Branding configuration for email templates\n branding: {\n brandName: config.branding?.brandName || 'Your App',\n portalUrl: config.branding?.portalUrl || 'https://app.example.com',\n primaryColor: config.branding?.primaryColor || '#667eea',\n ...config.branding\n },\n ...config\n };\n\n // Cache Auto-detection:\n // If no provider explicitly passed, try to use built-in DO provider if binding exists\n if (!cacheProvider && env.EMAIL_TEMPLATE_CACHE) {\n this.cache = createDOCacheProvider(env.EMAIL_TEMPLATE_CACHE);\n } else {\n this.cache = cacheProvider;\n }\n }\n\n // --- Configuration & Settings ---\n\n /**\n * Load email configuration\n * @param {string} profile - 'system' or 'tenant' (or custom profile string)\n * @param {string} tenantId - Context ID (optional)\n * @returns {Promise<Object>} Email configuration\n */\n async loadSettings(profile = 'system', tenantId = null) {\n // 1. Try cache (now with Read-Through logic in DO)\n if (this.cache && this.cache.getSettings) {\n try {\n const cached = await this.cache.getSettings(profile, tenantId);\n if (cached) return this._normalizeConfig(cached);\n } catch (e) {\n // Ignore cache/rpc errors\n }\n }\n\n let settings = null;\n\n // 2. Use settingsLoader (Custom Worker Logic) if provided\n if (this.config.settingsLoader) {\n try {\n settings = await this.config.settingsLoader(profile, tenantId);\n } catch (e) {\n console.warn('[EmailService] settingsLoader failed:', e);\n }\n }\n\n // Note: The \"Magical D1 Fallback\" for system settings has been moved \n // INSIDE the EmailTemplateCacheDO (fetchSettingsFromD1).\n // If the DO failed to find it (or is missing), we fall back to generic defaults below.\n\n if (settings) {\n // 3. Populate Cache (Write-Back for custom loaded settings)\n if (this.cache && this.cache.putSettings) {\n try {\n this.cache.putSettings(profile, tenantId, settings);\n } catch (e) { /* ignore */ }\n }\n return this._normalizeConfig(settings);\n }\n\n // 4. Fallback to defaults\n return {\n ...this.config.defaults,\n };\n }\n\n /**\n * Normalize config keys to standard format\n * Handles both snake_case (DB) and camelCase inputs\n */\n _normalizeConfig(config) {\n return {\n provider: config.email_provider || config.provider || this.config.defaults.provider,\n fromAddress: config.email_from_address || config.fromAddress || this.config.defaults.fromAddress,\n fromName: config.email_from_name || config.fromName || this.config.defaults.fromName,\n\n // Provider-specific settings (normalize DB keys to service keys)\n sendgridApiKey: config.sendgrid_api_key || config.sendgridApiKey,\n resendApiKey: config.resend_api_key || config.resendApiKey,\n sendpulseClientId: config.sendpulse_client_id || config.sendpulseClientId,\n sendpulseClientSecret: config.sendpulse_client_secret || config.sendpulseClientSecret,\n\n // SMTP\n smtpHost: config.smtp_host || config.smtpHost,\n smtpPort: config.smtp_port || config.smtpPort,\n smtpUsername: config.smtp_username || config.smtpUsername,\n smtpPassword: config.smtp_password || config.smtpPassword,\n\n // Tracking\n trackingUrl: config.tracking_url || config.trackingUrl,\n\n // Pass through others\n // Pass through others\n ...config,\n smtpSecure: config.smtp_secure === 'true',\n };\n }\n\n // --- Template Management ---\n\n async getTemplate(templateId) {\n // Try cache first\n if (this.cache) {\n try {\n const cached = await this.cache.getTemplate(templateId);\n if (cached) return cached;\n } catch (e) {\n console.warn('[EmailService] Template cache lookup failed:', e);\n }\n }\n\n const table = `${this.config.emailTablePrefix}templates`;\n return await this.db.prepare(`SELECT * FROM ${table} WHERE template_id = ?`)\n .bind(templateId)\n .first();\n }\n\n async getAllTemplates() {\n const table = `${this.config.emailTablePrefix}templates`;\n const result = await this.db.prepare(`SELECT * FROM ${table} ORDER BY template_name`).all();\n return result.results || [];\n }\n\n /**\n * Save email configuration\n * @param {Object} settings - Config object\n * @param {string} profile - 'system' or 'tenant'\n * @param {string} tenantId - Context ID\n */\n async saveSettings(settings, profile = 'system', tenantId = null) {\n // 1. Convert to DB format if needed (not implemented here, assumes settingsUpdater handles it)\n\n // 2. Use settingsUpdater if provided (Write-Aside)\n if (this.config.settingsUpdater) {\n try {\n await this.config.settingsUpdater(profile, tenantId, settings);\n } catch (e) {\n console.error('[EmailService] settingsUpdater failed:', e);\n throw e;\n }\n }\n // 3. Helper for saving to D1 (if no updater, legacy/default tables)\n else if (profile === 'system' && this.db) {\n // NOTE: We could implement a default D1 upsert here similar to the DO fallback,\n // but for writing it's safer to rely on explicit updaters or the DO write-through if implemented.\n // Currently DO supports write-through for 'system' keys.\n }\n\n // 4. Update Cache (Write-Invalidate)\n if (this.cache && this.cache.invalidateSettings) {\n try {\n await this.cache.invalidateSettings(profile, tenantId);\n } catch (e) {\n console.warn('[EmailService] Failed to invalidate settings cache:', e);\n }\n }\n }\n\n async saveTemplate(template, userId = 'system') {\n const table = `${this.config.emailTablePrefix}templates`;\n const now = Math.floor(Date.now() / 1000);\n const existing = await this.getTemplate(template.template_id);\n\n if (existing) {\n await this.db.prepare(`\n UPDATE ${table} SET \n template_name = ?, template_type = ?, subject_template = ?, \n body_markdown = ?, variables = ?, description = ?, is_active = ?, \n updated_at = ?, updated_by = ?\n WHERE template_id = ?\n `).bind(\n template.template_name, template.template_type, template.subject_template,\n template.body_markdown, template.variables, template.description,\n template.is_active, now, userId, template.template_id\n ).run();\n } else {\n await this.db.prepare(`\n INSERT INTO ${table} (\n template_id, template_name, template_type, subject_template,\n body_markdown, variables, description, is_active, created_at, updated_at, updated_by\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `).bind(\n template.template_id, template.template_name, template.template_type,\n template.subject_template, template.body_markdown, template.variables || '[]',\n template.description, template.is_active || 1, now, now, userId\n ).run();\n }\n\n // Invalidate cache if exists\n if (this.cache) {\n await this.cache.putTemplate(template);\n }\n }\n\n async deleteTemplate(templateId) {\n const table = `${this.config.emailTablePrefix}templates`;\n await this.db.prepare(`DELETE FROM ${table} WHERE template_id = ?`).bind(templateId).run();\n if (this.cache) {\n await this.cache.deleteTemplate(templateId);\n }\n }\n\n // --- Rendering ---\n\n async renderTemplate(templateId, data) {\n const template = await this.getTemplate(templateId);\n if (!template) throw new Error(`Template not found: ${templateId}`);\n\n // Render Subject\n const subject = Mustache.render(template.subject_template, data);\n\n // Render Body (Markdown -> HTML)\n let markdown = Mustache.render(template.body_markdown, data);\n\n // Normalize escaped newlines from DB storage to actual newlines\n markdown = markdown.replace(/\\\\n/g, '\\n');\n\n // Configure marked for email-friendly output\n marked.use({\n mangle: false,\n headerIds: false,\n breaks: true // Convert single line breaks to <br>\n });\n const htmlContent = marked.parse(markdown);\n\n // Wrap in Base Template (could be another template or hardcoded default)\n const html = this.wrapInBaseTemplate(htmlContent, subject, data);\n const plainText = markdown.replace(/<[^>]*>/g, ''); // Simple strip\n\n return { subject, html, plainText };\n }\n\n wrapInBaseTemplate(content, subject, data = {}) {\n // Merge branding config with template data\n const templateData = {\n ...data,\n brandName: data.brandName || this.config.branding.brandName,\n portalUrl: data.portalUrl || this.config.branding.portalUrl,\n unsubscribeUrl: data.unsubscribeUrl || '{{unsubscribe_url}}'\n };\n\n // Use the full branded HTML wrapper from common\n return wrapInEmailTemplate(content, subject, templateData);\n }\n\n // --- Delivery ---\n\n /**\n * Send a single email\n * @param {Object} params - Email parameters\n * @param {string} params.to - Recipient email\n * @param {string} params.subject - Email subject\n * @param {string} params.html - HTML body\n * @param {string} params.text - Plain text body\n * @param {string} [params.provider] - Override provider\n * @param {string} [params.profile='system'] - 'system' or 'tenant'\n * @param {string} [params.tenantId] - Required if profile is 'tenant'\n * @param {Object} [params.metadata] - Additional metadata\n * @returns {Promise<Object>} Delivery result\n */\n async sendEmail({ to, subject, html, htmlBody, text, textBody, provider, profile = 'system', tenantId = null, metadata = {} }) {\n // Backward compatibility: accept htmlBody/textBody as aliases\n const htmlContent = html || htmlBody;\n const textContent = text || textBody;\n\n try {\n const settings = await this.loadSettings(profile, tenantId);\n const useProvider = provider || settings.provider || 'mailchannels';\n\n let result;\n\n switch (useProvider) {\n case 'mailchannels':\n result = await this.sendViaMailChannels(to, subject, htmlContent, textContent, settings, metadata);\n break;\n case 'sendgrid':\n result = await this.sendViaSendGrid(to, subject, htmlContent, textContent, settings, metadata);\n break;\n case 'resend':\n result = await this.sendViaResend(to, subject, htmlContent, textContent, settings, metadata);\n break;\n case 'sendpulse':\n result = await this.sendViaSendPulse(to, subject, htmlContent, textContent, settings, metadata);\n break;\n default:\n console.error(`[EmailService] Unknown provider: ${useProvider}`);\n return { success: false, error: `Unknown email provider: ${useProvider}` };\n }\n\n if (result) {\n return { success: true, messageId: crypto.randomUUID() };\n } else {\n console.error('[EmailService] Failed to send email to:', to);\n return { success: false, error: 'Failed to send email' };\n }\n } catch (error) {\n console.error('[EmailService] Error sending email:', error);\n return { success: false, error: error.message };\n }\n }\n\n /**\n * Send multiple emails in batch\n * @param {Array} emails - Array of email objects\n * @returns {Promise<Array>} Array of delivery results\n */\n async sendBatch(emails) {\n console.log('[EmailService] Sending batch of', emails.length, 'emails');\n const results = await Promise.all(\n emails.map(email => this.sendEmail(email))\n );\n return results;\n }\n\n /**\n * Send email via MailChannels HTTP API\n * MailChannels is specifically designed for Cloudflare Workers\n */\n async sendViaMailChannels(to, subject, html, text, settings, metadata) {\n try {\n const response = await fetch('https://api.mailchannels.net/tx/v1/send', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n personalizations: [{ to: [{ email: to, name: metadata.recipientName || '' }] }],\n from: { email: settings.fromAddress, name: settings.fromName },\n subject,\n content: [\n { type: 'text/plain', value: text || html.replace(/<[^>]*>/g, '') },\n { type: 'text/html', value: html }\n ]\n })\n });\n\n if (response.status === 202) {\n return true;\n } else {\n const contentType = response.headers.get('content-type');\n const errorBody = contentType?.includes('application/json')\n ? await response.json()\n : await response.text();\n console.error('[EmailService] MailChannels error:', response.status, errorBody);\n return false;\n }\n } catch (error) {\n console.error('[EmailService] MailChannels exception:', error.message);\n return false;\n }\n }\n\n /**\n * Send email via SendGrid HTTP API\n */\n async sendViaSendGrid(to, subject, html, text, settings, metadata) {\n try {\n if (!settings.sendgridApiKey) {\n console.error('[EmailService] SendGrid API key missing');\n return false;\n }\n\n const response = await fetch('https://api.sendgrid.com/v3/mail/send', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${settings.sendgridApiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n personalizations: [{ to: [{ email: to, name: metadata.recipientName || '' }] }],\n from: { email: settings.fromAddress, name: settings.fromName },\n subject,\n content: [\n { type: 'text/html', value: html },\n { type: 'text/plain', value: text || html.replace(/<[^>]*>/g, '') },\n ],\n }),\n });\n\n if (response.status === 202) {\n return true;\n } else {\n const errorText = await response.text();\n console.error('[EmailService] SendGrid error:', response.status, errorText);\n return false;\n }\n } catch (error) {\n console.error('[EmailService] SendGrid exception:', error.message);\n return false;\n }\n }\n\n /**\n * Send email via Resend HTTP API\n */\n async sendViaResend(to, subject, html, text, settings, metadata) {\n try {\n if (!settings.resendApiKey) {\n console.error('[EmailService] Resend API key missing');\n return false;\n }\n\n const response = await fetch('https://api.resend.com/emails', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${settings.resendApiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n from: `${settings.fromName} <${settings.fromAddress}>`,\n to: [to],\n subject,\n html,\n text: text || html.replace(/<[^>]*>/g, ''),\n }),\n });\n\n if (response.ok) {\n return true;\n } else {\n const errorText = await response.text();\n console.error('[EmailService] Resend error:', response.status, errorText);\n return false;\n }\n } catch (error) {\n console.error('[EmailService] Resend exception:', error.message);\n return false;\n }\n }\n\n /**\n * Send email via SendPulse HTTP API\n * SendPulse offers 15,000 free emails/month\n */\n async sendViaSendPulse(to, subject, html, text, settings, metadata) {\n try {\n if (!settings.sendpulseClientId || !settings.sendpulseClientSecret) {\n console.error('[EmailService] SendPulse credentials missing');\n return false;\n }\n\n // SendPulse uses OAuth2 token-based authentication\n const tokenParams = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: settings.sendpulseClientId,\n client_secret: settings.sendpulseClientSecret,\n });\n\n const tokenResponse = await fetch('https://api.sendpulse.com/oauth/access_token', {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: tokenParams.toString(),\n });\n\n if (!tokenResponse.ok) {\n const error = await tokenResponse.text();\n console.error('[EmailService] SendPulse auth error:', error);\n return false;\n }\n\n const tokenData = await tokenResponse.json();\n if (!tokenData.access_token) {\n console.error('[EmailService] SendPulse: No access token in response');\n return false;\n }\n\n const { access_token } = tokenData;\n\n // Safe base64 encoding\n const toBase64 = (str) => {\n if (!str) return '';\n try {\n return btoa(unescape(encodeURIComponent(String(str))));\n } catch (e) {\n console.error('[EmailService] Base64 encoding failed:', e);\n return '';\n }\n };\n\n // Ensure html/text are strings\n const htmlSafe = html || '';\n const textSafe = text || (htmlSafe ? htmlSafe.replace(/<[^>]*>/g, '') : '');\n\n // Send the email\n const response = await fetch('https://api.sendpulse.com/smtp/emails', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${access_token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n email: {\n html: toBase64(htmlSafe),\n text: toBase64(textSafe),\n subject,\n from: { name: settings.fromName, email: settings.fromAddress },\n to: [{ name: metadata.recipientName || '', email: to }],\n },\n }),\n });\n\n if (response.ok) {\n return true;\n } else {\n const errorText = await response.text();\n console.error('[EmailService] SendPulse send error:', response.status, errorText);\n return false;\n }\n } catch (error) {\n console.error('[EmailService] SendPulse exception:', error.message);\n return false;\n }\n }\n}\n\n","/**\n * HTML Email Wrapper\n * Full styled HTML template for wrapping email content\n */\n\n/**\n * Wrap content HTML in email template with styling\n * @param {string} contentHtml - The HTML content to wrap\n * @param {string} subject - Email subject for the title\n * @param {Object} data - Template data (portalUrl, unsubscribeUrl, etc.)\n * @returns {string} Complete HTML email\n */\nexport function wrapInEmailTemplate(contentHtml, subject, data = {}) {\n const portalUrl = data.portalUrl || 'https://app.x0start.com';\n const unsubscribeUrl = data.unsubscribeUrl || '{{unsubscribe_url}}';\n const brandName = data.brandName || 'X0 Start';\n\n return `\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${subject}</title>\n <style>\n body {\n margin: 0;\n padding: 0;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n background-color: #f5f5f5;\n line-height: 1.6;\n }\n .email-wrapper {\n background-color: #f5f5f5;\n padding: 40px 20px;\n }\n .email-container {\n max-width: 600px;\n margin: 0 auto;\n background-color: #ffffff;\n border-radius: 8px;\n overflow: hidden;\n box-shadow: 0 2px 8px rgba(0,0,0,0.1);\n }\n .email-header {\n padding: 40px 40px 20px;\n text-align: center;\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: #ffffff;\n }\n .email-header h1 {\n margin: 0;\n font-size: 28px;\n font-weight: 600;\n }\n .email-content {\n padding: 30px 40px;\n color: #333333;\n }\n .email-content h1 {\n font-size: 24px;\n margin-top: 0;\n margin-bottom: 20px;\n color: #333333;\n }\n .email-content h2 {\n font-size: 20px;\n margin-top: 30px;\n margin-bottom: 15px;\n color: #333333;\n }\n .email-content h3 {\n font-size: 16px;\n margin-top: 20px;\n margin-bottom: 10px;\n color: #333333;\n }\n .email-content p {\n margin: 0 0 15px;\n color: #666666;\n }\n .email-content a {\n color: #667eea;\n text-decoration: none;\n }\n .email-content ul, .email-content ol {\n margin: 0 0 15px;\n padding-left: 25px;\n }\n .email-content li {\n margin-bottom: 8px;\n color: #666666;\n }\n .email-content blockquote {\n margin: 20px 0;\n padding: 15px 20px;\n background-color: #f8f9fa;\n border-left: 4px solid #667eea;\n color: #666666;\n }\n .email-content code {\n padding: 2px 6px;\n background-color: #f8f9fa;\n border-radius: 3px;\n font-family: 'Courier New', monospace;\n font-size: 14px;\n }\n .email-content pre {\n padding: 15px;\n background-color: #f8f9fa;\n border-radius: 6px;\n overflow-x: auto;\n }\n .email-content pre code {\n padding: 0;\n background: none;\n }\n .btn {\n display: inline-block;\n padding: 12px 24px;\n background-color: #667eea;\n color: #ffffff !important;\n text-decoration: none;\n border-radius: 6px;\n font-weight: 600;\n margin: 10px 0;\n }\n .btn:hover {\n background-color: #5568d3;\n }\n .email-footer {\n padding: 20px 40px;\n background-color: #f8f9fa;\n text-align: center;\n font-size: 12px;\n color: #666666;\n }\n .email-footer a {\n color: #667eea;\n text-decoration: none;\n }\n hr {\n border: none;\n border-top: 1px solid #e0e0e0;\n margin: 30px 0;\n }\n </style>\n</head>\n<body>\n <div class=\"email-wrapper\">\n <div class=\"email-container\">\n <div class=\"email-content\">\n ${contentHtml}\n </div>\n <div class=\"email-footer\">\n <p style=\"margin: 0 0 10px;\">\n You're receiving this email from ${brandName}.\n </p>\n <p style=\"margin: 0;\">\n <a href=\"${unsubscribeUrl}\">Unsubscribe</a> | \n <a href=\"${portalUrl}/settings/notifications\">Manage Preferences</a>\n </p>\n </div>\n </div>\n </div>\n</body>\n</html>\n `.trim();\n}\n","/**\n * EmailingCacheDO - Optional read-through cache for email templates and settings\n * \n * This is a Cloudflare Durable Object that provides caching for email templates and settings.\n * \n * Configurable via environment variable:\n * - EMAIL_TABLE_PREFIX: Prefix for tables (default: 'system_email_')\n */\nexport class EmailingCacheDO {\n constructor(state, env) {\n this.state = state;\n this.env = env;\n this.cache = new Map(); // templateId -> { data, timestamp }\n this.settingsCache = new Map(); // key -> { data, timestamp }\n this.cacheTTL = 3600000; // 1 hour in milliseconds\n // Templates use the prefix\n this.emailTablePrefix = env.EMAIL_TABLE_PREFIX || 'system_email_';\n // Settings use a specific table name (defaulting to system_settings)\n // This allows decoupling template prefix from settings table\n this.settingsTableName = env.EMAIL_SETTINGS_TABLE || 'system_settings';\n\n // Optional: Filter settings by key prefix (e.g. 'email_')\n // This allows sharing the system_settings table with other apps\n this.settingsKeyPrefix = env.EMAIL_SETTINGS_KEY_PREFIX || '';\n }\n\n /**\n * Handle HTTP requests to this Durable Object\n */\n async fetch(request) {\n const url = new URL(request.url);\n const path = url.pathname;\n\n try {\n if (path === '/get' && request.method === 'GET') {\n return this.handleGet(request);\n } else if (path === '/invalidate' && request.method === 'POST') {\n return this.handleInvalidate(request);\n } else if (path === '/clear' && request.method === 'POST') {\n return this.handleClear(request);\n } else if (path === '/stats' && request.method === 'GET') {\n return this.handleStats(request);\n }\n // Settings endpoints\n else if (path === '/settings/get' && request.method === 'GET') {\n return this.handleGetSettings(request);\n } else if (path === '/settings/put' && request.method === 'POST') {\n return this.handlePutSettings(request);\n } else if (path === '/settings/invalidate' && request.method === 'POST') {\n return this.handleInvalidateSettings(request);\n } else {\n return new Response('Not Found', { status: 404 });\n }\n } catch (error) {\n console.error('[EmailingCacheDO] Error:', error);\n return new Response(JSON.stringify({ error: error.message }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n\n /**\n * Get template (from cache or D1)\n */\n async handleGet(request) {\n const url = new URL(request.url);\n const templateId = url.searchParams.get('templateId');\n const forceRefresh = url.searchParams.get('refresh') === 'true';\n\n if (!templateId) {\n return new Response(JSON.stringify({ error: 'templateId is required' }), {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Check cache (unless force refresh)\n if (!forceRefresh) {\n const cached = this.cache.get(templateId);\n if (cached && Date.now() - cached.timestamp < this.cacheTTL) {\n console.log('[EmailingCacheDO] Cache HIT:', templateId);\n return new Response(JSON.stringify({\n template: cached.data,\n cached: true,\n age: Date.now() - cached.timestamp,\n }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n\n // Cache miss or expired - fetch from D1\n console.log('[EmailingCacheDO] Cache MISS - fetching from D1:', templateId);\n const template = await this.fetchTemplateFromD1(templateId);\n\n if (!template) {\n return new Response(JSON.stringify({\n error: 'Template not found',\n templateId\n }), {\n status: 404,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Cache the result\n this.cache.set(templateId, {\n data: template,\n timestamp: Date.now(),\n });\n\n return new Response(JSON.stringify({\n template,\n cached: false,\n }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // --- Settings Cache Handlers ---\n\n async handleGetSettings(request) {\n const url = new URL(request.url);\n const key = url.searchParams.get('key');\n\n if (!key) return new Response('Key required', { status: 400 });\n\n // Check Cache\n const cached = this.settingsCache.get(key);\n if (cached && Date.now() - cached.timestamp < this.cacheTTL) {\n console.log('[EmailingCacheDO] Settings Cache HIT:', key);\n return new Response(JSON.stringify({ settings: cached.data }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Cache Miss - Fetch from D1 (Read-Through)\n // Only fetch from D1 for system settings (consistent with handlePutSettings)\n if (key.startsWith('system')) {\n console.log('[EmailingCacheDO] Settings Cache MISS - fetching from D1:', key);\n const settings = await this.fetchSettingsFromD1(key);\n\n // Even if null, we might want to cache the \"null\" result to prevent hammer? \n // For now, only cache if we found something or explicitly handle negative caching.\n if (settings) {\n this.settingsCache.set(key, {\n data: settings,\n timestamp: Date.now()\n });\n return new Response(JSON.stringify({ settings }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n\n return new Response(JSON.stringify({ settings: null }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n async handlePutSettings(request) {\n try {\n const body = await request.json();\n const { key, settings } = body;\n\n if (!key || !settings) return new Response('Key and settings required', { status: 400 });\n\n // Write to Cache\n this.settingsCache.set(key, {\n data: settings,\n timestamp: Date.now()\n });\n\n // Write to D1 (Write-Through)\n // Note: only supports writing to \"system\" (default table) currently\n if (key.startsWith('system')) {\n await this.saveSettingsToD1(settings);\n }\n\n return new Response(JSON.stringify({ success: true }), {\n headers: { 'Content-Type': 'application/json' },\n });\n } catch (e) {\n console.error('[EmailingCacheDO] PutSettings error:', e);\n return new Response('Error parsing body/saving', { status: 400 });\n }\n }\n\n async handleInvalidateSettings(request) {\n try {\n const body = await request.json();\n const { key } = body;\n\n if (!key) return new Response('Key required', { status: 400 });\n\n const existed = this.settingsCache.has(key);\n this.settingsCache.delete(key);\n console.log('[EmailingCacheDO] Invalidated settings:', key, existed ? '(existed)' : '(not in cache)');\n\n return new Response(JSON.stringify({ success: true, existed }), {\n headers: { 'Content-Type': 'application/json' },\n });\n } catch (e) {\n console.error('[EmailingCacheDO] InvalidateSettings error:', e);\n return new Response('Error invalidated settings', { status: 400 });\n }\n }\n\n /**\n * Invalidate specific template(s) from cache\n * Body: { templateId: 'template_id' } or { templateId: '*' } for all\n */\n async handleInvalidate(request) {\n const body = await request.json();\n const { templateId } = body;\n\n if (!templateId) {\n return new Response(JSON.stringify({ error: 'templateId is required' }), {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n if (templateId === '*') {\n // Invalidate all templates\n const count = this.cache.size;\n this.cache.clear();\n console.log('[EmailingCacheDO] Invalidated ALL templates:', count);\n return new Response(JSON.stringify({\n success: true,\n message: `Invalidated ${count} templates`,\n }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Invalidate specific template\n const existed = this.cache.has(templateId);\n this.cache.delete(templateId);\n console.log('[EmailingCacheDO] Invalidated template:', templateId, existed ? '(existed)' : '(not in cache)');\n\n return new Response(JSON.stringify({\n success: true,\n message: existed ? 'Template invalidated' : 'Template was not in cache',\n templateId,\n }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n /**\n * Clear entire cache (admin operation)\n */\n async handleClear(request) {\n const count = this.cache.size + this.settingsCache.size;\n this.cache.clear();\n this.settingsCache.clear();\n console.log('[EmailingCacheDO] Cache cleared:', count, 'entries (templates + settings)');\n\n return new Response(JSON.stringify({\n success: true,\n message: `Cleared ${count} cached items`,\n }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n /**\n * Get cache statistics\n */\n async handleStats(request) {\n const stats = {\n templates: this.cache.size,\n settings: this.settingsCache.size,\n cacheTTL: this.cacheTTL,\n };\n\n return new Response(JSON.stringify(stats), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n /**\n * Fetch template from D1\n */\n async fetchTemplateFromD1(templateId) {\n const db = this.env.DB;\n const tableName = `${this.emailTablePrefix}templates`;\n\n try {\n const template = await db\n .prepare(`SELECT * FROM ${tableName} WHERE template_id = ? AND is_active = 1`)\n .bind(templateId)\n .first();\n return template;\n } catch (e) {\n console.error(`[EmailingCacheDO] DB Error (${tableName}):`, e);\n return null;\n }\n }\n\n /**\n * Fetch settings from D1\n * Only supports default table (e.g. system_settings) for now\n */\n async fetchSettingsFromD1(key) {\n const db = this.env.DB;\n const tableName = this.settingsTableName;\n const prefix = this.settingsKeyPrefix;\n\n try {\n let results;\n\n if (prefix) {\n // Filter by prefix (e.g. WHERE setting_key LIKE 'email_%')\n // Note: We need to handle both schema variants (setting_key vs key)\n // BUT standard D1 SQL doesn't support \"OR\" in column names easily with LIKE parameter binding\n // for flexible schemas.\n // We will assume 'setting_key' matches if table is system_settings, or try both.\n\n // Construct query dynamically based on likely schema or just try standard first\n try {\n results = await db.prepare(`SELECT * FROM ${tableName} WHERE setting_key LIKE ?`).bind(`${prefix}%`).all();\n } catch (e) {\n // Fallback to 'key' column\n results = await db.prepare(`SELECT * FROM ${tableName} WHERE key LIKE ?`).bind(`${prefix}%`).all();\n }\n } else {\n // No prefix, fetch all\n results = await db.prepare(`SELECT * FROM ${tableName}`).all();\n }\n\n if (!results.results || results.results.length === 0) return null;\n\n const settings = {};\n results.results.forEach(row => {\n const k = row.setting_key || row.key;\n const v = row.setting_value || row.value;\n if (k) settings[k] = v;\n });\n return settings;\n } catch (e) {\n console.warn(`[EmailingCacheDO] Failed to load settings from ${tableName}:`, e);\n return null;\n }\n }\n\n async saveSettingsToD1(settings) {\n const db = this.env.DB;\n const tableName = this.settingsTableName;\n\n // Simple upset not easy in D1 without specific keys.\n // We'll rely on calling code/migration. \n // For now, let's just log or try to update if possible.\n // Actually, writing settings is complex because we don't know the schema perfectly.\n // Let's implement a BEST EFFORT update for x0start schema\n\n const entries = Object.entries(settings);\n for (const [k, v] of entries) {\n try {\n // Heuristic: Try to determine column names based on common conventions\n // We'll try Schema 1 (setting_key/value) first as it's the default internal convention\n // If that fails, we might fall back to Schema 2 (key/value) in a real implementation\n // For now, let's try a best-effort upsert based on x0start schema or generic\n\n try {\n const res = await db.prepare(`UPDATE ${tableName} SET setting_value = ? WHERE setting_key = ?`).bind(v, k).run();\n if (res.meta.changes === 0) {\n await db.prepare(`INSERT INTO ${tableName} (setting_key, setting_value) VALUES (?, ?)`).bind(k, v).run();\n }\n } catch (e) {\n // Fallback to key/value\n await db.prepare(`INSERT OR REPLACE INTO ${tableName} (key, value) VALUES (?, ?)`).bind(k, v).run();\n }\n } catch (e) {\n console.warn('[EmailingCacheDO] Failed to save setting to D1:', k);\n }\n }\n }\n}\n\n/**\n * Create a cache provider wrapper for the DO\n */\nexport function createDOCacheProvider(doStub, instanceName = 'global') {\n if (!doStub) {\n return null;\n }\n\n const stub = doStub.get(doStub.idFromName(instanceName));\n\n return {\n async getTemplate(templateId) {\n try {\n const response = await stub.fetch(`http://do/get?templateId=${templateId}`);\n const data = await response.json();\n return data.template || null;\n } catch (e) {\n // Silently fall back to DB - DO cache is optional\n return null;\n }\n },\n\n async getSettings(profile, tenantId) {\n const key = `${profile}:${tenantId || ''}`;\n try {\n const response = await stub.fetch(`http://do/settings/get?key=${encodeURIComponent(key)}`);\n const data = await response.json();\n return data.settings || null;\n } catch (e) {\n return null;\n }\n },\n\n async putSettings(profile, tenantId, settings) {\n const key = `${profile}:${tenantId || ''}`;\n try {\n await stub.fetch('http://do/settings/put', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ key, settings }),\n });\n } catch (e) {\n console.warn('[DOCacheProvider] Failed to cache settings:', e);\n }\n },\n\n async putTemplate(template) {\n try {\n await stub.fetch('http://do/invalidate', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ templateId: template.template_id }),\n });\n } catch (e) {\n console.warn('[DOCacheProvider] Failed to invalidate template:', e);\n }\n },\n\n async deleteTemplate(templateId) {\n try {\n await stub.fetch('http://do/invalidate', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ templateId }),\n });\n } catch (e) {\n console.warn('[DOCacheProvider] Failed to invalidate template:', e);\n }\n },\n\n async invalidateSettings(profile, tenantId) {\n const key = `${profile}:${tenantId || ''}`;\n try {\n await stub.fetch('http://do/settings/invalidate', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ key }),\n });\n } catch (e) {\n console.warn('[DOCacheProvider] Failed to invalidate settings:', e);\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,oBAAuB;AACvB,sBAAqB;;;ACOd,SAAS,oBAAoB,aAAa,SAAS,OAAO,CAAC,GAAG;AACjE,QAAM,YAAY,KAAK,aAAa;AACpC,QAAM,iBAAiB,KAAK,kBAAkB;AAC9C,QAAM,YAAY,KAAK,aAAa;AAEpC,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAMA,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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M,SAAS,iBAAiB,IAAI,OAAO,GAAG,CAAC;AAAA,UAC1D;AAAA,QACJ,CAAC;AAAA,MACL,CAAC;AAED,UAAI,SAAS,IAAI;AACb,eAAO;AAAA,MACX,OAAO;AACH,cAAM,YAAY,MAAM,SAAS,KAAK;AACtC,gBAAQ,MAAM,wCAAwC,SAAS,QAAQ,SAAS;AAChF,eAAO;AAAA,MACX;AAAA,IACJ,SAAS,OAAO;AACZ,cAAQ,MAAM,uCAAuC,MAAM,OAAO;AAClE,aAAO;AAAA,IACX;AAAA,EACJ;AACJ;","names":["Mustache"]}
|
|
1
|
+
{"version":3,"sources":["../../src/backend/EmailService.js","../../src/common/htmlWrapper.js","../../src/backend/EmailingCacheDO.js"],"sourcesContent":["/**\n * Email Service\n * Unified service for email delivery and template management.\n */\nimport { marked } from 'marked';\nimport Mustache from 'mustache';\nimport { wrapInEmailTemplate } from '../common/htmlWrapper.js';\nimport { createDOCacheProvider } from './EmailingCacheDO.js';\n\nexport class EmailService {\n /**\n * @param {Object} env - Cloudflare environment bindings (DB, etc.)\n * @param {Object} config - Configuration options\n * @param {string} [config.emailTablePrefix='system_email_'] - Prefix for D1 tables\n * @param {Object} [config.defaults] - Default settings (fromName, fromAddress)\n * @param {Object} [cacheProvider] - Optional cache interface (DO stub or KV wrapper)\n */\n constructor(env, config = {}, cacheProvider = null) {\n this.env = env;\n this.db = env.DB;\n this.config = {\n emailTablePrefix: config.emailTablePrefix || config.tableNamePrefix || 'system_email_',\n defaults: config.defaults || {\n fromName: 'System',\n fromAddress: 'noreply@example.com',\n provider: 'mailchannels'\n },\n // Loader function to fetch settings from backend (DB, KV, etc.)\n // Signature: async (profile, tenantId) => SettingsObject\n settingsLoader: config.settingsLoader || null,\n\n // Updater function to save settings to backend\n // Signature: async (profile, tenantId, settings) => void\n settingsUpdater: config.settingsUpdater || null,\n\n // Branding configuration for email templates\n branding: {\n brandName: config.branding?.brandName || 'Your App',\n portalUrl: config.branding?.portalUrl || 'https://app.example.com',\n primaryColor: config.branding?.primaryColor || '#667eea',\n ...config.branding\n },\n ...config\n };\n\n // Cache Auto-detection:\n // If no provider explicitly passed, try to use built-in DO provider if binding exists\n if (!cacheProvider && env.EMAIL_TEMPLATE_CACHE) {\n this.cache = createDOCacheProvider(env.EMAIL_TEMPLATE_CACHE);\n } else {\n this.cache = cacheProvider;\n }\n }\n\n // --- Configuration & Settings ---\n\n /**\n * Load email configuration\n * @param {string} profile - 'system' or 'tenant' (or custom profile string)\n * @param {string} tenantId - Context ID (optional)\n * @returns {Promise<Object>} Email configuration\n */\n async loadSettings(profile = 'system', tenantId = null) {\n // 1. Try cache (now with Read-Through logic in DO)\n if (this.cache && this.cache.getSettings) {\n try {\n const cached = await this.cache.getSettings(profile, tenantId);\n if (cached) return this._normalizeConfig(cached);\n } catch (e) {\n // Ignore cache/rpc errors\n }\n }\n\n let settings = null;\n\n // 2. Use settingsLoader (Custom Worker Logic) if provided\n if (this.config.settingsLoader) {\n try {\n settings = await this.config.settingsLoader(profile, tenantId);\n } catch (e) {\n console.warn('[EmailService] settingsLoader failed:', e);\n }\n }\n\n // Note: The \"Magical D1 Fallback\" for system settings has been moved \n // INSIDE the EmailTemplateCacheDO (fetchSettingsFromD1).\n // If the DO failed to find it (or is missing), we fall back to generic defaults below.\n\n if (settings) {\n // 3. Populate Cache (Write-Back for custom loaded settings)\n if (this.cache && this.cache.putSettings) {\n try {\n this.cache.putSettings(profile, tenantId, settings);\n } catch (e) { /* ignore */ }\n }\n return this._normalizeConfig(settings);\n }\n\n // 4. Fallback to defaults\n return {\n ...this.config.defaults,\n };\n }\n\n /**\n * Normalize config keys to standard format\n * Handles both snake_case (DB) and camelCase inputs\n */\n _normalizeConfig(config) {\n return {\n provider: config.email_provider || config.provider || this.config.defaults.provider,\n fromAddress: config.email_from_address || config.fromAddress || this.config.defaults.fromAddress,\n fromName: config.email_from_name || config.fromName || this.config.defaults.fromName,\n\n // Provider-specific settings (normalize DB keys to service keys)\n sendgridApiKey: config.sendgrid_api_key || config.sendgridApiKey,\n resendApiKey: config.resend_api_key || config.resendApiKey,\n sendpulseClientId: config.sendpulse_client_id || config.sendpulseClientId,\n sendpulseClientSecret: config.sendpulse_client_secret || config.sendpulseClientSecret,\n\n // SMTP\n smtpHost: config.smtp_host || config.smtpHost,\n smtpPort: config.smtp_port || config.smtpPort,\n smtpUsername: config.smtp_username || config.smtpUsername,\n smtpPassword: config.smtp_password || config.smtpPassword,\n\n // Tracking\n trackingUrl: config.tracking_url || config.trackingUrl,\n\n // Pass through others\n // Pass through others\n ...config,\n smtpSecure: config.smtp_secure === 'true',\n };\n }\n\n // --- Template Management ---\n\n async getTemplate(templateId) {\n // Try cache first\n if (this.cache) {\n try {\n const cached = await this.cache.getTemplate(templateId);\n if (cached) return cached;\n } catch (e) {\n console.warn('[EmailService] Template cache lookup failed:', e);\n }\n }\n\n const table = `${this.config.emailTablePrefix}templates`;\n return await this.db.prepare(`SELECT * FROM ${table} WHERE template_id = ?`)\n .bind(templateId)\n .first();\n }\n\n async getAllTemplates() {\n const table = `${this.config.emailTablePrefix}templates`;\n const result = await this.db.prepare(`SELECT * FROM ${table} ORDER BY template_name`).all();\n return result.results || [];\n }\n\n /**\n * Save email configuration\n * @param {Object} settings - Config object\n * @param {string} profile - 'system' or 'tenant'\n * @param {string} tenantId - Context ID\n */\n async saveSettings(settings, profile = 'system', tenantId = null) {\n // 1. Convert to DB format if needed (not implemented here, assumes settingsUpdater handles it)\n\n // 2. Use settingsUpdater if provided (Write-Aside)\n if (this.config.settingsUpdater) {\n try {\n await this.config.settingsUpdater(profile, tenantId, settings);\n } catch (e) {\n console.error('[EmailService] settingsUpdater failed:', e);\n throw e;\n }\n }\n // 3. Helper for saving to D1 (if no updater, legacy/default tables)\n else if (profile === 'system' && this.db) {\n // NOTE: We could implement a default D1 upsert here similar to the DO fallback,\n // but for writing it's safer to rely on explicit updaters or the DO write-through if implemented.\n // Currently DO supports write-through for 'system' keys.\n }\n\n // 4. Update Cache (Write-Invalidate)\n if (this.cache && this.cache.invalidateSettings) {\n try {\n await this.cache.invalidateSettings(profile, tenantId);\n } catch (e) {\n console.warn('[EmailService] Failed to invalidate settings cache:', e);\n }\n }\n }\n\n async saveTemplate(template, userId = 'system') {\n const table = `${this.config.emailTablePrefix}templates`;\n const now = Math.floor(Date.now() / 1000);\n const existing = await this.getTemplate(template.template_id);\n\n if (existing) {\n await this.db.prepare(`\n UPDATE ${table} SET \n template_name = ?, template_type = ?, subject_template = ?, \n body_markdown = ?, variables = ?, description = ?, is_active = ?, \n updated_at = ?, updated_by = ?\n WHERE template_id = ?\n `).bind(\n template.template_name, template.template_type, template.subject_template,\n template.body_markdown, template.variables, template.description,\n template.is_active, now, userId, template.template_id\n ).run();\n } else {\n await this.db.prepare(`\n INSERT INTO ${table} (\n template_id, template_name, template_type, subject_template,\n body_markdown, variables, description, is_active, created_at, updated_at, updated_by\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `).bind(\n template.template_id, template.template_name, template.template_type,\n template.subject_template, template.body_markdown, template.variables || '[]',\n template.description, template.is_active || 1, now, now, userId\n ).run();\n }\n\n // Invalidate cache if exists\n if (this.cache) {\n await this.cache.putTemplate(template);\n }\n }\n\n async deleteTemplate(templateId) {\n const table = `${this.config.emailTablePrefix}templates`;\n await this.db.prepare(`DELETE FROM ${table} WHERE template_id = ?`).bind(templateId).run();\n if (this.cache) {\n await this.cache.deleteTemplate(templateId);\n }\n }\n\n // --- Rendering ---\n\n /**\n * Pre-process template data to auto-format URLs\n * Scans for strings starting with http:// or https:// and wraps them in Markdown links\n */\n _preprocessData(data) {\n if (!data || typeof data !== 'object') return data;\n\n const processed = { ...data };\n for (const [key, value] of Object.entries(processed)) {\n if (typeof value === 'string' && (value.startsWith('http://') || value.startsWith('https://'))) {\n // Check if it's already a markdown link to avoid double wrapping\n if (!value.trim().startsWith('[') && !value.includes('](')) {\n processed[key] = `[${value}](${value})`;\n }\n }\n }\n return processed;\n }\n\n async renderTemplate(templateId, data) {\n const template = await this.getTemplate(templateId);\n if (!template) throw new Error(`Template not found: ${templateId}`);\n\n // Pre-process data to auto-format links\n const processedData = this._preprocessData(data);\n\n // Render Subject\n const subject = Mustache.render(template.subject_template, processedData);\n\n // Render Body (Markdown -> HTML)\n let markdown = Mustache.render(template.body_markdown, processedData);\n\n // Normalize escaped newlines from DB storage to actual newlines\n markdown = markdown.replace(/\\\\n/g, '\\n');\n\n // Configure marked for email-friendly output\n marked.use({\n mangle: false,\n headerIds: false,\n breaks: true // Convert single line breaks to <br>\n });\n const htmlContent = marked.parse(markdown);\n\n // Wrap in Base Template (could be another template or hardcoded default)\n const html = this.wrapInBaseTemplate(htmlContent, subject, data);\n const plainText = markdown.replace(/<[^>]*>/g, ''); // Simple strip\n\n return { subject, html, plainText };\n }\n\n wrapInBaseTemplate(content, subject, data = {}) {\n // Merge branding config with template data\n const templateData = {\n ...data,\n brandName: data.brandName || this.config.branding.brandName,\n portalUrl: data.portalUrl || this.config.branding.portalUrl,\n unsubscribeUrl: data.unsubscribeUrl || '{{unsubscribe_url}}'\n };\n\n // Use the full branded HTML wrapper from common\n return wrapInEmailTemplate(content, subject, templateData);\n }\n\n // --- Delivery ---\n\n /**\n * Send an email using a template\n * @param {string} templateId - Template ID\n * @param {Object} data - Template variables\n * @param {Object} options - Sending options (to, provider, etc.)\n * @returns {Promise<Object>} Delivery result\n */\n async sendViaTemplate(templateId, data, options) {\n try {\n const { subject, html, plainText } = await this.renderTemplate(templateId, data);\n\n return await this.sendEmail({\n ...options,\n subject, // Can be overridden by options.subject if needed, but usually template subject is preferred\n html,\n text: plainText,\n metadata: {\n ...options.metadata,\n templateId\n }\n });\n } catch (error) {\n console.error(`[EmailService] sendViaTemplate failed for ${templateId}:`, error);\n return { success: false, error: error.message };\n }\n }\n\n /**\n * Send a single email\n * @param {Object} params - Email parameters\n * @param {string} params.to - Recipient email\n * @param {string} params.subject - Email subject\n * @param {string} params.html - HTML body\n * @param {string} params.text - Plain text body\n * @param {string} [params.provider] - Override provider\n * @param {string} [params.profile='system'] - 'system' or 'tenant'\n * @param {string} [params.tenantId] - Required if profile is 'tenant'\n * @param {Object} [params.metadata] - Additional metadata\n * @returns {Promise<Object>} Delivery result\n */\n async sendEmail({ to, subject, html, htmlBody, text, textBody, provider, profile = 'system', tenantId = null, metadata = {} }) {\n // Backward compatibility: accept htmlBody/textBody as aliases\n const htmlContent = html || htmlBody;\n const textContent = text || textBody;\n\n try {\n const settings = await this.loadSettings(profile, tenantId);\n const useProvider = provider || settings.provider || 'mailchannels';\n\n let result;\n\n switch (useProvider) {\n case 'mailchannels':\n result = await this.sendViaMailChannels(to, subject, htmlContent, textContent, settings, metadata);\n break;\n case 'sendgrid':\n result = await this.sendViaSendGrid(to, subject, htmlContent, textContent, settings, metadata);\n break;\n case 'resend':\n result = await this.sendViaResend(to, subject, htmlContent, textContent, settings, metadata);\n break;\n case 'sendpulse':\n result = await this.sendViaSendPulse(to, subject, htmlContent, textContent, settings, metadata);\n break;\n default:\n console.error(`[EmailService] Unknown provider: ${useProvider}`);\n return { success: false, error: `Unknown email provider: ${useProvider}` };\n }\n\n if (result) {\n return { success: true, messageId: crypto.randomUUID() };\n } else {\n console.error('[EmailService] Failed to send email to:', to);\n return { success: false, error: 'Failed to send email' };\n }\n } catch (error) {\n console.error('[EmailService] Error sending email:', error);\n return { success: false, error: error.message };\n }\n }\n\n /**\n * Send multiple emails in batch\n * @param {Array} emails - Array of email objects\n * @returns {Promise<Array>} Array of delivery results\n */\n async sendBatch(emails) {\n console.log('[EmailService] Sending batch of', emails.length, 'emails');\n const results = await Promise.all(\n emails.map(email => this.sendEmail(email))\n );\n return results;\n }\n\n /**\n * Send email via MailChannels HTTP API\n * MailChannels is specifically designed for Cloudflare Workers\n */\n async sendViaMailChannels(to, subject, html, text, settings, metadata) {\n try {\n const response = await fetch('https://api.mailchannels.net/tx/v1/send', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n personalizations: [{ to: [{ email: to, name: metadata.recipientName || '' }] }],\n from: { email: settings.fromAddress, name: settings.fromName },\n subject,\n content: [\n { type: 'text/plain', value: text || html.replace(/<[^>]*>/g, '') },\n { type: 'text/html', value: html }\n ]\n })\n });\n\n if (response.status === 202) {\n return true;\n } else {\n const contentType = response.headers.get('content-type');\n const errorBody = contentType?.includes('application/json')\n ? await response.json()\n : await response.text();\n console.error('[EmailService] MailChannels error:', response.status, errorBody);\n return false;\n }\n } catch (error) {\n console.error('[EmailService] MailChannels exception:', error.message);\n return false;\n }\n }\n\n /**\n * Send email via SendGrid HTTP API\n */\n async sendViaSendGrid(to, subject, html, text, settings, metadata) {\n try {\n if (!settings.sendgridApiKey) {\n console.error('[EmailService] SendGrid API key missing');\n return false;\n }\n\n const response = await fetch('https://api.sendgrid.com/v3/mail/send', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${settings.sendgridApiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n personalizations: [{ to: [{ email: to, name: metadata.recipientName || '' }] }],\n from: { email: settings.fromAddress, name: settings.fromName },\n subject,\n content: [\n { type: 'text/html', value: html },\n { type: 'text/plain', value: text || html.replace(/<[^>]*>/g, '') },\n ],\n }),\n });\n\n if (response.status === 202) {\n return true;\n } else {\n const errorText = await response.text();\n console.error('[EmailService] SendGrid error:', response.status, errorText);\n return false;\n }\n } catch (error) {\n console.error('[EmailService] SendGrid exception:', error.message);\n return false;\n }\n }\n\n /**\n * Send email via Resend HTTP API\n */\n async sendViaResend(to, subject, html, text, settings, metadata) {\n try {\n if (!settings.resendApiKey) {\n console.error('[EmailService] Resend API key missing');\n return false;\n }\n\n const response = await fetch('https://api.resend.com/emails', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${settings.resendApiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n from: `${settings.fromName} <${settings.fromAddress}>`,\n to: [to],\n subject,\n html,\n text: text || html.replace(/<[^>]*>/g, ''),\n }),\n });\n\n if (response.ok) {\n return true;\n } else {\n const errorText = await response.text();\n console.error('[EmailService] Resend error:', response.status, errorText);\n return false;\n }\n } catch (error) {\n console.error('[EmailService] Resend exception:', error.message);\n return false;\n }\n }\n\n /**\n * Send email via SendPulse HTTP API\n * SendPulse offers 15,000 free emails/month\n */\n async sendViaSendPulse(to, subject, html, text, settings, metadata) {\n try {\n if (!settings.sendpulseClientId || !settings.sendpulseClientSecret) {\n console.error('[EmailService] SendPulse credentials missing');\n return false;\n }\n\n // SendPulse uses OAuth2 token-based authentication\n const tokenParams = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: settings.sendpulseClientId,\n client_secret: settings.sendpulseClientSecret,\n });\n\n const tokenResponse = await fetch('https://api.sendpulse.com/oauth/access_token', {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: tokenParams.toString(),\n });\n\n if (!tokenResponse.ok) {\n const error = await tokenResponse.text();\n console.error('[EmailService] SendPulse auth error:', error);\n return false;\n }\n\n const tokenData = await tokenResponse.json();\n if (!tokenData.access_token) {\n console.error('[EmailService] SendPulse: No access token in response');\n return false;\n }\n\n const { access_token } = tokenData;\n\n // Safe base64 encoding\n const toBase64 = (str) => {\n if (!str) return '';\n try {\n return btoa(unescape(encodeURIComponent(String(str))));\n } catch (e) {\n console.error('[EmailService] Base64 encoding failed:', e);\n return '';\n }\n };\n\n // Ensure html/text are strings\n const htmlSafe = html || '';\n const textSafe = text || (htmlSafe ? htmlSafe.replace(/<[^>]*>/g, '') : '');\n\n // Send the email\n const response = await fetch('https://api.sendpulse.com/smtp/emails', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${access_token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n email: {\n html: toBase64(htmlSafe),\n text: toBase64(textSafe),\n subject,\n from: { name: settings.fromName, email: settings.fromAddress },\n to: [{ name: metadata.recipientName || '', email: to }],\n },\n }),\n });\n\n if (response.ok) {\n return true;\n } else {\n const errorText = await response.text();\n console.error('[EmailService] SendPulse send error:', response.status, errorText);\n return false;\n }\n } catch (error) {\n console.error('[EmailService] SendPulse exception:', error.message);\n return false;\n }\n }\n}\n\n","/**\n * HTML Email Wrapper\n * Full styled HTML template for wrapping email content\n */\n\n/**\n * Wrap content HTML in email template with styling\n * @param {string} contentHtml - The HTML content to wrap\n * @param {string} subject - Email subject for the title\n * @param {Object} data - Template data (portalUrl, unsubscribeUrl, etc.)\n * @returns {string} Complete HTML email\n */\nexport function wrapInEmailTemplate(contentHtml, subject, data = {}) {\n const portalUrl = data.portalUrl || 'https://app.x0start.com';\n const unsubscribeUrl = data.unsubscribeUrl || '{{unsubscribe_url}}';\n const brandName = data.brandName || 'X0 Start';\n\n return `\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${subject}</title>\n <style>\n body {\n margin: 0;\n padding: 0;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n background-color: #f5f5f5;\n line-height: 1.6;\n }\n .email-wrapper {\n background-color: #f5f5f5;\n padding: 40px 20px;\n }\n .email-container {\n max-width: 600px;\n margin: 0 auto;\n background-color: #ffffff;\n border-radius: 8px;\n overflow: hidden;\n box-shadow: 0 2px 8px rgba(0,0,0,0.1);\n }\n .email-header {\n padding: 40px 40px 20px;\n text-align: center;\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: #ffffff;\n }\n .email-header h1 {\n margin: 0;\n font-size: 28px;\n font-weight: 600;\n }\n .email-content {\n padding: 30px 40px;\n color: #333333;\n }\n .email-content h1 {\n font-size: 24px;\n margin-top: 0;\n margin-bottom: 20px;\n color: #333333;\n }\n .email-content h2 {\n font-size: 20px;\n margin-top: 30px;\n margin-bottom: 15px;\n color: #333333;\n }\n .email-content h3 {\n font-size: 16px;\n margin-top: 20px;\n margin-bottom: 10px;\n color: #333333;\n }\n .email-content p {\n margin: 0 0 15px;\n color: #666666;\n }\n .email-content a {\n color: #667eea;\n text-decoration: none;\n }\n .email-content ul, .email-content ol {\n margin: 0 0 15px;\n padding-left: 25px;\n }\n .email-content li {\n margin-bottom: 8px;\n color: #666666;\n }\n .email-content blockquote {\n margin: 20px 0;\n padding: 15px 20px;\n background-color: #f8f9fa;\n border-left: 4px solid #667eea;\n color: #666666;\n }\n .email-content code {\n padding: 2px 6px;\n background-color: #f8f9fa;\n border-radius: 3px;\n font-family: 'Courier New', monospace;\n font-size: 14px;\n }\n .email-content pre {\n padding: 15px;\n background-color: #f8f9fa;\n border-radius: 6px;\n overflow-x: auto;\n }\n .email-content pre code {\n padding: 0;\n background: none;\n }\n .btn {\n display: inline-block;\n padding: 12px 24px;\n background-color: #667eea;\n color: #ffffff !important;\n text-decoration: none;\n border-radius: 6px;\n font-weight: 600;\n margin: 10px 0;\n }\n .btn:hover {\n background-color: #5568d3;\n }\n .email-footer {\n padding: 20px 40px;\n background-color: #f8f9fa;\n text-align: center;\n font-size: 12px;\n color: #666666;\n }\n .email-footer a {\n color: #667eea;\n text-decoration: none;\n }\n hr {\n border: none;\n border-top: 1px solid #e0e0e0;\n margin: 30px 0;\n }\n </style>\n</head>\n<body>\n <div class=\"email-wrapper\">\n <div class=\"email-container\">\n <div class=\"email-content\">\n ${contentHtml}\n </div>\n <div class=\"email-footer\">\n <p style=\"margin: 0 0 10px;\">\n You're receiving this email from ${brandName}.\n </p>\n <p style=\"margin: 0;\">\n <a href=\"${unsubscribeUrl}\">Unsubscribe</a> | \n <a href=\"${portalUrl}/settings/notifications\">Manage Preferences</a>\n </p>\n </div>\n </div>\n </div>\n</body>\n</html>\n `.trim();\n}\n","/**\n * EmailingCacheDO - Optional read-through cache for email templates and settings\n * \n * This is a Cloudflare Durable Object that provides caching for email templates and settings.\n * \n * Configurable via environment variable:\n * - EMAIL_TABLE_PREFIX: Prefix for tables (default: 'system_email_')\n */\nexport class EmailingCacheDO {\n constructor(state, env) {\n this.state = state;\n this.env = env;\n this.cache = new Map(); // templateId -> { data, timestamp }\n this.settingsCache = new Map(); // key -> { data, timestamp }\n this.cacheTTL = 3600000; // 1 hour in milliseconds\n // Templates use the prefix\n this.emailTablePrefix = env.EMAIL_TABLE_PREFIX || 'system_email_';\n // Settings use a specific table name (defaulting to system_settings)\n // This allows decoupling template prefix from settings table\n this.settingsTableName = env.EMAIL_SETTINGS_TABLE || 'system_settings';\n\n // Optional: Filter settings by key prefix (e.g. 'email_')\n // This allows sharing the system_settings table with other apps\n this.settingsKeyPrefix = env.EMAIL_SETTINGS_KEY_PREFIX || '';\n }\n\n /**\n * Handle HTTP requests to this Durable Object\n */\n async fetch(request) {\n const url = new URL(request.url);\n const path = url.pathname;\n\n try {\n if (path === '/get' && request.method === 'GET') {\n return this.handleGet(request);\n } else if (path === '/invalidate' && request.method === 'POST') {\n return this.handleInvalidate(request);\n } else if (path === '/clear' && request.method === 'POST') {\n return this.handleClear(request);\n } else if (path === '/stats' && request.method === 'GET') {\n return this.handleStats(request);\n }\n // Settings endpoints\n else if (path === '/settings/get' && request.method === 'GET') {\n return this.handleGetSettings(request);\n } else if (path === '/settings/put' && request.method === 'POST') {\n return this.handlePutSettings(request);\n } else if (path === '/settings/invalidate' && request.method === 'POST') {\n return this.handleInvalidateSettings(request);\n } else {\n return new Response('Not Found', { status: 404 });\n }\n } catch (error) {\n console.error('[EmailingCacheDO] Error:', error);\n return new Response(JSON.stringify({ error: error.message }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n\n /**\n * Get template (from cache or D1)\n */\n async handleGet(request) {\n const url = new URL(request.url);\n const templateId = url.searchParams.get('templateId');\n const forceRefresh = url.searchParams.get('refresh') === 'true';\n\n if (!templateId) {\n return new Response(JSON.stringify({ error: 'templateId is required' }), {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Check cache (unless force refresh)\n if (!forceRefresh) {\n const cached = this.cache.get(templateId);\n if (cached && Date.now() - cached.timestamp < this.cacheTTL) {\n console.log('[EmailingCacheDO] Cache HIT:', templateId);\n return new Response(JSON.stringify({\n template: cached.data,\n cached: true,\n age: Date.now() - cached.timestamp,\n }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n\n // Cache miss or expired - fetch from D1\n console.log('[EmailingCacheDO] Cache MISS - fetching from D1:', templateId);\n const template = await this.fetchTemplateFromD1(templateId);\n\n if (!template) {\n return new Response(JSON.stringify({\n error: 'Template not found',\n templateId\n }), {\n status: 404,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Cache the result\n this.cache.set(templateId, {\n data: template,\n timestamp: Date.now(),\n });\n\n return new Response(JSON.stringify({\n template,\n cached: false,\n }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // --- Settings Cache Handlers ---\n\n async handleGetSettings(request) {\n const url = new URL(request.url);\n const key = url.searchParams.get('key');\n\n if (!key) return new Response('Key required', { status: 400 });\n\n // Check Cache\n const cached = this.settingsCache.get(key);\n if (cached && Date.now() - cached.timestamp < this.cacheTTL) {\n console.log('[EmailingCacheDO] Settings Cache HIT:', key);\n return new Response(JSON.stringify({ settings: cached.data }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Cache Miss - Fetch from D1 (Read-Through)\n // Only fetch from D1 for system settings (consistent with handlePutSettings)\n if (key.startsWith('system')) {\n console.log('[EmailingCacheDO] Settings Cache MISS - fetching from D1:', key);\n const settings = await this.fetchSettingsFromD1(key);\n\n // Even if null, we might want to cache the \"null\" result to prevent hammer? \n // For now, only cache if we found something or explicitly handle negative caching.\n if (settings) {\n this.settingsCache.set(key, {\n data: settings,\n timestamp: Date.now()\n });\n return new Response(JSON.stringify({ settings }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n\n return new Response(JSON.stringify({ settings: null }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n async handlePutSettings(request) {\n try {\n const body = await request.json();\n const { key, settings } = body;\n\n if (!key || !settings) return new Response('Key and settings required', { status: 400 });\n\n // Write to Cache\n this.settingsCache.set(key, {\n data: settings,\n timestamp: Date.now()\n });\n\n // Write to D1 (Write-Through)\n // Note: only supports writing to \"system\" (default table) currently\n if (key.startsWith('system')) {\n await this.saveSettingsToD1(settings);\n }\n\n return new Response(JSON.stringify({ success: true }), {\n headers: { 'Content-Type': 'application/json' },\n });\n } catch (e) {\n console.error('[EmailingCacheDO] PutSettings error:', e);\n return new Response('Error parsing body/saving', { status: 400 });\n }\n }\n\n async handleInvalidateSettings(request) {\n try {\n const body = await request.json();\n const { key } = body;\n\n if (!key) return new Response('Key required', { status: 400 });\n\n const existed = this.settingsCache.has(key);\n this.settingsCache.delete(key);\n console.log('[EmailingCacheDO] Invalidated settings:', key, existed ? '(existed)' : '(not in cache)');\n\n return new Response(JSON.stringify({ success: true, existed }), {\n headers: { 'Content-Type': 'application/json' },\n });\n } catch (e) {\n console.error('[EmailingCacheDO] InvalidateSettings error:', e);\n return new Response('Error invalidated settings', { status: 400 });\n }\n }\n\n /**\n * Invalidate specific template(s) from cache\n * Body: { templateId: 'template_id' } or { templateId: '*' } for all\n */\n async handleInvalidate(request) {\n const body = await request.json();\n const { templateId } = body;\n\n if (!templateId) {\n return new Response(JSON.stringify({ error: 'templateId is required' }), {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n if (templateId === '*') {\n // Invalidate all templates\n const count = this.cache.size;\n this.cache.clear();\n console.log('[EmailingCacheDO] Invalidated ALL templates:', count);\n return new Response(JSON.stringify({\n success: true,\n message: `Invalidated ${count} templates`,\n }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Invalidate specific template\n const existed = this.cache.has(templateId);\n this.cache.delete(templateId);\n console.log('[EmailingCacheDO] Invalidated template:', templateId, existed ? '(existed)' : '(not in cache)');\n\n return new Response(JSON.stringify({\n success: true,\n message: existed ? 'Template invalidated' : 'Template was not in cache',\n templateId,\n }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n /**\n * Clear entire cache (admin operation)\n */\n async handleClear(request) {\n const count = this.cache.size + this.settingsCache.size;\n this.cache.clear();\n this.settingsCache.clear();\n console.log('[EmailingCacheDO] Cache cleared:', count, 'entries (templates + settings)');\n\n return new Response(JSON.stringify({\n success: true,\n message: `Cleared ${count} cached items`,\n }), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n /**\n * Get cache statistics\n */\n async handleStats(request) {\n const stats = {\n templates: this.cache.size,\n settings: this.settingsCache.size,\n cacheTTL: this.cacheTTL,\n };\n\n return new Response(JSON.stringify(stats), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n /**\n * Fetch template from D1\n */\n async fetchTemplateFromD1(templateId) {\n const db = this.env.DB;\n const tableName = `${this.emailTablePrefix}templates`;\n\n try {\n const template = await db\n .prepare(`SELECT * FROM ${tableName} WHERE template_id = ? AND is_active = 1`)\n .bind(templateId)\n .first();\n return template;\n } catch (e) {\n console.error(`[EmailingCacheDO] DB Error (${tableName}):`, e);\n return null;\n }\n }\n\n /**\n * Fetch settings from D1\n * Only supports default table (e.g. system_settings) for now\n */\n async fetchSettingsFromD1(key) {\n const db = this.env.DB;\n const tableName = this.settingsTableName;\n const prefix = this.settingsKeyPrefix;\n\n try {\n let results;\n\n if (prefix) {\n // Filter by prefix (e.g. WHERE setting_key LIKE 'email_%')\n // Note: We need to handle both schema variants (setting_key vs key)\n // BUT standard D1 SQL doesn't support \"OR\" in column names easily with LIKE parameter binding\n // for flexible schemas.\n // We will assume 'setting_key' matches if table is system_settings, or try both.\n\n // Construct query dynamically based on likely schema or just try standard first\n try {\n results = await db.prepare(`SELECT * FROM ${tableName} WHERE setting_key LIKE ?`).bind(`${prefix}%`).all();\n } catch (e) {\n // Fallback to 'key' column\n results = await db.prepare(`SELECT * FROM ${tableName} WHERE key LIKE ?`).bind(`${prefix}%`).all();\n }\n } else {\n // No prefix, fetch all\n results = await db.prepare(`SELECT * FROM ${tableName}`).all();\n }\n\n if (!results.results || results.results.length === 0) return null;\n\n const settings = {};\n results.results.forEach(row => {\n const k = row.setting_key || row.key;\n const v = row.setting_value || row.value;\n if (k) settings[k] = v;\n });\n return settings;\n } catch (e) {\n console.warn(`[EmailingCacheDO] Failed to load settings from ${tableName}:`, e);\n return null;\n }\n }\n\n async saveSettingsToD1(settings) {\n const db = this.env.DB;\n const tableName = this.settingsTableName;\n\n // Simple upset not easy in D1 without specific keys.\n // We'll rely on calling code/migration. \n // For now, let's just log or try to update if possible.\n // Actually, writing settings is complex because we don't know the schema perfectly.\n // Let's implement a BEST EFFORT update for x0start schema\n\n const entries = Object.entries(settings);\n for (const [k, v] of entries) {\n try {\n // Heuristic: Try to determine column names based on common conventions\n // We'll try Schema 1 (setting_key/value) first as it's the default internal convention\n // If that fails, we might fall back to Schema 2 (key/value) in a real implementation\n // For now, let's try a best-effort upsert based on x0start schema or generic\n\n try {\n const res = await db.prepare(`UPDATE ${tableName} SET setting_value = ? WHERE setting_key = ?`).bind(v, k).run();\n if (res.meta.changes === 0) {\n await db.prepare(`INSERT INTO ${tableName} (setting_key, setting_value) VALUES (?, ?)`).bind(k, v).run();\n }\n } catch (e) {\n // Fallback to key/value\n await db.prepare(`INSERT OR REPLACE INTO ${tableName} (key, value) VALUES (?, ?)`).bind(k, v).run();\n }\n } catch (e) {\n console.warn('[EmailingCacheDO] Failed to save setting to D1:', k);\n }\n }\n }\n}\n\n/**\n * Create a cache provider wrapper for the DO\n */\nexport function createDOCacheProvider(doStub, instanceName = 'global') {\n if (!doStub) {\n return null;\n }\n\n const stub = doStub.get(doStub.idFromName(instanceName));\n\n return {\n async getTemplate(templateId) {\n try {\n const response = await stub.fetch(`http://do/get?templateId=${templateId}`);\n const data = await response.json();\n return data.template || null;\n } catch (e) {\n // Silently fall back to DB - DO cache is optional\n return null;\n }\n },\n\n async getSettings(profile, tenantId) {\n const key = `${profile}:${tenantId || ''}`;\n try {\n const response = await stub.fetch(`http://do/settings/get?key=${encodeURIComponent(key)}`);\n const data = await response.json();\n return data.settings || null;\n } catch (e) {\n return null;\n }\n },\n\n async putSettings(profile, tenantId, settings) {\n const key = `${profile}:${tenantId || ''}`;\n try {\n await stub.fetch('http://do/settings/put', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ key, settings }),\n });\n } catch (e) {\n console.warn('[DOCacheProvider] Failed to cache settings:', e);\n }\n },\n\n async putTemplate(template) {\n try {\n await stub.fetch('http://do/invalidate', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ templateId: template.template_id }),\n });\n } catch (e) {\n console.warn('[DOCacheProvider] Failed to invalidate template:', e);\n }\n },\n\n async deleteTemplate(templateId) {\n try {\n await stub.fetch('http://do/invalidate', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ templateId }),\n });\n } catch (e) {\n console.warn('[DOCacheProvider] Failed to invalidate template:', e);\n }\n },\n\n async invalidateSettings(profile, tenantId) {\n const key = `${profile}:${tenantId || ''}`;\n try {\n await stub.fetch('http://do/settings/invalidate', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ key }),\n });\n } catch (e) {\n console.warn('[DOCacheProvider] Failed to invalidate settings:', e);\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,oBAAuB;AACvB,sBAAqB;;;ACOd,SAAS,oBAAoB,aAAa,SAAS,OAAO,CAAC,GAAG;AACjE,QAAM,YAAY,KAAK,aAAa;AACpC,QAAM,iBAAiB,KAAK,kBAAkB;AAC9C,QAAM,YAAY,KAAK,aAAa;AAEpC,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAMA,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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MACX,OAAO;AACH,cAAM,YAAY,MAAM,SAAS,KAAK;AACtC,gBAAQ,MAAM,wCAAwC,SAAS,QAAQ,SAAS;AAChF,eAAO;AAAA,MACX;AAAA,IACJ,SAAS,OAAO;AACZ,cAAQ,MAAM,uCAAuC,MAAM,OAAO;AAClE,aAAO;AAAA,IACX;AAAA,EACJ;AACJ;","names":["Mustache"]}
|
|
@@ -43,12 +43,25 @@ declare class EmailService {
|
|
|
43
43
|
saveSettings(settings: any, profile?: string, tenantId?: string): Promise<void>;
|
|
44
44
|
saveTemplate(template: any, userId?: string): Promise<void>;
|
|
45
45
|
deleteTemplate(templateId: any): Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* Pre-process template data to auto-format URLs
|
|
48
|
+
* Scans for strings starting with http:// or https:// and wraps them in Markdown links
|
|
49
|
+
*/
|
|
50
|
+
_preprocessData(data: any): any;
|
|
46
51
|
renderTemplate(templateId: any, data: any): Promise<{
|
|
47
52
|
subject: any;
|
|
48
53
|
html: string;
|
|
49
54
|
plainText: any;
|
|
50
55
|
}>;
|
|
51
56
|
wrapInBaseTemplate(content: any, subject: any, data?: {}): string;
|
|
57
|
+
/**
|
|
58
|
+
* Send an email using a template
|
|
59
|
+
* @param {string} templateId - Template ID
|
|
60
|
+
* @param {Object} data - Template variables
|
|
61
|
+
* @param {Object} options - Sending options (to, provider, etc.)
|
|
62
|
+
* @returns {Promise<Object>} Delivery result
|
|
63
|
+
*/
|
|
64
|
+
sendViaTemplate(templateId: string, data: any, options: any): Promise<any>;
|
|
52
65
|
/**
|
|
53
66
|
* Send a single email
|
|
54
67
|
* @param {Object} params - Email parameters
|
|
@@ -43,12 +43,25 @@ declare class EmailService {
|
|
|
43
43
|
saveSettings(settings: any, profile?: string, tenantId?: string): Promise<void>;
|
|
44
44
|
saveTemplate(template: any, userId?: string): Promise<void>;
|
|
45
45
|
deleteTemplate(templateId: any): Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* Pre-process template data to auto-format URLs
|
|
48
|
+
* Scans for strings starting with http:// or https:// and wraps them in Markdown links
|
|
49
|
+
*/
|
|
50
|
+
_preprocessData(data: any): any;
|
|
46
51
|
renderTemplate(templateId: any, data: any): Promise<{
|
|
47
52
|
subject: any;
|
|
48
53
|
html: string;
|
|
49
54
|
plainText: any;
|
|
50
55
|
}>;
|
|
51
56
|
wrapInBaseTemplate(content: any, subject: any, data?: {}): string;
|
|
57
|
+
/**
|
|
58
|
+
* Send an email using a template
|
|
59
|
+
* @param {string} templateId - Template ID
|
|
60
|
+
* @param {Object} data - Template variables
|
|
61
|
+
* @param {Object} options - Sending options (to, provider, etc.)
|
|
62
|
+
* @returns {Promise<Object>} Delivery result
|
|
63
|
+
*/
|
|
64
|
+
sendViaTemplate(templateId: string, data: any, options: any): Promise<any>;
|
|
52
65
|
/**
|
|
53
66
|
* Send a single email
|
|
54
67
|
* @param {Object} params - Email parameters
|
|
@@ -435,11 +435,28 @@ var EmailService = class {
|
|
|
435
435
|
}
|
|
436
436
|
}
|
|
437
437
|
// --- Rendering ---
|
|
438
|
+
/**
|
|
439
|
+
* Pre-process template data to auto-format URLs
|
|
440
|
+
* Scans for strings starting with http:// or https:// and wraps them in Markdown links
|
|
441
|
+
*/
|
|
442
|
+
_preprocessData(data) {
|
|
443
|
+
if (!data || typeof data !== "object") return data;
|
|
444
|
+
const processed = { ...data };
|
|
445
|
+
for (const [key, value] of Object.entries(processed)) {
|
|
446
|
+
if (typeof value === "string" && (value.startsWith("http://") || value.startsWith("https://"))) {
|
|
447
|
+
if (!value.trim().startsWith("[") && !value.includes("](")) {
|
|
448
|
+
processed[key] = `[${value}](${value})`;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
return processed;
|
|
453
|
+
}
|
|
438
454
|
async renderTemplate(templateId, data) {
|
|
439
455
|
const template = await this.getTemplate(templateId);
|
|
440
456
|
if (!template) throw new Error(`Template not found: ${templateId}`);
|
|
441
|
-
const
|
|
442
|
-
|
|
457
|
+
const processedData = this._preprocessData(data);
|
|
458
|
+
const subject = Mustache.render(template.subject_template, processedData);
|
|
459
|
+
let markdown = Mustache.render(template.body_markdown, processedData);
|
|
443
460
|
markdown = markdown.replace(/\\n/g, "\n");
|
|
444
461
|
marked.use({
|
|
445
462
|
mangle: false,
|
|
@@ -462,6 +479,32 @@ var EmailService = class {
|
|
|
462
479
|
return wrapInEmailTemplate(content, subject, templateData);
|
|
463
480
|
}
|
|
464
481
|
// --- Delivery ---
|
|
482
|
+
/**
|
|
483
|
+
* Send an email using a template
|
|
484
|
+
* @param {string} templateId - Template ID
|
|
485
|
+
* @param {Object} data - Template variables
|
|
486
|
+
* @param {Object} options - Sending options (to, provider, etc.)
|
|
487
|
+
* @returns {Promise<Object>} Delivery result
|
|
488
|
+
*/
|
|
489
|
+
async sendViaTemplate(templateId, data, options) {
|
|
490
|
+
try {
|
|
491
|
+
const { subject, html, plainText } = await this.renderTemplate(templateId, data);
|
|
492
|
+
return await this.sendEmail({
|
|
493
|
+
...options,
|
|
494
|
+
subject,
|
|
495
|
+
// Can be overridden by options.subject if needed, but usually template subject is preferred
|
|
496
|
+
html,
|
|
497
|
+
text: plainText,
|
|
498
|
+
metadata: {
|
|
499
|
+
...options.metadata,
|
|
500
|
+
templateId
|
|
501
|
+
}
|
|
502
|
+
});
|
|
503
|
+
} catch (error) {
|
|
504
|
+
console.error(`[EmailService] sendViaTemplate failed for ${templateId}:`, error);
|
|
505
|
+
return { success: false, error: error.message };
|
|
506
|
+
}
|
|
507
|
+
}
|
|
465
508
|
/**
|
|
466
509
|
* Send a single email
|
|
467
510
|
* @param {Object} params - Email parameters
|