@tylix/mail 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,181 @@
1
+ // The standalone mailer. Works in any Node app; nothing here needs Tylix.
2
+ //
3
+ // import { createMailer, transports } from '@tylix/mail'
4
+ //
5
+ // const mailer = createMailer({
6
+ // transport: transports.resend({ apiKey: process.env.RESEND_API_KEY }),
7
+ // from: 'Acme <hello@acme.dev>',
8
+ // views: './emails', // or (view, data) => ({ html, text })
9
+ // })
10
+ //
11
+ // await mailer.send({
12
+ // to: 'ada@example.com',
13
+ // subject: 'Welcome',
14
+ // view: 'welcome', data: { name: 'Ada' }, // or html / text
15
+ // attachments: [{ path: './invoice.pdf' }],
16
+ // })
17
+ import { buildMime, loadAttachments, normalizeMessage } from './mime.js'
18
+ import { createViewRenderer } from './template.js'
19
+ import { log as logTransport } from './transports/dev.js'
20
+
21
+ function resolveViews(views) {
22
+ if (typeof views === 'function') return views
23
+ if (typeof views === 'string') return createViewRenderer(views)
24
+ return null
25
+ }
26
+
27
+ // Mailable instances (anything with build()) become plain messages.
28
+ async function toMessage(input, to) {
29
+ if (input && typeof input.build === 'function') {
30
+ const built = await input.build()
31
+ return { ...built, ...(to !== undefined ? { to } : {}) }
32
+ }
33
+ return to !== undefined ? { ...input, to } : input
34
+ }
35
+
36
+ export function createMailer({
37
+ transport = logTransport(),
38
+ from,
39
+ replyTo,
40
+ headers,
41
+ views,
42
+ onSent,
43
+ onError,
44
+ } = {}) {
45
+ let current = transport
46
+ const render = resolveViews(views)
47
+
48
+ // The message with its view rendered and defaults applied; nothing sent.
49
+ async function prepare(input, to) {
50
+ const message = await toMessage(input, to)
51
+ let { html, text } = message
52
+ if (message.view) {
53
+ if (!render) throw new Error(`Message uses view "${message.view}" but the mailer has no \`views\` option`)
54
+ const out = await render(message.view, message.data ?? {})
55
+ const rendered = typeof out === 'string' ? { html: out } : out
56
+ html = html ?? rendered.html
57
+ text = text ?? rendered.text
58
+ }
59
+ const normalized = normalizeMessage(
60
+ { ...message, html, text, headers: { ...headers, ...message.headers } },
61
+ { from, replyTo },
62
+ )
63
+ normalized.attachments = await loadAttachments(normalized.attachments)
64
+ normalized.view = message.view ?? null
65
+ normalized.data = message.data ?? null
66
+ return normalized
67
+ }
68
+
69
+ const mailer = {
70
+ get transport() {
71
+ return current
72
+ },
73
+ // Swap the transport (Mail.fake() uses this).
74
+ useTransport(next) {
75
+ const previous = current
76
+ current = next
77
+ return previous
78
+ },
79
+
80
+ async send(input, to) {
81
+ const msg = await prepare(input, to)
82
+ try {
83
+ const result = await current.send(msg)
84
+ const outcome = { status: result?.status ?? 'sent', id: result?.id ?? null, transport: current.name ?? 'custom', message: msg }
85
+ await onSent?.(outcome)
86
+ return outcome
87
+ } catch (err) {
88
+ await onError?.(err, { transport: current.name ?? 'custom', message: msg })
89
+ throw err
90
+ }
91
+ },
92
+
93
+ // Renders without sending: { subject, html, text, from, to, ... }.
94
+ prepare,
95
+
96
+ // The complete .eml text of a message, for previews and debugging.
97
+ async preview(input, to) {
98
+ const msg = await prepare(input, to)
99
+ return { ...msg, raw: buildMime(msg).raw }
100
+ },
101
+ }
102
+ return mailer
103
+ }
104
+
105
+ // ---------------------------------------------------------------- fakes
106
+
107
+ function matches(value, expected) {
108
+ if (expected instanceof RegExp) return expected.test(String(value ?? ''))
109
+ if (typeof expected === 'function') return Boolean(expected(value))
110
+ return value === expected
111
+ }
112
+
113
+ function hasAddress(list, expected) {
114
+ return list.some((a) => matches(a.address, expected))
115
+ }
116
+
117
+ // match: a predicate, or { to, cc, bcc, from, subject, view, html, text }
118
+ // where strings must be equal (html/text: contained) and RegExps match.
119
+ export function messageMatches(msg, match) {
120
+ if (typeof match === 'function') return Boolean(match(msg))
121
+ for (const [key, expected] of Object.entries(match ?? {})) {
122
+ if (key === 'to' || key === 'cc' || key === 'bcc' || key === 'replyTo') {
123
+ if (![].concat(expected).every((e) => hasAddress(msg[key], e))) return false
124
+ } else if (key === 'from') {
125
+ if (!matches(msg.from.address, expected)) return false
126
+ } else if ((key === 'html' || key === 'text') && typeof expected === 'string') {
127
+ if (!msg[key].includes(expected)) return false
128
+ } else if (!matches(msg[key], expected)) {
129
+ return false
130
+ }
131
+ }
132
+ return true
133
+ }
134
+
135
+ function describe(match) {
136
+ if (typeof match === 'function') return 'matching the predicate'
137
+ return JSON.stringify(match, (k, v) => (v instanceof RegExp ? String(v) : v))
138
+ }
139
+
140
+ // A memory transport with assertions. Pass it to createMailer, or use
141
+ // Mail.fake() in Tylix apps.
142
+ export function createFakeTransport() {
143
+ const sent = []
144
+ const fake = {
145
+ name: 'fake',
146
+ sent,
147
+ async send(msg) {
148
+ sent.push(msg)
149
+ return { status: 'captured', id: `fake-${sent.length}` }
150
+ },
151
+ last() {
152
+ return sent.at(-1) ?? null
153
+ },
154
+ find(match) {
155
+ return sent.filter((m) => messageMatches(m, match))
156
+ },
157
+ assertSent(match = {}, times) {
158
+ const found = fake.find(match)
159
+ if (times === undefined ? found.length === 0 : found.length !== times) {
160
+ throw new Error(
161
+ `Expected ${times === undefined ? 'a' : times} message(s) ${describe(match)}, found ${found.length}. Sent: ${sent.map((m) => `"${m.subject}" to ${m.to.map((a) => a.address).join(', ')}`).join('; ') || 'nothing'}`,
162
+ )
163
+ }
164
+ return found
165
+ },
166
+ assertNotSent(match = {}) {
167
+ const found = fake.find(match)
168
+ if (found.length) throw new Error(`Expected no message ${describe(match)}, found ${found.length}`)
169
+ },
170
+ assertNothingSent() {
171
+ if (sent.length) throw new Error(`Expected no mail, but ${sent.length} message(s) were sent`)
172
+ },
173
+ assertSentCount(n) {
174
+ if (sent.length !== n) throw new Error(`Expected ${n} message(s), ${sent.length} were sent`)
175
+ },
176
+ clear() {
177
+ sent.length = 0
178
+ },
179
+ }
180
+ return fake
181
+ }
package/index.d.ts CHANGED
@@ -1,49 +1,242 @@
1
- import { Model } from '@tylix/orm'
2
-
3
- export interface MailConfig {
4
- /** Anything other than "smtp" falls back to the log driver. */
5
- driver?: 'smtp' | 'log'
6
- /** Sender address. Required for the smtp driver. */
7
- from?: string
8
- host?: string
1
+ // ------------------------------------------------------------- messages
2
+
3
+ /** "ada@example.com", "Ada <ada@example.com>" or { name, address }. */
4
+ export type Address = string | { name?: string; address: string }
5
+
6
+ export interface Attachment {
7
+ filename?: string
8
+ /** File contents. A string is UTF-8 unless `encoding: 'base64'`. */
9
+ content?: Buffer | Uint8Array | string
10
+ /** Read from disk at send time instead of `content`. */
11
+ path?: string
12
+ encoding?: 'base64' | 'utf8'
13
+ /** Guessed from the file name when omitted. */
14
+ contentType?: string
15
+ /** Makes it an inline image, referenced in HTML as <img src="cid:ID">. */
16
+ cid?: string
17
+ }
18
+
19
+ export interface MailMessage {
20
+ to?: Address | Address[]
21
+ cc?: Address | Address[]
22
+ bcc?: Address | Address[]
23
+ /** Defaults to the mailer's `from`. */
24
+ from?: Address
25
+ replyTo?: Address | Address[]
26
+ subject?: string
27
+ html?: string
28
+ /** Generated from `html` when omitted. */
29
+ text?: string
30
+ /** A template rendered with `data` by the mailer's `views`. */
31
+ view?: string
32
+ data?: Record<string, unknown>
33
+ attachments?: Attachment[]
34
+ headers?: Record<string, string>
35
+ /** Provider tags / metadata (Resend tags, SendGrid custom_args, Postmark Tag + Metadata, Mailgun o:tag / v:, SES EmailTags). */
36
+ tags?: Record<string, string | number>
37
+ }
38
+
39
+ export interface ParsedAddress {
40
+ name: string
41
+ address: string
42
+ }
43
+
44
+ /** What transports receive and fakes record. */
45
+ export interface NormalizedMessage {
46
+ from: ParsedAddress
47
+ to: ParsedAddress[]
48
+ cc: ParsedAddress[]
49
+ bcc: ParsedAddress[]
50
+ replyTo: ParsedAddress[]
51
+ subject: string
52
+ html: string
53
+ text: string
54
+ headers: Record<string, string>
55
+ attachments: { filename: string; content: Buffer; contentType: string; cid: string | null }[]
56
+ tags: Record<string, string | number>
57
+ view: string | null
58
+ data: Record<string, unknown> | null
59
+ }
60
+
61
+ export interface SendResult {
62
+ status: 'sent' | 'captured'
63
+ /** The provider's message id, when it returns one. */
64
+ id: string | null
65
+ transport: string
66
+ message: NormalizedMessage
67
+ }
68
+
69
+ // ------------------------------------------------------------ transports
70
+
71
+ export interface MailTransport {
72
+ name?: string
73
+ send(message: NormalizedMessage): Promise<{ status?: 'sent' | 'captured'; id?: string | null }>
74
+ }
75
+
76
+ export interface SmtpOptions {
77
+ host: string
78
+ /** Default 587 (STARTTLS). */
9
79
  port?: number
10
- /** true = implicit TLS (port 465). Port 587 upgrades with STARTTLS. */
80
+ /** Implicit TLS (port 465). */
11
81
  secure?: boolean
12
82
  user?: string
13
83
  password?: string
14
- /** Name announced in EHLO. Defaults to "localhost". */
84
+ /** Name announced in EHLO. Default "localhost". */
15
85
  clientName?: string
86
+ /** true: STARTTLS on any port; false: never (local test servers). Default: only on 587. */
87
+ requireTLS?: boolean
88
+ timeoutMs?: number
16
89
  }
17
90
 
18
- export interface MailContent {
19
- subject: string
20
- /** Name of an HTML file in resources/mail/, without the extension. */
21
- view?: string
22
- /** Values rendered into the view template. */
23
- data?: Record<string, unknown>
91
+ export declare const transports: {
92
+ smtp(options: SmtpOptions): MailTransport
93
+ resend(options: { apiKey: string; endpoint?: string; fetch?: typeof fetch }): MailTransport
94
+ sendgrid(options: { apiKey: string; endpoint?: string; fetch?: typeof fetch }): MailTransport
95
+ postmark(options: { serverToken: string; messageStream?: string; endpoint?: string; fetch?: typeof fetch }): MailTransport
96
+ mailgun(options: { apiKey: string; domain: string; region?: 'us' | 'eu'; endpoint?: string; fetch?: typeof fetch }): MailTransport
97
+ /** Credentials default to AWS_REGION / AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_SESSION_TOKEN. */
98
+ ses(options?: {
99
+ region?: string
100
+ accessKeyId?: string
101
+ secretAccessKey?: string
102
+ sessionToken?: string
103
+ configurationSet?: string
104
+ endpoint?: string
105
+ fetch?: typeof fetch
106
+ }): MailTransport
107
+ /** Prints messages instead of sending them. */
108
+ log(options?: { logger?: { log(text: string): void }; showBody?: boolean }): MailTransport
109
+ /** Keeps messages in `.messages`. */
110
+ memory(): MailTransport & { messages: NormalizedMessage[] }
24
111
  }
25
112
 
26
- export interface SendMailOptions extends MailContent {
27
- to: string | string[]
113
+ export declare class MailTransportError extends Error {
114
+ provider: string
115
+ status: number
116
+ response: unknown
28
117
  }
29
118
 
30
- export interface DeliveryResult {
31
- status: 'sent' | 'captured'
119
+ // ---------------------------------------------------------------- mailer
120
+
121
+ /** A message without `to`, built by a Mailable. */
122
+ export type MailContent = Omit<MailMessage, 'to'> & { to?: MailMessage['to'] }
123
+
124
+ export interface MailerOptions {
125
+ /** Default: transports.log() */
126
+ transport?: MailTransport
127
+ from?: Address
128
+ replyTo?: Address | Address[]
129
+ /** Headers added to every message. */
130
+ headers?: Record<string, string>
131
+ /** A folder of <view>.html (+ optional <view>.txt) templates, or a render function. */
132
+ views?: string | ((view: string, data: Record<string, unknown>) => Promise<string | { html?: string; text?: string }> | string | { html?: string; text?: string })
133
+ onSent?(result: SendResult): void | Promise<void>
134
+ onError?(error: Error, info: { transport: string; message: NormalizedMessage }): void | Promise<void>
32
135
  }
33
136
 
34
- export class Mail {
35
- static send(options: SendMailOptions, config: MailConfig): Promise<DeliveryResult>
137
+ export interface Mailer {
138
+ readonly transport: MailTransport
139
+ useTransport(transport: MailTransport): MailTransport
140
+ send(message: MailMessage | Mailable, to?: MailMessage['to']): Promise<SendResult>
141
+ /** The message with its view rendered and defaults applied, not sent. */
142
+ prepare(message: MailMessage | Mailable, to?: MailMessage['to']): Promise<NormalizedMessage>
143
+ /** Like prepare(), plus the complete .eml text as `raw`. */
144
+ preview(message: MailMessage | Mailable, to?: MailMessage['to']): Promise<NormalizedMessage & { raw: string }>
36
145
  }
37
146
 
38
- export abstract class Mailable {
39
- abstract build(): MailContent
40
- send(to: string | string[], config: MailConfig): Promise<DeliveryResult>
147
+ export declare function createMailer(options?: MailerOptions): Mailer
148
+
149
+ /** Fields compared exactly (RegExps match; html/text strings are "contains"), or a predicate. */
150
+ export type MessageMatch =
151
+ | ((message: NormalizedMessage) => boolean)
152
+ | {
153
+ to?: string | RegExp | (string | RegExp)[]
154
+ cc?: string | RegExp | (string | RegExp)[]
155
+ bcc?: string | RegExp | (string | RegExp)[]
156
+ replyTo?: string | RegExp | (string | RegExp)[]
157
+ from?: string | RegExp
158
+ subject?: string | RegExp
159
+ view?: string | RegExp
160
+ html?: string | RegExp
161
+ text?: string | RegExp
162
+ }
163
+
164
+ export interface FakeTransport extends MailTransport {
165
+ sent: NormalizedMessage[]
166
+ last(): NormalizedMessage | null
167
+ find(match?: MessageMatch): NormalizedMessage[]
168
+ /** Throws unless a matching message was sent (exactly `times` when given). */
169
+ assertSent(match?: MessageMatch, times?: number): NormalizedMessage[]
170
+ assertNotSent(match?: MessageMatch): void
171
+ assertNothingSent(): void
172
+ assertSentCount(count: number): void
173
+ clear(): void
41
174
  }
42
175
 
43
- export class MailLog extends Model {
176
+ export declare function createFakeTransport(): FakeTransport
177
+ export declare function messageMatches(message: NormalizedMessage, match: MessageMatch): boolean
178
+
179
+ // ------------------------------------------------------------- templates
180
+
181
+ /** {{ value }} (escaped), {{{ raw }}}, {{ a.b }}, {{#if x}}…{{#else}}…{{/if}}, {{#each list}}…{{ this }} {{ @index }}…{{/each}} */
182
+ export declare function renderTemplate(template: string, data?: Record<string, unknown>, name?: string): string
183
+ export declare function createViewRenderer(dir: string): (view: string, data: Record<string, unknown>) => Promise<{ html: string; text?: string }>
184
+ export declare function escapeHtml(value: unknown): string
185
+ export declare function htmlToText(html: string): string
186
+ export declare function parseAddress(address: Address, label?: string): ParsedAddress
187
+ export declare function normalizeMessage(message: MailMessage, defaults?: Partial<MailMessage>): Omit<NormalizedMessage, 'view' | 'data'>
188
+ export declare function buildMime(message: NormalizedMessage): { raw: string; messageId: string; envelope: { from: string; to: string[] } }
189
+
190
+ // ------------------------------------------------------------ Tylix apps
191
+
192
+ export interface MailConfig extends Partial<SmtpOptions> {
193
+ /** Default "log". */
194
+ driver?: 'log' | 'smtp' | 'resend' | 'sendgrid' | 'postmark' | 'mailgun' | 'ses' | 'memory'
195
+ /** A transport object; wins over `driver`. */
196
+ transport?: MailTransport
197
+ from?: Address
198
+ replyTo?: Address | Address[]
199
+ /** Template folder. Default: resources/mail */
200
+ views?: MailerOptions['views']
201
+ /** resend, sendgrid, postmark, mailgun */
202
+ apiKey?: string
203
+ /** postmark (falls back to apiKey) */
204
+ serverToken?: string
205
+ messageStream?: string
206
+ /** mailgun */
207
+ domain?: string
208
+ /** mailgun ('us' | 'eu') or ses (AWS region) */
209
+ region?: string
210
+ /** ses */
211
+ accessKeyId?: string
212
+ secretAccessKey?: string
213
+ sessionToken?: string
214
+ configurationSet?: string
215
+ }
216
+
217
+ export declare function transportFromConfig(config?: MailConfig): MailTransport
218
+ export declare function mailerFromConfig(config?: MailConfig): Mailer
219
+
220
+ export declare class Mail {
221
+ static send(message: MailMessage | Mailable, config?: MailConfig): Promise<SendResult>
222
+ static preview(message: MailMessage | Mailable, config?: MailConfig): Promise<NormalizedMessage & { raw: string }>
223
+ /** Captures every Mail.send() until Mail.restore(). */
224
+ static fake(): FakeTransport
225
+ static restore(): void
226
+ }
227
+
228
+ export declare abstract class Mailable {
229
+ abstract build(): MailContent | Promise<MailContent>
230
+ send(to: MailMessage['to'], config?: MailConfig): Promise<SendResult>
231
+ }
232
+
233
+ /** The mail_logs model. `available` is false when @tylix/orm is not installed. */
234
+ export declare class MailLog {
235
+ static available: boolean
44
236
  static table: string
45
237
  static fillable: string[]
46
238
  static recent(limit?: number): Promise<MailLog[]>
239
+ static create(attributes: Partial<MailLog>): Promise<MailLog>
47
240
 
48
241
  id: number
49
242
  recipient: string
@@ -54,4 +247,4 @@ export class MailLog extends Model {
54
247
  error?: string | null
55
248
  created_at?: string
56
249
  updated_at?: string
57
- }
250
+ }
package/index.js CHANGED
@@ -1,3 +1,11 @@
1
- export { Mail } from './Mailer.js'
1
+ // Standalone (any Node app)
2
+ export { createMailer, createFakeTransport, messageMatches } from './createMailer.js'
3
+ export * as transports from './transports/index.js'
4
+ export { MailTransportError } from './transports/http.js'
5
+ export { renderTemplate, createViewRenderer, escapeHtml } from './template.js'
6
+ export { buildMime, normalizeMessage, htmlToText, parseAddress } from './mime.js'
7
+
8
+ // Tylix apps
9
+ export { Mail, transportFromConfig, mailerFromConfig } from './Mailer.js'
2
10
  export { Mailable } from './Mailable.js'
3
11
  export { MailLog } from './models/MailLog.js'