@prunellejs/mail 0.1.1 → 0.5.3

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,230 @@
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
+
9
+ export interface ResendOptions {
10
+ apiKey?: string | undefined
11
+ endpoint?: string | undefined
12
+ timeoutMs?: number | undefined
13
+ retries?: number | undefined
14
+ }
15
+
16
+ export interface PostmarkOptions {
17
+ serverToken?: string | undefined
18
+ endpoint?: string | undefined
19
+ timeoutMs?: number | undefined
20
+ retries?: number | undefined
21
+ messageStream?: string | undefined
22
+ }
23
+
24
+ /** 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. */
25
+ function retryDelayMs(res: Response | undefined, attempt: number): number {
26
+ const seconds = res !== undefined ? Number(res.headers.get('retry-after')) : Number.NaN
27
+ return Math.min(Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : 500 * 2 ** attempt, 5_000)
28
+ }
29
+
30
+ function isRetryableFetchError(error: unknown): boolean {
31
+ if (error !== null && typeof error === 'object' && 'code' in error && (error as { code?: unknown }).code === 'ERR_INVALID_URL')
32
+ return false
33
+ return true
34
+ }
35
+
36
+ async function sendJsonWithRetry(params: {
37
+ provider: string
38
+ endpoint: string
39
+ headers: Record<string, string>
40
+ body: string
41
+ timeoutMs: number
42
+ retries: number
43
+ }): Promise<void> {
44
+ const { provider, endpoint, headers, body, timeoutMs, retries } = params
45
+ for (let attempt = 0; ; attempt++) {
46
+ let res: Response
47
+ try {
48
+ res = await fetch(endpoint, {
49
+ method: 'POST',
50
+ headers,
51
+ body,
52
+ ...(timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}),
53
+ })
54
+ }
55
+ catch (error) {
56
+ if (!isRetryableFetchError(error) || attempt >= retries)
57
+ throw error
58
+ await Bun.sleep(retryDelayMs(undefined, attempt))
59
+ continue
60
+ }
61
+ if (res.ok)
62
+ return
63
+ const text = await res.text()
64
+ if ((res.status !== 429 && res.status < 500) || attempt >= retries)
65
+ throw new Error(`@prunellejs/mail (${provider}): HTTP ${res.status}: ${text}`)
66
+ await Bun.sleep(retryDelayMs(res, attempt))
67
+ }
68
+ }
69
+
70
+ /** 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. */
71
+ export function resend(options: ResendOptions = {}): MailTransport {
72
+ const endpoint = options.endpoint ?? 'https://api.resend.com/emails'
73
+ const timeoutMs = options.timeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS
74
+ const retries = options.retries ?? 2
75
+ return {
76
+ async send(mail: SentMail) {
77
+ const apiKey = options.apiKey ?? process.env.RESEND_API_KEY
78
+ if (!apiKey)
79
+ throw new MailNotConfiguredError('RESEND_API_KEY is not set')
80
+ const body = JSON.stringify({
81
+ from: mail.from,
82
+ to: mail.to,
83
+ reply_to: mail.replyTo,
84
+ subject: mail.subject,
85
+ text: mail.text,
86
+ html: mail.html,
87
+ })
88
+ await sendJsonWithRetry({
89
+ provider: 'resend',
90
+ endpoint,
91
+ headers: {
92
+ 'authorization': `Bearer ${apiKey}`,
93
+ 'content-type': 'application/json',
94
+ 'idempotency-key': mail.id,
95
+ },
96
+ body,
97
+ timeoutMs,
98
+ retries,
99
+ })
100
+ },
101
+ }
102
+ }
103
+
104
+ /** Zero-dependency Postmark HTTP transport using native fetch(); retries 429 and 5xx answers like `resend()`. */
105
+ export function postmark(options: PostmarkOptions = {}): MailTransport {
106
+ const endpoint = options.endpoint ?? 'https://api.postmarkapp.com/email'
107
+ const timeoutMs = options.timeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS
108
+ const retries = options.retries ?? 2
109
+ return {
110
+ async send(mail: SentMail) {
111
+ const serverToken = options.serverToken ?? process.env.POSTMARK_SERVER_TOKEN
112
+ if (!serverToken)
113
+ throw new MailNotConfiguredError('POSTMARK_SERVER_TOKEN is not set')
114
+ const body = JSON.stringify({
115
+ From: mail.from,
116
+ To: mail.to.join(', '),
117
+ ...(mail.replyTo !== undefined ? { ReplyTo: mail.replyTo } : {}),
118
+ Subject: mail.subject,
119
+ ...(mail.text !== undefined ? { TextBody: mail.text } : {}),
120
+ ...(mail.html !== undefined ? { HtmlBody: mail.html } : {}),
121
+ ...(options.messageStream !== undefined ? { MessageStream: options.messageStream } : {}),
122
+ })
123
+ await sendJsonWithRetry({
124
+ provider: 'postmark',
125
+ endpoint,
126
+ headers: {
127
+ 'accept': 'application/json',
128
+ 'content-type': 'application/json',
129
+ 'x-postmark-server-token': serverToken,
130
+ },
131
+ body,
132
+ timeoutMs,
133
+ retries,
134
+ })
135
+ },
136
+ }
137
+ }
138
+
139
+ function parseOptionalNumber(raw: string | null, label: string): number | undefined {
140
+ if (raw === null || raw === '')
141
+ return undefined
142
+ const num = Number(raw)
143
+ if (!Number.isFinite(num) || num < 0)
144
+ throw new RangeError(`@prunellejs/mail: invalid ${label} "${raw}" in MAIL_URL`)
145
+ return num
146
+ }
147
+
148
+ /** Extracts a case-preserving credential and optional custom endpoint from `resend://<key>` or `resend://:<key>@host/path`. */
149
+ function parseApiUrl(
150
+ rawUrl: string,
151
+ parsed: URL,
152
+ scheme: string,
153
+ defaultHost: string,
154
+ defaultPath: string,
155
+ ): { token: string, endpoint: string | undefined, timeoutMs: number | undefined, retries: number | undefined } {
156
+ const afterScheme = rawUrl.slice(`${scheme}//`.length)
157
+ const endIdx = afterScheme.search(/[/?#]/)
158
+ const authority = endIdx === -1 ? afterScheme : afterScheme.slice(0, endIdx)
159
+ const queryEndpoint = parsed.searchParams.get('endpoint') ?? undefined
160
+ const timeoutMs = parseOptionalNumber(parsed.searchParams.get('timeoutMs'), 'timeoutMs')
161
+ const retries = parseOptionalNumber(parsed.searchParams.get('retries'), 'retries')
162
+
163
+ let token: string
164
+ let endpoint = queryEndpoint
165
+
166
+ if (authority.includes('@')) {
167
+ token = decodeURIComponent(parsed.password || parsed.username)
168
+ if (endpoint === undefined && parsed.hostname.length > 0 && (parsed.hostname !== defaultHost || parsed.port !== '' || (parsed.pathname !== '' && parsed.pathname !== '/'))) {
169
+ const proto = parsed.searchParams.get('insecure') === 'true' ? 'http:' : 'https:'
170
+ const path = parsed.pathname === '' || parsed.pathname === '/' ? defaultPath : parsed.pathname
171
+ endpoint = `${proto}//${parsed.host}${path}`
172
+ }
173
+ }
174
+ else {
175
+ token = decodeURIComponent(authority)
176
+ }
177
+
178
+ if (token.length === 0)
179
+ throw new RangeError(`@prunellejs/mail: ${scheme}// URL is missing its API key / token`)
180
+
181
+ return { token, endpoint, timeoutMs, retries }
182
+ }
183
+
184
+ /** Builds a `MailTransport` from a `MAIL_URL` connection string (`smtp://`, `smtps://`, `resend://`, or `postmark://`). */
185
+ export function transportFromUrl(url: string): MailTransport {
186
+ const trimmed = url.trim()
187
+ let parsed: URL
188
+ try {
189
+ parsed = new URL(trimmed)
190
+ }
191
+ catch {
192
+ throw new RangeError(`@prunellejs/mail: invalid MAIL_URL "${url}"`)
193
+ }
194
+
195
+ const protocol = parsed.protocol.toLowerCase()
196
+
197
+ if (protocol === 'smtp:' || protocol === 'smtps:') {
198
+ const secure = protocol === 'smtps:'
199
+ const host = parsed.hostname
200
+ if (host.length === 0)
201
+ throw new RangeError(`@prunellejs/mail: ${protocol}// URL is missing a hostname`)
202
+ const port = parsed.port !== '' ? Number(parsed.port) : (secure ? 465 : 587)
203
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
204
+ throw new RangeError(`@prunellejs/mail: invalid SMTP port "${parsed.port}" in MAIL_URL`)
205
+ const tlsParam = parsed.searchParams.get('tls') ?? parsed.searchParams.get('starttls')
206
+ const requireTls = tlsParam === 'true' || tlsParam === '1' ? true : undefined
207
+ const disableStartTls = tlsParam === 'false' || tlsParam === '0'
208
+ const insecureAuthParam = parsed.searchParams.get('allowInsecureAuth')
209
+ const allowInsecureAuth = insecureAuthParam === 'true' || insecureAuthParam === '1' ? true : undefined
210
+ const rejectUnauthorized = parsed.searchParams.get('rejectUnauthorized') !== 'false'
211
+ const user = parsed.username !== '' ? decodeURIComponent(parsed.username) : undefined
212
+ const pass = parsed.password !== '' ? decodeURIComponent(parsed.password) : undefined
213
+ const ehloHost = parsed.searchParams.get('ehloHost') ?? undefined
214
+ const timeoutMs = parseOptionalNumber(parsed.searchParams.get('timeoutMs'), 'timeoutMs')
215
+ return smtp({ host, port, secure, requireTls, disableStartTls, allowInsecureAuth, rejectUnauthorized, user, pass, ehloHost, timeoutMs })
216
+ }
217
+
218
+ if (protocol === 'resend:') {
219
+ const { token, endpoint, timeoutMs, retries } = parseApiUrl(trimmed, parsed, 'resend:', 'api.resend.com', '/emails')
220
+ return resend({ apiKey: token, endpoint, timeoutMs, retries })
221
+ }
222
+
223
+ if (protocol === 'postmark:') {
224
+ const { token, endpoint, timeoutMs, retries } = parseApiUrl(trimmed, parsed, 'postmark:', 'api.postmarkapp.com', '/email')
225
+ const messageStream = parsed.searchParams.get('stream') ?? parsed.searchParams.get('messageStream') ?? undefined
226
+ return postmark({ serverToken: token, endpoint, timeoutMs, retries, messageStream })
227
+ }
228
+
229
+ throw new RangeError(`@prunellejs/mail: unsupported MAIL_URL protocol "${parsed.protocol}" (expected smtp:, smtps:, resend:, or postmark:)`)
230
+ }
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
+ }