-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathemail-service.ts
More file actions
372 lines (345 loc) · 13.7 KB
/
Copy pathemail-service.ts
File metadata and controls
372 lines (345 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import type {
IEmailService,
IEmailTransport,
SendEmailInput,
SendEmailResult,
SendTemplateInput,
NormalizedEmailMessage,
EmailAddress,
EmailDeliveryStatus,
TransportSendResult,
} from '@objectstack/spec/contracts';
import { renderTemplate, requireVars, htmlToText } from './template-engine.js';
/**
* Internal persistence shim — typed loosely so the service can run
* without an ObjectQL engine wired (e.g. unit tests, serverless).
*/
export interface EmailPersistence {
insert(row: Record<string, any>): Promise<{ id: string } | string>;
update?(id: string, patch: Record<string, any>): Promise<void>;
}
/**
* Naive RFC-5322 validator — good enough to catch obvious typos.
* Defers full validation to the transport / receiving MTA.
*/
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
/**
* Format an EmailAddress (string or {name,address}) into the canonical
* `"Display" <addr>` form. Throws if address is malformed.
*/
export function formatAddress(addr: EmailAddress): string {
const obj = typeof addr === 'string' ? { address: addr } : addr;
const address = String(obj.address ?? '').trim();
if (!EMAIL_REGEX.test(address)) {
throw new Error(`Invalid email address: ${address || '(empty)'}`);
}
const name = obj.name?.trim();
if (!name) return address;
// Quote display name if it contains characters that need quoting
const needsQuote = /[",()<>@:;.\\\[\]]/.test(name);
const quoted = needsQuote ? `"${name.replace(/"/g, '\\"')}"` : name;
return `${quoted} <${address}>`;
}
function listToArray(v: EmailAddress | EmailAddress[] | undefined): string[] | undefined {
if (v === undefined) return undefined;
const arr = Array.isArray(v) ? v : [v];
return arr.map(formatAddress);
}
/**
* Validate input + apply default-from + canonicalize recipients.
* Throws Error('VALIDATION_FAILED: <reason>') for malformed payloads.
*/
export function normalizeMessage(
input: SendEmailInput,
defaultFrom?: EmailAddress,
): NormalizedEmailMessage {
if (!input || typeof input !== 'object') {
throw new Error('VALIDATION_FAILED: input must be an object');
}
const subject = String(input.subject ?? '').trim();
if (!subject) throw new Error('VALIDATION_FAILED: subject is required');
if (!input.text && !input.html) {
throw new Error('VALIDATION_FAILED: at least one of text or html is required');
}
const toArr = listToArray(input.to);
if (!toArr || toArr.length === 0) {
throw new Error('VALIDATION_FAILED: at least one recipient (to) is required');
}
const fromCandidate = input.from ?? defaultFrom;
if (!fromCandidate) {
throw new Error('VALIDATION_FAILED: from address required (set options.defaultFrom or pass input.from)');
}
const from = formatAddress(fromCandidate);
const msg: NormalizedEmailMessage = {
to: toArr,
from,
subject,
...(input.text !== undefined ? { text: input.text } : {}),
...(input.html !== undefined ? { html: input.html } : {}),
};
const cc = listToArray(input.cc);
if (cc && cc.length > 0) msg.cc = cc;
const bcc = listToArray(input.bcc);
if (bcc && bcc.length > 0) msg.bcc = bcc;
if (input.replyTo) msg.replyTo = formatAddress(input.replyTo);
if (input.attachments && input.attachments.length > 0) msg.attachments = input.attachments;
if (input.headers && Object.keys(input.headers).length > 0) msg.headers = input.headers;
return msg;
}
/**
* Development transport — never actually sends. Logs to the provided
* logger and returns a synthetic Message-ID. Useful for local dev,
* tests, and "dry run" environments.
*/
export class LogTransport implements IEmailTransport {
private counter = 0;
constructor(private readonly logger?: { info: (msg: string, meta?: any) => void }) {}
async send(message: NormalizedEmailMessage): Promise<TransportSendResult> {
const messageId = `<dev-${Date.now()}-${++this.counter}@objectstack.local>`;
this.logger?.info('[LogTransport] would send email', {
messageId,
to: message.to,
from: message.from,
subject: message.subject,
hasText: !!message.text,
hasHtml: !!message.html,
attachments: message.attachments?.length ?? 0,
});
return { messageId, response: 'logged' };
}
}
/**
* Generate a UUID-like id without pulling crypto in test contexts.
* Uses crypto.randomUUID when available, falls back to a v4-shaped
* random string. NOT cryptographically secure when the fallback is
* used; the only consumer is local row identifiers, never tokens.
*/
function newId(): string {
try {
const g = (globalThis as any).crypto;
if (g?.randomUUID) return g.randomUUID();
} catch { /* fall through */ }
const hex = (n: number) => Math.floor(Math.random() * 16 ** n).toString(16).padStart(n, '0');
return `${hex(8)}-${hex(4)}-4${hex(3)}-a${hex(3)}-${hex(12)}`;
}
/**
* Loader for sys_email_template rows. Injected by EmailServicePlugin
* on `kernel:ready`. Returns the best-matching row for `(name, locale)`
* or `null` when none exists / inactive.
*/
export interface TemplateLoader {
load(name: string, locale: string | undefined): Promise<EmailTemplateRow | null>;
}
/**
* Row shape returned by the loader — mirrors sys_email_template
* columns relevant to rendering.
*/
export interface EmailTemplateRow {
name: string;
locale: string;
subject: string;
body_html: string;
body_text?: string | null;
from_name?: string | null;
from_address?: string | null;
reply_to?: string | null;
active?: boolean;
variables_json?: string | null;
}
export interface EmailServiceOptions {
transport: IEmailTransport;
defaultFrom?: EmailAddress;
/** Persist each attempt to sys_email. Omit to disable persistence. */
persistence?: EmailPersistence;
/** Resolve named templates for sendTemplate(). Omit to disable templates. */
templateLoader?: TemplateLoader;
/** Retry attempts on transport throw. Default 0 (no retry). */
retries?: number;
/** Logger for diagnostic output. */
logger?: { info: (msg: string, meta?: any) => void; warn: (msg: string, meta?: any) => void; error?: (msg: string, meta?: any) => void };
/** Default render context merged into every sendTemplate call (e.g. `{ appName }`). */
defaultTemplateContext?: Record<string, unknown>;
}
/**
* Concrete IEmailService implementation.
*
* Flow:
* 1. Validate + normalize input (throws on bad input).
* 2. Persist queued row to sys_email (best-effort; failures logged).
* 3. Call transport.send(); on success, update row to sent +
* timestamp + messageId. On failure, mark failed + error.
* 4. Return SendEmailResult with the persisted row id (or a fresh
* id when persistence is disabled).
*/
export class EmailService implements IEmailService {
constructor(public options: EmailServiceOptions) {
if (!options.transport) throw new Error('EmailService: transport is required');
}
/** Wire (or replace) the template loader after construction. */
setTemplateLoader(loader: TemplateLoader): void {
this.options.templateLoader = loader;
}
/** Wire (or replace) persistence after construction. */
setPersistence(persistence: EmailPersistence | undefined): void {
this.options.persistence = persistence;
}
/**
* Hot-swap the underlying transport. Used by EmailServicePlugin when
* the `mail` settings namespace changes (e.g. SMTP host updated in
* the admin UI) so subsequent `send()` calls go through the new
* transport without restarting the process.
*/
setTransport(transport: IEmailTransport): void {
this.options.transport = transport;
}
/** Replace the default `from` address used when callers omit `input.from`. */
setDefaultFrom(from: EmailAddress | undefined): void {
this.options.defaultFrom = from;
}
async send(input: SendEmailInput): Promise<SendEmailResult> {
let normalized: NormalizedEmailMessage;
try {
normalized = normalizeMessage(input, this.options.defaultFrom);
} catch (err: any) {
// Validation failures must surface to the caller.
throw err;
}
const id = newId();
const baseRow: Record<string, any> = {
id,
from_address: normalized.from,
to_addresses: normalized.to.join(', '),
...(normalized.cc?.length ? { cc_addresses: normalized.cc.join(', ') } : {}),
...(normalized.bcc?.length ? { bcc_addresses: normalized.bcc.join(', ') } : {}),
...(normalized.replyTo ? { reply_to: normalized.replyTo } : {}),
subject: normalized.subject,
...(normalized.text !== undefined ? { body_text: normalized.text } : {}),
...(normalized.html !== undefined ? { body_html: normalized.html } : {}),
...(input.relatedObject ? { related_object: input.relatedObject } : {}),
...(input.relatedId ? { related_id: input.relatedId } : {}),
...(input.sentBy ? { sent_by: input.sentBy } : {}),
status: 'queued',
attempt_count: 0,
};
let persistedId: string | undefined;
if (this.options.persistence) {
try {
const res = await this.options.persistence.insert(baseRow);
persistedId = typeof res === 'string' ? res : res?.id ?? id;
} catch (err: any) {
this.options.logger?.warn('EmailService: sys_email persist failed (non-fatal)', { error: err?.message });
}
}
const rowId = persistedId ?? id;
const maxAttempts = (this.options.retries ?? 0) + 1;
let lastError: any;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const result = await this.options.transport.send(normalized);
const messageId = result.messageId;
const status: EmailDeliveryStatus = 'sent';
await this.updateRow(rowId, {
status,
message_id: messageId,
sent_at: new Date().toISOString(),
attempt_count: attempt,
});
return { id: rowId, status, messageId };
} catch (err: any) {
lastError = err;
if (attempt < maxAttempts) {
// simple exponential backoff
await new Promise(r => setTimeout(r, Math.min(2000, 100 * 2 ** (attempt - 1))));
}
}
}
const errMessage = String(lastError?.message ?? lastError ?? 'send failed').slice(0, 1000);
await this.updateRow(rowId, {
status: 'failed',
error: errMessage,
attempt_count: maxAttempts,
});
return { id: rowId, status: 'failed', error: errMessage };
}
private async updateRow(id: string, patch: Record<string, any>): Promise<void> {
if (!this.options.persistence?.update) return;
try {
await this.options.persistence.update(id, patch);
} catch (err: any) {
this.options.logger?.warn('EmailService: sys_email update failed (non-fatal)', { id, error: err?.message });
}
}
/**
* Render a named template from sys_email_template and deliver via
* send(). Looks up `(name, locale)` then falls back to `(name, 'en-US')`.
*/
async sendTemplate(input: SendTemplateInput): Promise<SendEmailResult> {
if (!input?.template) {
throw new Error('VALIDATION_FAILED: template name is required');
}
const loader = this.options.templateLoader;
if (!loader) {
throw new Error('TEMPLATE_NOT_FOUND: no templateLoader configured on EmailService');
}
const preferred = input.locale && String(input.locale).trim();
let row = await loader.load(input.template, preferred || undefined);
if (!row && preferred && preferred !== 'en-US') {
row = await loader.load(input.template, 'en-US');
}
if (!row) {
throw new Error(`TEMPLATE_NOT_FOUND: ${input.template} (locale=${preferred || 'en-US'})`);
}
if (row.active === false) {
throw new Error(`TEMPLATE_INACTIVE: ${input.template}`);
}
// Validate required variables (declared in variables_json).
const data: Record<string, any> = {
...(this.options.defaultTemplateContext || {}),
...(input.data || {}),
};
if (row.variables_json) {
try {
const decl: Array<{ name: string; required?: boolean }> = JSON.parse(String(row.variables_json));
const required = decl.filter((v) => v?.required).map((v) => v.name);
if (required.length) requireVars(data, required);
} catch (err: any) {
if (String(err?.message).startsWith('MISSING_VARIABLES')) throw err;
this.options.logger?.warn('EmailService: variables_json parse failed (ignored)', { template: input.template });
}
}
// Render holes with the recipient's locale + reference timezone so
// `{{ ts | datetime }}` shows the right wall-clock (ADR-0053 Phase 2).
const renderOpts = {
...(input.locale ? { locale: input.locale } : {}),
...(input.timezone ? { timeZone: input.timezone } : {}),
};
const subject = renderTemplate(row.subject, data, renderOpts);
const html = renderTemplate(row.body_html, data, renderOpts);
const text = row.body_text
? renderTemplate(row.body_text, data, renderOpts)
: htmlToText(html);
const from: EmailAddress | undefined = input.from
?? (row.from_address
? { address: row.from_address, ...(row.from_name ? { name: row.from_name } : {}) }
: undefined);
const sendInput: SendEmailInput = {
to: input.to,
subject,
html,
text,
...(from ? { from } : {}),
...(input.cc ? { cc: input.cc } : {}),
...(input.bcc ? { bcc: input.bcc } : {}),
...(input.replyTo ?? row.reply_to
? { replyTo: input.replyTo ?? (row.reply_to as string) }
: {}),
...(input.attachments ? { attachments: input.attachments } : {}),
...(input.headers ? { headers: input.headers } : {}),
...(input.relatedObject ? { relatedObject: input.relatedObject } : {}),
...(input.relatedId ? { relatedId: input.relatedId } : {}),
...(input.sentBy ? { sentBy: input.sentBy } : {}),
};
return this.send(sendInput);
}
}