@prunellejs/mail 0.1.1 → 0.7.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,254 @@
1
+ // Built-in HTTP transports (Resend, Postmark) and `MAIL_URL` transport parser (`smtp://`, `smtps://`, `resend://`, `postmark://`).
2
+
3
+ import type { MailTransport, SentMail } from './types'
4
+ import { smtp } from './smtp'
5
+ import { MailNotConfiguredError } from './types'
6
+
7
+ const DEFAULT_HTTP_TIMEOUT_MS = 10_000
8
+ // A provider's error body lands in the thrown message and so in logs: enough to name the cause, not to copy a mail or a token back.
9
+ const ERROR_BODY_MAX_CHARS = 200
10
+
11
+ export interface ResendOptions {
12
+ apiKey?: string | undefined
13
+ endpoint?: string | undefined
14
+ timeoutMs?: number | undefined
15
+ retries?: number | undefined
16
+ }
17
+
18
+ export interface PostmarkOptions {
19
+ serverToken?: string | undefined
20
+ endpoint?: string | undefined
21
+ timeoutMs?: number | undefined
22
+ retries?: number | undefined
23
+ messageStream?: string | undefined
24
+ }
25
+
26
+ /** The wait before retry `attempt` (0-based): the answer's `retry-after` when it gives one, else 0.5 s doubling, never past 5 s. */
27
+ function retryDelayMs(res: Response | undefined, attempt: number): number {
28
+ const seconds = res !== undefined ? Number(res.headers.get('retry-after')) : Number.NaN
29
+ return Math.min(Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : 500 * 2 ** attempt, 5_000)
30
+ }
31
+
32
+ function isRetryableFetchError(error: unknown): boolean {
33
+ if (error !== null && typeof error === 'object' && 'code' in error && (error as { code?: unknown }).code === 'ERR_INVALID_URL')
34
+ return false
35
+ return true
36
+ }
37
+
38
+ async function sendJsonWithRetry(params: {
39
+ provider: string
40
+ endpoint: string
41
+ headers: Record<string, string>
42
+ body: string
43
+ timeoutMs: number
44
+ retries: number
45
+ /** Whether the provider drops a repeated send (an idempotency key); without it only a 429, which sent nothing, is retried. */
46
+ idempotent: boolean
47
+ }): Promise<void> {
48
+ const { provider, endpoint, headers, body, timeoutMs, retries, idempotent } = params
49
+ for (let attempt = 0; ; attempt++) {
50
+ let res: Response
51
+ try {
52
+ res = await fetch(endpoint, {
53
+ method: 'POST',
54
+ headers,
55
+ body,
56
+ ...(timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}),
57
+ })
58
+ }
59
+ catch (error) {
60
+ if (!idempotent || !isRetryableFetchError(error) || attempt >= retries)
61
+ throw error
62
+ await Bun.sleep(retryDelayMs(undefined, attempt))
63
+ continue
64
+ }
65
+ if (res.ok)
66
+ return
67
+ const text = (await res.text()).slice(0, ERROR_BODY_MAX_CHARS)
68
+ const retryable = res.status === 429 || (idempotent && res.status >= 500)
69
+ if (!retryable || attempt >= retries)
70
+ throw new Error(`@prunellejs/mail (${provider}): HTTP ${res.status}: ${text}`)
71
+ await Bun.sleep(retryDelayMs(res, attempt))
72
+ }
73
+ }
74
+
75
+ /** Zero-dependency Resend HTTP transport using native fetch(); a 429 or 5xx answer is retried `retries` times (default 2) under the mail's id as idempotency key, so a retry never sends twice. */
76
+ export function resend(options: ResendOptions = {}): MailTransport {
77
+ const endpoint = options.endpoint ?? 'https://api.resend.com/emails'
78
+ const timeoutMs = options.timeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS
79
+ const retries = options.retries ?? 2
80
+ return {
81
+ async send(mail: SentMail) {
82
+ const apiKey = options.apiKey ?? process.env.RESEND_API_KEY
83
+ if (!apiKey)
84
+ throw new MailNotConfiguredError('RESEND_API_KEY is not set')
85
+ const body = JSON.stringify({
86
+ from: mail.from,
87
+ to: mail.to,
88
+ reply_to: mail.replyTo,
89
+ subject: mail.subject,
90
+ text: mail.text,
91
+ html: mail.html,
92
+ })
93
+ await sendJsonWithRetry({
94
+ provider: 'resend',
95
+ endpoint,
96
+ headers: {
97
+ 'authorization': `Bearer ${apiKey}`,
98
+ 'content-type': 'application/json',
99
+ 'idempotency-key': mail.id,
100
+ },
101
+ body,
102
+ timeoutMs,
103
+ retries,
104
+ idempotent: true,
105
+ })
106
+ },
107
+ }
108
+ }
109
+
110
+ /** Zero-dependency Postmark HTTP transport using native fetch(). Postmark documents no idempotency key, so only a 429 answer, which sent nothing, is retried `retries` times (default 2): a 5xx or a timeout may have sent the mail, and is thrown instead of risking a second one. */
111
+ export function postmark(options: PostmarkOptions = {}): MailTransport {
112
+ const endpoint = options.endpoint ?? 'https://api.postmarkapp.com/email'
113
+ const timeoutMs = options.timeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS
114
+ const retries = options.retries ?? 2
115
+ return {
116
+ async send(mail: SentMail) {
117
+ const serverToken = options.serverToken ?? process.env.POSTMARK_SERVER_TOKEN
118
+ if (!serverToken)
119
+ throw new MailNotConfiguredError('POSTMARK_SERVER_TOKEN is not set')
120
+ const body = JSON.stringify({
121
+ From: mail.from,
122
+ To: mail.to.join(', '),
123
+ ...(mail.replyTo !== undefined ? { ReplyTo: mail.replyTo } : {}),
124
+ Subject: mail.subject,
125
+ ...(mail.text !== undefined ? { TextBody: mail.text } : {}),
126
+ ...(mail.html !== undefined ? { HtmlBody: mail.html } : {}),
127
+ ...(options.messageStream !== undefined ? { MessageStream: options.messageStream } : {}),
128
+ })
129
+ await sendJsonWithRetry({
130
+ provider: 'postmark',
131
+ endpoint,
132
+ headers: {
133
+ 'accept': 'application/json',
134
+ 'content-type': 'application/json',
135
+ 'x-postmark-server-token': serverToken,
136
+ },
137
+ body,
138
+ timeoutMs,
139
+ retries,
140
+ idempotent: false,
141
+ })
142
+ },
143
+ }
144
+ }
145
+
146
+ function parseOptionalNumber(raw: string | null, label: string): number | undefined {
147
+ if (raw === null || raw === '')
148
+ return undefined
149
+ const num = Number(raw)
150
+ if (!Number.isFinite(num) || num < 0)
151
+ throw new RangeError(`@prunellejs/mail: invalid ${label} "${raw}" in MAIL_URL`)
152
+ return num
153
+ }
154
+
155
+ /** Extracts a case-preserving credential and optional custom endpoint from `resend://<key>` or `resend://:<key>@host/path`. */
156
+ function parseApiUrl(
157
+ rawUrl: string,
158
+ parsed: URL,
159
+ scheme: string,
160
+ defaultHost: string,
161
+ defaultPath: string,
162
+ ): { token: string, endpoint: string | undefined, timeoutMs: number | undefined, retries: number | undefined } {
163
+ const afterScheme = rawUrl.slice(`${scheme}//`.length)
164
+ const endIdx = afterScheme.search(/[/?#]/)
165
+ const authority = endIdx === -1 ? afterScheme : afterScheme.slice(0, endIdx)
166
+ const queryEndpoint = parsed.searchParams.get('endpoint') ?? undefined
167
+ const timeoutMs = parseOptionalNumber(parsed.searchParams.get('timeoutMs'), 'timeoutMs')
168
+ const retries = parseOptionalNumber(parsed.searchParams.get('retries'), 'retries')
169
+
170
+ let token: string
171
+ let endpoint = queryEndpoint
172
+
173
+ if (authority.includes('@')) {
174
+ token = decodeURIComponent(parsed.password || parsed.username)
175
+ if (endpoint === undefined && parsed.hostname.length > 0 && (parsed.hostname !== defaultHost || parsed.port !== '' || (parsed.pathname !== '' && parsed.pathname !== '/'))) {
176
+ const proto = parsed.searchParams.get('insecure') === 'true' ? 'http:' : 'https:'
177
+ const path = parsed.pathname === '' || parsed.pathname === '/' ? defaultPath : parsed.pathname
178
+ endpoint = `${proto}//${parsed.host}${path}`
179
+ }
180
+ }
181
+ else {
182
+ token = decodeURIComponent(authority)
183
+ }
184
+
185
+ if (token.length === 0)
186
+ throw new RangeError(`@prunellejs/mail: ${scheme}// URL is missing its API key / token`)
187
+
188
+ return { token, endpoint, timeoutMs, retries }
189
+ }
190
+
191
+ const TLS_PARAM_MODES: Readonly<Record<string, { requireTls: boolean | undefined, disableStartTls: boolean }>> = {
192
+ true: { requireTls: true, disableStartTls: false },
193
+ 1: { requireTls: true, disableStartTls: false },
194
+ opportunistic: { requireTls: false, disableStartTls: false },
195
+ false: { requireTls: undefined, disableStartTls: true },
196
+ 0: { requireTls: undefined, disableStartTls: true },
197
+ }
198
+
199
+ function parseTlsParam(value: string | null): { requireTls: boolean | undefined, disableStartTls: boolean } {
200
+ if (value === null)
201
+ return { requireTls: undefined, disableStartTls: false }
202
+ const mode = TLS_PARAM_MODES[value]
203
+ if (mode === undefined)
204
+ throw new RangeError(`@prunellejs/mail: invalid tls value "${value}" in MAIL_URL: use true, opportunistic or false`)
205
+ return mode
206
+ }
207
+
208
+ /** Builds a `MailTransport` from a `MAIL_URL` connection string (`smtp://`, `smtps://`, `resend://`, or `postmark://`). */
209
+ export function transportFromUrl(url: string): MailTransport {
210
+ const trimmed = url.trim()
211
+ let parsed: URL
212
+ try {
213
+ parsed = new URL(trimmed)
214
+ }
215
+ catch {
216
+ // Never echo the value: it holds the password or the API key.
217
+ throw new RangeError('@prunellejs/mail: invalid MAIL_URL (not echoed, it holds credentials): expected smtp://user:pass@host:587, smtps://, resend://<key> or postmark://<token>')
218
+ }
219
+
220
+ const protocol = parsed.protocol.toLowerCase()
221
+
222
+ if (protocol === 'smtp:' || protocol === 'smtps:') {
223
+ const secure = protocol === 'smtps:'
224
+ const host = parsed.hostname
225
+ if (host.length === 0)
226
+ throw new RangeError(`@prunellejs/mail: ${protocol}// URL is missing a hostname`)
227
+ const port = parsed.port !== '' ? Number(parsed.port) : (secure ? 465 : 587)
228
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
229
+ throw new RangeError(`@prunellejs/mail: invalid SMTP port "${parsed.port}" in MAIL_URL`)
230
+ const tlsParam = parsed.searchParams.get('tls') ?? parsed.searchParams.get('starttls')
231
+ const { requireTls, disableStartTls } = parseTlsParam(tlsParam)
232
+ const insecureAuthParam = parsed.searchParams.get('allowInsecureAuth')
233
+ const allowInsecureAuth = insecureAuthParam === 'true' || insecureAuthParam === '1' ? true : undefined
234
+ const rejectUnauthorized = parsed.searchParams.get('rejectUnauthorized') !== 'false'
235
+ const user = parsed.username !== '' ? decodeURIComponent(parsed.username) : undefined
236
+ const pass = parsed.password !== '' ? decodeURIComponent(parsed.password) : undefined
237
+ const ehloHost = parsed.searchParams.get('ehloHost') ?? undefined
238
+ const timeoutMs = parseOptionalNumber(parsed.searchParams.get('timeoutMs'), 'timeoutMs')
239
+ return smtp({ host, port, secure, requireTls, disableStartTls, allowInsecureAuth, rejectUnauthorized, user, pass, ehloHost, timeoutMs })
240
+ }
241
+
242
+ if (protocol === 'resend:') {
243
+ const { token, endpoint, timeoutMs, retries } = parseApiUrl(trimmed, parsed, 'resend:', 'api.resend.com', '/emails')
244
+ return resend({ apiKey: token, endpoint, timeoutMs, retries })
245
+ }
246
+
247
+ if (protocol === 'postmark:') {
248
+ const { token, endpoint, timeoutMs, retries } = parseApiUrl(trimmed, parsed, 'postmark:', 'api.postmarkapp.com', '/email')
249
+ const messageStream = parsed.searchParams.get('stream') ?? parsed.searchParams.get('messageStream') ?? undefined
250
+ return postmark({ serverToken: token, endpoint, timeoutMs, retries, messageStream })
251
+ }
252
+
253
+ throw new RangeError(`@prunellejs/mail: unsupported MAIL_URL protocol "${parsed.protocol}" (expected smtp:, smtps:, resend:, or postmark:)`)
254
+ }
package/src/types.ts ADDED
@@ -0,0 +1,161 @@
1
+ // Shared types, errors, and address/header utilities for @prunellejs/mail.
2
+
3
+ import type { JobsQueueOptions, PrunellePlugin } from 'prunelle/config'
4
+ import type { PrunelleChild } from 'prunelle/jsx-runtime'
5
+
6
+ export type MailAddress = string | { name: string, address: string }
7
+
8
+ /** JSX/TSX element, compiled Html, async component result, or lazy render function accepted by `mail.send({ body })` and `renderMail()`. */
9
+ export type MailBody =
10
+ | PrunelleChild
11
+ | Promise<PrunelleChild>
12
+ | (() => PrunelleChild | Promise<PrunelleChild>)
13
+
14
+ export interface RenderedMail {
15
+ html: string
16
+ text: string
17
+ }
18
+
19
+ export interface MailMessage {
20
+ from?: MailAddress | undefined
21
+ to?: MailAddress | MailAddress[] | undefined
22
+ replyTo?: MailAddress | undefined
23
+ subject: string
24
+ /** Rendered into both `html` and a clean plain-text `text` fallback unless overridden by explicit `html`/`text`. */
25
+ body?: MailBody | undefined
26
+ text?: string | undefined
27
+ html?: string | undefined
28
+ }
29
+
30
+ export interface SentMail {
31
+ id: string
32
+ from: string
33
+ to: string[]
34
+ replyTo?: string | undefined
35
+ subject: string
36
+ text?: string | undefined
37
+ html?: string | undefined
38
+ sentAt: string
39
+ }
40
+
41
+ export interface MailTransport {
42
+ send(mail: SentMail): Promise<void>
43
+ }
44
+
45
+ export interface MailPreviewEntry {
46
+ name: string
47
+ subject?: string | undefined
48
+ props?: Record<string, unknown> | undefined
49
+ render: () => MailBody
50
+ }
51
+
52
+ export interface RenderedMailPreview {
53
+ name: string
54
+ subject: string
55
+ props?: Record<string, unknown> | undefined
56
+ html?: string | undefined
57
+ text?: string | undefined
58
+ error?: string | undefined
59
+ }
60
+
61
+ export interface MailPreviewOptions {
62
+ /** Dev outbox preview route (default: '/_pru/mail'). */
63
+ previewRoute?: string | undefined
64
+ /** Turns the outbox preview off; it is only ever mounted under `prunelle dev` or `NODE_ENV=test`, never in production or built servers outside test. */
65
+ preview?: false | undefined
66
+ /** Sample templates listed in the dev outbox (`/_pru/mail` and `/_pru/mail.json`) for live preview. */
67
+ previews?: readonly MailPreviewEntry[] | undefined
68
+ }
69
+
70
+ export interface MailRetryOptions extends JobsQueueOptions {
71
+ /** Queue name registered on `@prunellejs/jobs` (default `'mail.deliver'`). */
72
+ queue?: string | undefined
73
+ }
74
+
75
+ export interface MailerOptions extends MailPreviewOptions {
76
+ from?: MailAddress | undefined
77
+ to?: MailAddress | MailAddress[] | undefined
78
+ transport?: MailTransport | undefined
79
+ /** When true, missing transport in production drops mail instead of throwing MailNotConfiguredError; dev/test always uses outbox. */
80
+ optional?: boolean | undefined
81
+ /** Retry configuration passed to `@prunellejs/jobs` when registered (default `{ attempts: 3, backoff: 'exponential' }`). */
82
+ retries?: MailRetryOptions | undefined
83
+ /** When true and `@prunellejs/jobs` is registered, `send()` enqueues delivery asynchronously upfront instead of trying inline first. */
84
+ asyncQueue?: boolean | undefined
85
+ }
86
+
87
+ export interface MailPreviewRegisterOptions {
88
+ subject?: string | undefined
89
+ }
90
+
91
+ /** The plugin `prunelle.config.ts` registers for the dev outbox preview, and the handle routes and actions send with. */
92
+ export interface Mailer extends PrunellePlugin {
93
+ readonly outbox: SentMail[]
94
+ isConfigured(): boolean
95
+ clearOutbox(): void
96
+ send(message: MailMessage): Promise<SentMail>
97
+ preview(entry: MailPreviewEntry): void
98
+ preview(name: string, render: () => MailBody, options?: MailPreviewRegisterOptions): void
99
+ preview<P extends Record<string, unknown>>(
100
+ name: string,
101
+ component: (props: P) => PrunelleChild | Promise<PrunelleChild>,
102
+ sampleProps: P,
103
+ options?: MailPreviewRegisterOptions,
104
+ ): void
105
+ }
106
+
107
+ export class MailNotConfiguredError extends Error {
108
+ constructor(message = '@prunellejs/mail: no transport configured (set MAIL_URL, RESEND_API_KEY, or pass transport)') {
109
+ super(message)
110
+ this.name = 'MailNotConfiguredError'
111
+ }
112
+ }
113
+
114
+ const CR_LF_OR_NUL_RE = /[\r\n\0]/
115
+ const ANGLE_BRACKET_RE = /[<>]/
116
+ const NEEDS_DISPLAY_NAME_QUOTES_RE = /[^A-Za-z0-9 !#$%&'*+\-/=?^_`{|}~]/
117
+ const ANGLE_ADDR_RE = /<([^<>]+)>/
118
+
119
+ export function assertNoHeaderInjection(value: string, label: string): void {
120
+ if (CR_LF_OR_NUL_RE.test(value))
121
+ throw new RangeError(`@prunellejs/mail: ${label} must not contain CR, LF, or NUL characters`)
122
+ }
123
+
124
+ function escapeDisplayName(name: string): string {
125
+ const trimmed = name.trim()
126
+ if (trimmed.length === 0)
127
+ return ''
128
+ if (!NEEDS_DISPLAY_NAME_QUOTES_RE.test(trimmed))
129
+ return trimmed
130
+ return `"${trimmed.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
131
+ }
132
+
133
+ export function formatAddress(addr: MailAddress, label: string): string {
134
+ if (typeof addr === 'string') {
135
+ assertNoHeaderInjection(addr, label)
136
+ return addr
137
+ }
138
+ assertNoHeaderInjection(addr.name, `${label} name`)
139
+ assertNoHeaderInjection(addr.address, `${label} address`)
140
+ const address = addr.address.trim()
141
+ if (ANGLE_BRACKET_RE.test(address))
142
+ throw new RangeError(`@prunellejs/mail: ${label} address must not contain angle brackets`)
143
+ const displayName = escapeDisplayName(addr.name)
144
+ return displayName.length > 0 ? `${displayName} <${address}>` : address
145
+ }
146
+
147
+ export function normalizeList(to: MailAddress | MailAddress[] | undefined, label: string): string[] {
148
+ if (to === undefined)
149
+ return []
150
+ return Array.isArray(to) ? to.map(item => formatAddress(item, label)) : [formatAddress(to, label)]
151
+ }
152
+
153
+ /** Extracts the bare `local@domain` envelope address from `"Name <a@b>"` or `"a@b"`. */
154
+ export function extractEmailAddress(formatted: string): string {
155
+ assertNoHeaderInjection(formatted, 'address')
156
+ const match = ANGLE_ADDR_RE.exec(formatted)
157
+ const bare = (match !== null ? match[1]! : formatted).trim()
158
+ if (bare.length === 0 || ANGLE_BRACKET_RE.test(bare))
159
+ throw new RangeError(`@prunellejs/mail: invalid email address "${formatted}"`)
160
+ return bare
161
+ }