@prunellejs/mail 0.7.4 → 0.8.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.
- package/llms.txt +5 -5
- package/package.json +2 -2
- package/src/index.ts +19 -6
- package/src/mime.ts +10 -2
- package/src/smtp.ts +9 -7
- package/src/transports.ts +9 -2
- package/src/types.ts +12 -0
package/llms.txt
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
## Imports
|
|
6
6
|
|
|
7
7
|
- `@prunellejs/mail`:
|
|
8
|
-
- Core: `createMailer`, `renderMail`, `htmlToText`, `MailNotConfiguredError`
|
|
8
|
+
- Core: `createMailer`, `renderMail`, `htmlToText`, `MailNotConfiguredError`, `MailDeliveryUnknownError`
|
|
9
9
|
- Transports: `smtp`, `resend`, `postmark`, `transportFromUrl`, `buildMimeMessage`, `dotStuffSmtpData`
|
|
10
10
|
- Components: `Email`, `Section`, `Heading`, `Text`, `Button`, `Divider`, `Footer`, `Link`
|
|
11
11
|
- Types: `Mailer`, `MailerOptions`, `MailPreviewOptions`, `MailPreviewEntry`, `MailPreviewRegisterOptions`, `MailRetryOptions`, `MailMessage`, `MailBody`, `RenderedMail`, `RenderedMailPreview`, `SentMail`, `MailAddress`, `MailTransport`, `SmtpOptions`, `ResendOptions`, `PostmarkOptions`, `EmailProps`, `SectionProps`, `HeadingProps`, `TextProps`, `ButtonProps`, `DividerProps`, `FooterProps`, `LinkProps`, `TextAlign`.
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
`createMailer()` returns a single object that is both the `PrunellePlugin` (register in `prunelle.config.ts`) and the handle routes/actions call `mail.send()` on:
|
|
16
16
|
|
|
17
|
-
- `from`: default sender (`string | { name, address }`, falls back to `process.env.MAIL_FROM`, then `'noreply@localhost
|
|
17
|
+
- `from`: default sender (`string | { name, address }`, falls back to `process.env.MAIL_FROM`, then `noreply@<host of the app's `site`>`, or `noreply@localhost` with no `site`, outside production: a production start refuses without one).
|
|
18
18
|
- `to`: default recipient(s) (falls back to `process.env.MAIL_TO`); `send()` with no recipient throws, in every mode.
|
|
19
19
|
- `transport`: `MailTransport` (`{ send(mail: SentMail): Promise<void> }`). Resolution order:
|
|
20
20
|
1. Explicit `options.transport`
|
|
@@ -37,12 +37,12 @@
|
|
|
37
37
|
## Transports & `MAIL_URL`
|
|
38
38
|
|
|
39
39
|
- `transportFromUrl(url)` supports:
|
|
40
|
-
- `smtp://[user:pass@]host[:port]` (default port 587; `STARTTLS` is required on a non-loopback host, so a server that does not offer it fails the send instead of getting the mail in plaintext; `?tls=true`/`?starttls=true` requires it on a loopback host too, `?tls=opportunistic` sends in plaintext when it is missing, `?tls=false` disables it, `?allowInsecureAuth=true` allows a plaintext send and plaintext `AUTH` on non-loopback hosts; any other `tls` value throws)
|
|
40
|
+
- `smtp://[user:pass@]host[:port]` (default port 587; `STARTTLS` is required on a non-loopback host, so a server that does not offer it fails the send instead of getting the mail in plaintext; `?tls=true`/`?starttls=true` requires it on a loopback host too, `?tls=opportunistic` sends in plaintext when it is missing (but never the credentials), `?tls=false` disables it, `?allowInsecureAuth=true` allows a plaintext send and plaintext `AUTH` on non-loopback hosts; any other `tls` value throws)
|
|
41
41
|
- `smtps://[user:pass@]host[:port]` (default port 465; implicit TLS)
|
|
42
42
|
- `resend://<apiKey>` or `resend://:<apiKey>@api.resend.com`
|
|
43
43
|
- `postmark://<serverToken>` or `postmark://:<serverToken>@api.postmarkapp.com`
|
|
44
|
-
- `smtp(options)` uses `Bun.connect` TCP/TLS sockets directly (zero npm dependencies): RFC 5321 multi-line parsing, `EHLO`, `STARTTLS` (with RFC 3207 response-injection protection and plaintext credential downgrade refusal on non-loopback hosts unless `allowInsecureAuth: true
|
|
45
|
-
- `resend({ apiKey?, endpoint?, timeoutMs?, retries? })` and `postmark({ serverToken?, endpoint?, timeoutMs?, retries?, messageStream? })` use native `fetch()` with a timeout. `resend()` retries `429`/`5xx` and transient network/timeout errors under an idempotency key; `postmark()` has none, so it retries only `429
|
|
44
|
+
- `smtp(options)` uses `Bun.connect` TCP/TLS sockets directly (zero npm dependencies): RFC 5321 multi-line parsing, `EHLO` (announcing `ehloHost`, else the domain of the From address, else `localhost`; the same domain ends each `Message-ID`), `STARTTLS` (with RFC 3207 response-injection protection and plaintext credential downgrade refusal on non-loopback hosts unless `allowInsecureAuth: true`, which `requireTls: false` does not imply), `AUTH PLAIN` / `AUTH LOGIN`, `MAIL FROM`, `RCPT TO`, `DATA` with CRLF normalization + dot-stuffing, MIME `multipart/alternative`, and `QUIT`. Bodies go out as quoted-printable (7-bit, lines of at most 76 characters), headers are folded at 78, a non-ASCII display name or subject becomes RFC 2047 encoded words of at most 75 characters, and once the server accepts the data a failing `QUIT` does not fail the send.
|
|
45
|
+
- `resend({ apiKey?, endpoint?, timeoutMs?, retries? })` and `postmark({ serverToken?, endpoint?, timeoutMs?, retries?, messageStream? })` use native `fetch()` with a timeout. `resend()` retries `429`/`5xx` and transient network/timeout errors under an idempotency key; `postmark()` has none, so it retries only `429`, and a `5xx` or timeout throws `MailDeliveryUnknownError` (`retryable: false`): the queue marks the job `failed` after one attempt and logs the mail, `send()` does not enqueue a retry. Provider error bodies are cut to 200 characters, a malformed `MAIL_URL` is not echoed, and Resend and Postmark are US processors (DPA with SCCs and DPF, see the docs: a transfer outside the EU).
|
|
46
46
|
- `smtp({ maxConnections? (4), deadlineMs? (60_000) })`: connections open at once and the longest a send may take; a reply past 64 KiB drops the connection. `buildMimeMessage` throws on a line break in an address, subject or id, and `<Link>`/`<Button>` refuse `//host`, control characters and backslashes in `href`.
|
|
47
47
|
|
|
48
48
|
## Mounted Routes (`prunelle dev` or `NODE_ENV=test` only — never in production or built servers outside test)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/mail",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Zero-dependency email delivery (JSX/TSX templates, SMTP/SMTPS, Resend, Postmark, MAIL_URL, @prunellejs/jobs retries) and dev outbox/preview plugin for Prunelle",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -21,6 +21,6 @@
|
|
|
21
21
|
"directory": "packages/plugin-mail"
|
|
22
22
|
},
|
|
23
23
|
"peerDependencies": {
|
|
24
|
-
"prunelle": "^0.
|
|
24
|
+
"prunelle": "^0.8.0"
|
|
25
25
|
}
|
|
26
26
|
}
|
package/src/index.ts
CHANGED
|
@@ -11,7 +11,7 @@ import { setAppLang } from './components'
|
|
|
11
11
|
import { renderOutboxHtml, renderPreviewEntries } from './preview'
|
|
12
12
|
import { renderMail } from './render'
|
|
13
13
|
import { resend, transportFromUrl } from './transports'
|
|
14
|
-
import { assertNoHeaderInjection, formatAddress, MailNotConfiguredError, normalizeList } from './types'
|
|
14
|
+
import { assertNoHeaderInjection, formatAddress, MailDeliveryUnknownError, MailNotConfiguredError, normalizeList } from './types'
|
|
15
15
|
|
|
16
16
|
export { Button, Divider, Email, Footer, Heading, Link, Section, Text } from './components'
|
|
17
17
|
export type { ButtonProps, DividerProps, EmailProps, FooterProps, HeadingProps, LinkProps, SectionProps, TextAlign, TextProps } from './components'
|
|
@@ -20,12 +20,16 @@ export { buildMimeMessage, dotStuffSmtpData, smtp } from './smtp'
|
|
|
20
20
|
export type { SmtpOptions } from './smtp'
|
|
21
21
|
export { postmark, resend, transportFromUrl } from './transports'
|
|
22
22
|
export type { PostmarkOptions, ResendOptions } from './transports'
|
|
23
|
-
export { MailNotConfiguredError } from './types'
|
|
23
|
+
export { MailDeliveryUnknownError, MailNotConfiguredError } from './types'
|
|
24
24
|
export type { MailAddress, MailBody, Mailer, MailerOptions, MailMessage, MailPreviewEntry, MailPreviewOptions, MailPreviewRegisterOptions, MailRetryOptions, MailTransport, RenderedMail, RenderedMailPreview, SentMail } from './types'
|
|
25
25
|
|
|
26
26
|
const DEFAULT_QUEUE_NAME = 'mail.deliver'
|
|
27
27
|
const DEFAULT_RETRY_OPTIONS: JobsQueueOptions = { attempts: 3, backoff: 'exponential' }
|
|
28
28
|
|
|
29
|
+
function hostOf(site: string | undefined): string | undefined {
|
|
30
|
+
return site !== undefined && URL.canParse(site) ? new URL(site).hostname : undefined
|
|
31
|
+
}
|
|
32
|
+
|
|
29
33
|
function isDevOrTest(devFlag: boolean): boolean {
|
|
30
34
|
const env = nodeEnv()
|
|
31
35
|
if (env === 'production')
|
|
@@ -108,7 +112,7 @@ async function deliverRecord(params: {
|
|
|
108
112
|
await transport.send(record)
|
|
109
113
|
}
|
|
110
114
|
catch (error) {
|
|
111
|
-
if (jobs !== undefined) {
|
|
115
|
+
if (jobs !== undefined && !(error instanceof MailDeliveryUnknownError)) {
|
|
112
116
|
await jobs.enqueue(queueName, record, { key: record.id })
|
|
113
117
|
return
|
|
114
118
|
}
|
|
@@ -127,6 +131,7 @@ export function createMailer(options: MailerOptions = {}): Mailer {
|
|
|
127
131
|
}
|
|
128
132
|
|
|
129
133
|
let serverDev: boolean | undefined
|
|
134
|
+
let siteHost: string | undefined
|
|
130
135
|
let injectJobs: (() => JobsService | undefined) | undefined
|
|
131
136
|
const registeredJobs = new WeakSet<JobsService>()
|
|
132
137
|
const getTransport = createTransportResolver(options.transport)
|
|
@@ -141,7 +146,14 @@ export function createMailer(options: MailerOptions = {}): Mailer {
|
|
|
141
146
|
const transport = getTransport()
|
|
142
147
|
if (transport === undefined)
|
|
143
148
|
throw new MailNotConfiguredError()
|
|
144
|
-
|
|
149
|
+
try {
|
|
150
|
+
await transport.send(record)
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
if (error instanceof MailDeliveryUnknownError)
|
|
154
|
+
console.error(`@prunellejs/mail: mail ${record.id} is marked failed and will not be retried, as it may already have been sent: ${error.message}`)
|
|
155
|
+
throw error
|
|
156
|
+
}
|
|
145
157
|
}, queueOpts)
|
|
146
158
|
}
|
|
147
159
|
return svc
|
|
@@ -152,6 +164,7 @@ export function createMailer(options: MailerOptions = {}): Mailer {
|
|
|
152
164
|
after: ['@prunellejs/jobs'],
|
|
153
165
|
server(api) {
|
|
154
166
|
serverDev = api.dev
|
|
167
|
+
siteHost = hostOf(api.site)
|
|
155
168
|
setAppLang(typeof api.config?.lang === 'string' ? api.config.lang : undefined)
|
|
156
169
|
injectJobs = () => api.inject(JOBS_SERVICE)
|
|
157
170
|
ensureJobsQueue()
|
|
@@ -190,7 +203,7 @@ export function createMailer(options: MailerOptions = {}): Mailer {
|
|
|
190
203
|
if (getTransport() === undefined && !options.optional)
|
|
191
204
|
unmet.push('no transport, so every send() throws: set `MAIL_URL` or `RESEND_API_KEY`, or pass `transport` to `createMailer()` (`optional: true` drops mail instead).')
|
|
192
205
|
if ((options.from ?? process.env.MAIL_FROM) === undefined)
|
|
193
|
-
unmet.push('no sender, so mail goes out from noreply@localhost: set `MAIL_FROM`, or pass `from` to `createMailer()`.')
|
|
206
|
+
unmet.push('no sender, so mail goes out from noreply@<your site host> (noreply@localhost with no `site`): set `MAIL_FROM`, or pass `from` to `createMailer()`.')
|
|
194
207
|
return unmet
|
|
195
208
|
},
|
|
196
209
|
clearOutbox() {
|
|
@@ -211,7 +224,7 @@ export function createMailer(options: MailerOptions = {}): Mailer {
|
|
|
211
224
|
},
|
|
212
225
|
async send(message: MailMessage) {
|
|
213
226
|
assertNoHeaderInjection(message.subject, 'subject')
|
|
214
|
-
const from = message.from ?? options.from ?? process.env.MAIL_FROM ?? '
|
|
227
|
+
const from = message.from ?? options.from ?? process.env.MAIL_FROM ?? `noreply@${siteHost ?? 'localhost'}`
|
|
215
228
|
const toList = normalizeList(message.to ?? options.to ?? process.env.MAIL_TO, 'to')
|
|
216
229
|
if (toList.length === 0)
|
|
217
230
|
throw new Error(`@prunellejs/mail: send({ subject: ${JSON.stringify(message.subject)} }) has no recipient: give it \`to\`, pass \`to\` to \`createMailer()\`, or set \`MAIL_TO\`.`)
|
package/src/mime.ts
CHANGED
|
@@ -13,6 +13,7 @@ const QP_LINE_MAX = 76
|
|
|
13
13
|
const HEADER_TOKEN_RE = /([ \t]*)([^ \t]+)/g
|
|
14
14
|
const ANGLE_ADDRESS_RE = /^\s*(.*?)\s*(<[^<>]+>)\s*$/
|
|
15
15
|
const QUOTED_NAME_RE = /^"(.*)"$/
|
|
16
|
+
const DOMAIN_RE = /^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/
|
|
16
17
|
|
|
17
18
|
export function validateEhloHost(value: string): string {
|
|
18
19
|
assertNoHeaderInjection(value, 'ehloHost')
|
|
@@ -21,6 +22,13 @@ export function validateEhloHost(value: string): string {
|
|
|
21
22
|
return value
|
|
22
23
|
}
|
|
23
24
|
|
|
25
|
+
/** The ASCII domain of a `From` value (`Name <a@b.test>` or `a@b.test`), or `undefined` when it has none. */
|
|
26
|
+
export function mailDomain(from: string): string | undefined {
|
|
27
|
+
const bare = ANGLE_ADDRESS_RE.exec(from)?.[2]?.slice(1, -1) ?? from
|
|
28
|
+
const domain = bare.slice(bare.lastIndexOf('@') + 1).trim()
|
|
29
|
+
return bare.includes('@') && DOMAIN_RE.test(domain) ? domain : undefined
|
|
30
|
+
}
|
|
31
|
+
|
|
24
32
|
/** Splits non-ASCII text into space-separated RFC 2047 encoded words, never cutting a UTF-8 sequence. */
|
|
25
33
|
function encodeRfc2047(value: string): string {
|
|
26
34
|
if (!NON_ASCII_RE.test(value))
|
|
@@ -115,8 +123,8 @@ export function dotStuffSmtpData(rawMessage: string): string {
|
|
|
115
123
|
}
|
|
116
124
|
|
|
117
125
|
/** Builds an RFC 5322 + MIME message (using `multipart/alternative` when both `text` and `html` are present). */
|
|
118
|
-
export function buildMimeMessage(mail: SentMail, domain
|
|
119
|
-
const safeDomain = validateEhloHost(domain)
|
|
126
|
+
export function buildMimeMessage(mail: SentMail, domain?: string): string {
|
|
127
|
+
const safeDomain = validateEhloHost(domain ?? mailDomain(mail.from) ?? 'localhost')
|
|
120
128
|
for (const [label, value] of [['from', mail.from], ['replyTo', mail.replyTo ?? ''], ['subject', mail.subject], ['id', mail.id], ...mail.to.map(to => ['to', to] as const)] as const)
|
|
121
129
|
assertNoHeaderInjection(value, label)
|
|
122
130
|
const headers = [
|
package/src/smtp.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import type { Socket, SocketHandler, TLSOptions } from 'bun'
|
|
5
5
|
import type { MailTransport, SentMail } from './types'
|
|
6
6
|
import { isLoopbackHost } from 'prunelle/internal/server'
|
|
7
|
-
import { buildMimeMessage, dotStuffSmtpData, validateEhloHost } from './mime'
|
|
7
|
+
import { buildMimeMessage, dotStuffSmtpData, mailDomain, validateEhloHost } from './mime'
|
|
8
8
|
import { extractEmailAddress } from './types'
|
|
9
9
|
|
|
10
10
|
export { buildMimeMessage, dotStuffSmtpData } from './mime'
|
|
@@ -18,13 +18,13 @@ export interface SmtpOptions {
|
|
|
18
18
|
requireTls?: boolean | undefined
|
|
19
19
|
/** Disable automatic STARTTLS even when the server advertises it. */
|
|
20
20
|
disableStartTls?: boolean | undefined
|
|
21
|
-
/** Allow sending SMTP AUTH credentials over an unencrypted non-loopback connection (default `false`). */
|
|
21
|
+
/** Allow sending SMTP AUTH credentials over an unencrypted non-loopback connection (default `false`); `requireTls: false` alone does not. */
|
|
22
22
|
allowInsecureAuth?: boolean | undefined
|
|
23
23
|
/** Verify the server TLS certificate (default `true`). */
|
|
24
24
|
rejectUnauthorized?: boolean | undefined
|
|
25
25
|
user?: string | undefined
|
|
26
26
|
pass?: string | undefined
|
|
27
|
-
/** Hostname announced in `EHLO` (default `'localhost'`). */
|
|
27
|
+
/** Hostname announced in `EHLO` and used in `Message-ID` (default: the domain of the mail's From address, else `'localhost'`). */
|
|
28
28
|
ehloHost?: string | undefined
|
|
29
29
|
/** Socket read/connect timeout in milliseconds (default `15_000`). */
|
|
30
30
|
timeoutMs?: number | undefined
|
|
@@ -184,6 +184,8 @@ class SmtpConnection {
|
|
|
184
184
|
}
|
|
185
185
|
else {
|
|
186
186
|
this.unexpectedLines++
|
|
187
|
+
// Not part of a reply, so it counts only while it is on the wire, not against the replies after it.
|
|
188
|
+
this.replyBytes = Math.max(0, this.replyBytes - lineBytes)
|
|
187
189
|
}
|
|
188
190
|
return
|
|
189
191
|
}
|
|
@@ -462,7 +464,7 @@ export function smtp(options: SmtpOptions): MailTransport {
|
|
|
462
464
|
throw new RangeError('@prunellejs/mail (smtp): `host` must be a non-empty hostname')
|
|
463
465
|
const secure = options.secure ?? options.port === 465
|
|
464
466
|
const port = options.port ?? (secure ? 465 : 587)
|
|
465
|
-
const
|
|
467
|
+
const configuredEhloHost = options.ehloHost === undefined ? undefined : validateEhloHost(options.ehloHost)
|
|
466
468
|
if (!secure && options.requireTls === true && options.disableStartTls === true)
|
|
467
469
|
throw new RangeError('@prunellejs/mail (smtp): cannot set both `requireTls` and `disableStartTls`')
|
|
468
470
|
const requireTls = options.requireTls ?? !(options.allowInsecureAuth === true || isLoopbackHost(host))
|
|
@@ -478,6 +480,7 @@ export function smtp(options: SmtpOptions): MailTransport {
|
|
|
478
480
|
async send(mail: SentMail): Promise<void> {
|
|
479
481
|
const envelopeFrom = extractEmailAddress(mail.from)
|
|
480
482
|
const envelopeTo = mail.to.map(extractEmailAddress)
|
|
483
|
+
const ehloHost = configuredEhloHost ?? mailDomain(mail.from) ?? 'localhost'
|
|
481
484
|
const message = buildMimeMessage(mail, ehloHost)
|
|
482
485
|
await connections.acquire()
|
|
483
486
|
const conn = new SmtpConnection(timeoutMs)
|
|
@@ -505,9 +508,8 @@ export function smtp(options: SmtpOptions): MailTransport {
|
|
|
505
508
|
}
|
|
506
509
|
|
|
507
510
|
if (options.user !== undefined || options.pass !== undefined) {
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
throw new Error('@prunellejs/mail (smtp): refusing to send AUTH credentials over an unencrypted connection; server did not upgrade via STARTTLS (set `allowInsecureAuth: true` or `requireTls: false` to override)')
|
|
511
|
+
if (!encrypted && !isLoopbackHost(host) && options.allowInsecureAuth !== true)
|
|
512
|
+
throw new Error('@prunellejs/mail (smtp): refusing to send AUTH credentials over an unencrypted connection, as the server did not upgrade via STARTTLS: enable STARTTLS on the server, or set `allowInsecureAuth: true` (MAIL_URL `?allowInsecureAuth=true`) to send the password in clear')
|
|
511
513
|
await authenticateSmtp(conn, caps.authMethods, options.user ?? '', options.pass ?? '')
|
|
512
514
|
}
|
|
513
515
|
|
package/src/transports.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import type { MailTransport, SentMail } from './types'
|
|
4
4
|
import { smtp } from './smtp'
|
|
5
|
-
import { MailNotConfiguredError } from './types'
|
|
5
|
+
import { MailDeliveryUnknownError, MailNotConfiguredError } from './types'
|
|
6
6
|
|
|
7
7
|
const DEFAULT_HTTP_TIMEOUT_MS = 10_000
|
|
8
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.
|
|
@@ -37,6 +37,7 @@ function isRetryableFetchError(error: unknown): boolean {
|
|
|
37
37
|
|
|
38
38
|
async function sendJsonWithRetry(params: {
|
|
39
39
|
provider: string
|
|
40
|
+
mailId: string
|
|
40
41
|
endpoint: string
|
|
41
42
|
headers: Record<string, string>
|
|
42
43
|
body: string
|
|
@@ -45,7 +46,7 @@ async function sendJsonWithRetry(params: {
|
|
|
45
46
|
/** Whether the provider drops a repeated send (an idempotency key); without it only a 429, which sent nothing, is retried. */
|
|
46
47
|
idempotent: boolean
|
|
47
48
|
}): Promise<void> {
|
|
48
|
-
const { provider, endpoint, headers, body, timeoutMs, retries, idempotent } = params
|
|
49
|
+
const { provider, mailId, endpoint, headers, body, timeoutMs, retries, idempotent } = params
|
|
49
50
|
for (let attempt = 0; ; attempt++) {
|
|
50
51
|
let res: Response
|
|
51
52
|
try {
|
|
@@ -57,6 +58,8 @@ async function sendJsonWithRetry(params: {
|
|
|
57
58
|
})
|
|
58
59
|
}
|
|
59
60
|
catch (error) {
|
|
61
|
+
if (!idempotent && isRetryableFetchError(error))
|
|
62
|
+
throw new MailDeliveryUnknownError(provider, mailId, error instanceof Error ? error.message : String(error))
|
|
60
63
|
if (!idempotent || !isRetryableFetchError(error) || attempt >= retries)
|
|
61
64
|
throw error
|
|
62
65
|
await Bun.sleep(retryDelayMs(undefined, attempt))
|
|
@@ -65,6 +68,8 @@ async function sendJsonWithRetry(params: {
|
|
|
65
68
|
if (res.ok)
|
|
66
69
|
return
|
|
67
70
|
const text = (await res.text()).slice(0, ERROR_BODY_MAX_CHARS)
|
|
71
|
+
if (!idempotent && res.status >= 500)
|
|
72
|
+
throw new MailDeliveryUnknownError(provider, mailId, `HTTP ${res.status}: ${text}`)
|
|
68
73
|
const retryable = res.status === 429 || (idempotent && res.status >= 500)
|
|
69
74
|
if (!retryable || attempt >= retries)
|
|
70
75
|
throw new Error(`@prunellejs/mail (${provider}): HTTP ${res.status}: ${text}`)
|
|
@@ -92,6 +97,7 @@ export function resend(options: ResendOptions = {}): MailTransport {
|
|
|
92
97
|
})
|
|
93
98
|
await sendJsonWithRetry({
|
|
94
99
|
provider: 'resend',
|
|
100
|
+
mailId: mail.id,
|
|
95
101
|
endpoint,
|
|
96
102
|
headers: {
|
|
97
103
|
'authorization': `Bearer ${apiKey}`,
|
|
@@ -128,6 +134,7 @@ export function postmark(options: PostmarkOptions = {}): MailTransport {
|
|
|
128
134
|
})
|
|
129
135
|
await sendJsonWithRetry({
|
|
130
136
|
provider: 'postmark',
|
|
137
|
+
mailId: mail.id,
|
|
131
138
|
endpoint,
|
|
132
139
|
headers: {
|
|
133
140
|
'accept': 'application/json',
|
package/src/types.ts
CHANGED
|
@@ -111,6 +111,18 @@ export class MailNotConfiguredError extends Error {
|
|
|
111
111
|
}
|
|
112
112
|
}
|
|
113
113
|
|
|
114
|
+
/** A transport throws this when the provider may have sent the mail (a timeout, or a 5xx after the request went out): `retryable: false` makes the queue fail the job at once instead of sending the mail twice. */
|
|
115
|
+
export class MailDeliveryUnknownError extends Error {
|
|
116
|
+
readonly retryable = false
|
|
117
|
+
readonly mailId: string
|
|
118
|
+
|
|
119
|
+
constructor(provider: string, mailId: string, reason: string) {
|
|
120
|
+
super(`@prunellejs/mail (${provider}): mail ${mailId} may have been sent (${reason}), so it is not retried: check the provider's dashboard before sending it again`)
|
|
121
|
+
this.name = 'MailDeliveryUnknownError'
|
|
122
|
+
this.mailId = mailId
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
114
126
|
const CR_LF_OR_NUL_RE = /[\r\n\0]/
|
|
115
127
|
const ANGLE_BRACKET_RE = /[<>]/
|
|
116
128
|
const NEEDS_DISPLAY_NAME_QUOTES_RE = /[^A-Za-z0-9 !#$%&'*+\-/=?^_`{|}~]/
|