@prunellejs/mail 0.1.1 → 0.7.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.
package/src/index.ts CHANGED
@@ -1,167 +1,186 @@
1
- // @prunellejs/mail — Lightweight email delivery (Resend / custom transport / dev outbox) + `/_pru/mail` preview plugin.
2
- // Built strictly on the public PrunellePlugin API (server(api).route).
1
+ // @prunellejs/mail — Zero-dependency email delivery (JSX/TSX templates, SMTP/SMTPS, Resend, Postmark, MAIL_URL, @prunellejs/jobs retries) + `/_pru/mail` dev outbox & template previews.
2
+ // Built strictly on the public PrunellePlugin API (`server(api).route`, `api.inject(JOBS_SERVICE)`).
3
3
 
4
- import type { PrunellePlugin } from 'prunelle/config'
5
- import { definePlugin } from 'prunelle/config'
6
- import { esc, escAttr, nodeEnv } from 'prunelle/server'
4
+ import type { JobsQueueOptions, JobsService } from 'prunelle/config'
5
+ import type { PrunelleChild } from 'prunelle/jsx-runtime'
6
+ import type { MailBody, Mailer, MailerOptions, MailMessage, MailPreviewEntry, MailPreviewRegisterOptions, MailTransport, SentMail } from './types'
7
+ import { definePlugin, JOBS_SERVICE } from 'prunelle/config'
8
+ import { devFromEnv } from 'prunelle/internal/server'
9
+ import { nodeEnv } from 'prunelle/server'
10
+ import { setAppLang } from './components'
11
+ import { renderOutboxHtml, renderPreviewEntries } from './preview'
12
+ import { renderMail } from './render'
13
+ import { resend, transportFromUrl } from './transports'
14
+ import { assertNoHeaderInjection, formatAddress, MailNotConfiguredError, normalizeList } from './types'
7
15
 
8
- export type MailAddress = string | { name: string, address: string }
16
+ export { Button, Divider, Email, Footer, Heading, Link, Section, Text } from './components'
17
+ export type { ButtonProps, DividerProps, EmailProps, FooterProps, HeadingProps, LinkProps, SectionProps, TextAlign, TextProps } from './components'
18
+ export { htmlToText, renderMail } from './render'
19
+ export { buildMimeMessage, dotStuffSmtpData, smtp } from './smtp'
20
+ export type { SmtpOptions } from './smtp'
21
+ export { postmark, resend, transportFromUrl } from './transports'
22
+ export type { PostmarkOptions, ResendOptions } from './transports'
23
+ export { MailNotConfiguredError } from './types'
24
+ export type { MailAddress, MailBody, Mailer, MailerOptions, MailMessage, MailPreviewEntry, MailPreviewOptions, MailPreviewRegisterOptions, MailRetryOptions, MailTransport, RenderedMail, RenderedMailPreview, SentMail } from './types'
9
25
 
10
- export interface MailMessage {
11
- from?: MailAddress | undefined
12
- to?: MailAddress | MailAddress[] | undefined
13
- replyTo?: MailAddress | undefined
14
- subject: string
15
- text?: string | undefined
16
- html?: string | undefined
17
- }
18
-
19
- export interface SentMail {
20
- id: string
21
- from: string
22
- to: string[]
23
- replyTo?: string | undefined
24
- subject: string
25
- text?: string | undefined
26
- html?: string | undefined
27
- sentAt: string
28
- }
29
-
30
- export interface MailTransport {
31
- send(mail: SentMail): Promise<void>
32
- }
33
-
34
- export class MailNotConfiguredError extends Error {
35
- constructor(message = '@prunellejs/mail: no transport configured (set RESEND_API_KEY or pass transport)') {
36
- super(message)
37
- this.name = 'MailNotConfiguredError'
38
- }
39
- }
40
-
41
- const CR_LF_OR_NUL_RE = /[\r\n\0]/
42
- const ANGLE_BRACKET_RE = /[<>]/
43
- const NEEDS_DISPLAY_NAME_QUOTES_RE = /[^A-Za-z0-9 !#$%&'*+\-/=?^_`{|}~]/
44
- const DEFAULT_RESEND_TIMEOUT_MS = 10_000
45
-
46
- function assertNoHeaderInjection(value: string, label: string): void {
47
- if (CR_LF_OR_NUL_RE.test(value))
48
- throw new RangeError(`@prunellejs/mail: ${label} must not contain CR, LF, or NUL characters`)
49
- }
50
-
51
- function escapeDisplayName(name: string): string {
52
- const trimmed = name.trim()
53
- if (trimmed.length === 0)
54
- return ''
55
- if (!NEEDS_DISPLAY_NAME_QUOTES_RE.test(trimmed))
56
- return trimmed
57
- return `"${trimmed.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
58
- }
59
-
60
- function formatAddress(addr: MailAddress, label: string): string {
61
- if (typeof addr === 'string') {
62
- assertNoHeaderInjection(addr, label)
63
- return addr
64
- }
65
- assertNoHeaderInjection(addr.name, `${label} name`)
66
- assertNoHeaderInjection(addr.address, `${label} address`)
67
- const address = addr.address.trim()
68
- if (ANGLE_BRACKET_RE.test(address))
69
- throw new RangeError(`@prunellejs/mail: ${label} address must not contain angle brackets`)
70
- const displayName = escapeDisplayName(addr.name)
71
- return displayName.length > 0 ? `${displayName} <${address}>` : address
72
- }
73
-
74
- function normalizeList(to: MailAddress | MailAddress[] | undefined, label: string): string[] {
75
- if (to === undefined)
76
- return []
77
- return Array.isArray(to) ? to.map(item => formatAddress(item, label)) : [formatAddress(to, label)]
78
- }
26
+ const DEFAULT_QUEUE_NAME = 'mail.deliver'
27
+ const DEFAULT_RETRY_OPTIONS: JobsQueueOptions = { attempts: 3, backoff: 'exponential' }
79
28
 
80
29
  function isDevOrTest(devFlag: boolean): boolean {
81
30
  const env = nodeEnv()
82
31
  if (env === 'production')
83
32
  return false
84
- return devFlag || env === 'development' || env === 'test'
33
+ return devFlag || env === 'test'
85
34
  }
86
35
 
87
- /** 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. */
88
- function resendRetryDelay(res: Response, attempt: number): number {
89
- const seconds = Number(res.headers.get('retry-after'))
90
- return Math.min(Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : 500 * 2 ** attempt, 5_000)
91
- }
36
+ function toPreviewEntry(
37
+ nameOrEntry: string | MailPreviewEntry,
38
+ renderOrComponent?: ((props?: Record<string, unknown>) => MailBody) | (() => MailBody),
39
+ samplePropsOrOptions?: Record<string, unknown> | MailPreviewRegisterOptions,
40
+ options?: MailPreviewRegisterOptions,
41
+ ): MailPreviewEntry {
42
+ if (typeof nameOrEntry !== 'string')
43
+ return nameOrEntry
44
+ if (typeof renderOrComponent !== 'function')
45
+ throw new TypeError('@prunellejs/mail: preview() requires a render function or component')
92
46
 
93
- /** 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. */
94
- export function resend(options: { apiKey?: string | undefined, endpoint?: string | undefined, timeoutMs?: number | undefined, retries?: number | undefined } = {}): MailTransport {
95
- const endpoint = options.endpoint ?? 'https://api.resend.com/emails'
96
- const timeoutMs = options.timeoutMs ?? DEFAULT_RESEND_TIMEOUT_MS
97
- const retries = options.retries ?? 2
47
+ // Distinguish `preview(name, () => <T />, { subject })` from `preview(name, Comp, { ...sampleProps }, { subject })`.
48
+ const hasExplicitProps = options !== undefined || (samplePropsOrOptions !== undefined && renderOrComponent.length > 0)
49
+ if (hasExplicitProps) {
50
+ const props = samplePropsOrOptions as Record<string, unknown>
51
+ return {
52
+ name: nameOrEntry,
53
+ subject: options?.subject,
54
+ props,
55
+ render: () => (renderOrComponent as (p: Record<string, unknown>) => PrunelleChild | Promise<PrunelleChild>)(props),
56
+ }
57
+ }
58
+ const opts = samplePropsOrOptions as MailPreviewRegisterOptions | undefined
98
59
  return {
99
- async send(mail) {
100
- const apiKey = options.apiKey ?? process.env.RESEND_API_KEY
101
- if (!apiKey)
102
- throw new MailNotConfiguredError('RESEND_API_KEY is not set')
103
- const body = JSON.stringify({
104
- from: mail.from,
105
- to: mail.to,
106
- reply_to: mail.replyTo,
107
- subject: mail.subject,
108
- text: mail.text,
109
- html: mail.html,
110
- })
111
- for (let attempt = 0; ; attempt++) {
112
- const res = await fetch(endpoint, {
113
- method: 'POST',
114
- headers: {
115
- 'authorization': `Bearer ${apiKey}`,
116
- 'content-type': 'application/json',
117
- 'idempotency-key': mail.id,
118
- },
119
- body,
120
- ...(timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}),
121
- })
122
- if (res.ok)
123
- return
124
- const text = await res.text()
125
- if ((res.status !== 429 && res.status < 500) || attempt >= retries)
126
- throw new Error(`@prunellejs/mail (resend): HTTP ${res.status}: ${text}`)
127
- await Bun.sleep(resendRetryDelay(res, attempt))
128
- }
129
- },
60
+ name: nameOrEntry,
61
+ subject: opts?.subject,
62
+ render: renderOrComponent as () => MailBody,
130
63
  }
131
64
  }
132
65
 
133
- export interface MailerOptions extends MailPreviewOptions {
134
- from?: MailAddress | undefined
135
- to?: MailAddress | MailAddress[] | undefined
136
- transport?: MailTransport | undefined
137
- /** When true, missing transport in production throws MailNotConfiguredError; dev/test always uses outbox. */
138
- optional?: boolean | undefined
66
+ function createTransportResolver(explicitTransport: MailTransport | undefined): () => MailTransport | undefined {
67
+ let cachedMailUrl: string | undefined
68
+ let cachedUrlTransport: MailTransport | undefined
69
+ return () => {
70
+ if (explicitTransport !== undefined)
71
+ return explicitTransport
72
+ const envUrl = process.env.MAIL_URL
73
+ if (envUrl) {
74
+ if (envUrl !== cachedMailUrl) {
75
+ cachedUrlTransport = transportFromUrl(envUrl)
76
+ cachedMailUrl = envUrl
77
+ }
78
+ return cachedUrlTransport
79
+ }
80
+ if (process.env.RESEND_API_KEY)
81
+ return resend({ apiKey: process.env.RESEND_API_KEY })
82
+ return undefined
83
+ }
139
84
  }
140
85
 
141
- /** The plugin `prunelle.config.ts` registers for the dev outbox preview, and the handle routes and actions send with. */
142
- export interface Mailer extends PrunellePlugin {
143
- readonly outbox: SentMail[]
144
- isConfigured(): boolean
145
- clearOutbox(): void
146
- send(message: MailMessage): Promise<SentMail>
86
+ async function deliverRecord(params: {
87
+ record: SentMail
88
+ transport: MailTransport | undefined
89
+ devOrTest: boolean
90
+ optional: boolean
91
+ asyncQueue: boolean
92
+ queueName: string
93
+ jobs: JobsService | undefined
94
+ }): Promise<void> {
95
+ const { record, transport, devOrTest, optional, asyncQueue, queueName, jobs } = params
96
+ if (transport === undefined) {
97
+ if (!devOrTest && !optional)
98
+ throw new MailNotConfiguredError()
99
+ return
100
+ }
101
+
102
+ if (jobs !== undefined && asyncQueue) {
103
+ await jobs.enqueue(queueName, record, { key: record.id })
104
+ return
105
+ }
106
+
107
+ try {
108
+ await transport.send(record)
109
+ }
110
+ catch (error) {
111
+ if (jobs !== undefined) {
112
+ await jobs.enqueue(queueName, record, { key: record.id })
113
+ return
114
+ }
115
+ throw error
116
+ }
147
117
  }
148
118
 
149
119
  export function createMailer(options: MailerOptions = {}): Mailer {
150
120
  const outbox: SentMail[] = []
121
+ const previews: MailPreviewEntry[] = [...(options.previews ?? [])]
122
+ const route = options.previewRoute ?? '/_pru/mail'
123
+ const queueName = options.retries?.queue ?? DEFAULT_QUEUE_NAME
124
+ const queueOpts: JobsQueueOptions = {
125
+ attempts: options.retries?.attempts ?? DEFAULT_RETRY_OPTIONS.attempts,
126
+ backoff: options.retries?.backoff ?? DEFAULT_RETRY_OPTIONS.backoff,
127
+ }
128
+
151
129
  let serverDev: boolean | undefined
130
+ let injectJobs: (() => JobsService | undefined) | undefined
131
+ const registeredJobs = new WeakSet<JobsService>()
132
+ const getTransport = createTransportResolver(options.transport)
152
133
 
153
- const getTransport = (): MailTransport | undefined => {
154
- if (options.transport !== undefined)
155
- return options.transport
156
- if (process.env.RESEND_API_KEY)
157
- return resend({ apiKey: process.env.RESEND_API_KEY })
158
- return undefined
134
+ const ensureJobsQueue = (): JobsService | undefined => {
135
+ const svc = injectJobs?.()
136
+ if (svc === undefined)
137
+ return undefined
138
+ if (!registeredJobs.has(svc)) {
139
+ registeredJobs.add(svc)
140
+ svc.queue<SentMail>(queueName, async (record) => {
141
+ const transport = getTransport()
142
+ if (transport === undefined)
143
+ throw new MailNotConfiguredError()
144
+ await transport.send(record)
145
+ }, queueOpts)
146
+ }
147
+ return svc
159
148
  }
160
149
 
150
+ const plugin = definePlugin({
151
+ name: '@prunellejs/mail',
152
+ after: ['@prunellejs/jobs'],
153
+ server(api) {
154
+ serverDev = api.dev
155
+ setAppLang(typeof api.config?.lang === 'string' ? api.config.lang : undefined)
156
+ injectJobs = () => api.inject(JOBS_SERVICE)
157
+ ensureJobsQueue()
158
+
159
+ api.onShutdown(() => {
160
+ injectJobs = undefined
161
+ setAppLang(undefined)
162
+ })
163
+
164
+ const enablePreview = options.preview !== false && isDevOrTest(api.dev)
165
+ if (!enablePreview)
166
+ return
167
+
168
+ api.route('GET', `${route}.json`, async (ctx) => {
169
+ const renderedPreviews = await renderPreviewEntries(previews)
170
+ return ctx.json({ count: outbox.length, messages: outbox, previews: renderedPreviews })
171
+ })
172
+
173
+ api.route('GET', route, async () => {
174
+ const renderedPreviews = await renderPreviewEntries(previews)
175
+ const html = renderOutboxHtml(outbox, renderedPreviews)
176
+ // prunelle adds the app's CSP with this page's <style> hash.
177
+ return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } })
178
+ })
179
+ },
180
+ })
181
+
161
182
  const instance: Mailer = {
162
- ...previewPlugin(outbox, options, (dev) => {
163
- serverDev = dev
164
- }),
183
+ ...plugin,
165
184
  outbox,
166
185
  isConfigured() {
167
186
  return getTransport() !== undefined
@@ -169,7 +188,7 @@ export function createMailer(options: MailerOptions = {}): Mailer {
169
188
  requires() {
170
189
  const unmet: string[] = []
171
190
  if (getTransport() === undefined && !options.optional)
172
- unmet.push('no transport, so every send() throws: set `RESEND_API_KEY`, or pass `transport` to `createMailer()` (`optional: true` drops mail instead).')
191
+ 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).')
173
192
  if ((options.from ?? process.env.MAIL_FROM) === undefined)
174
193
  unmet.push('no sender, so mail goes out from noreply@localhost: set `MAIL_FROM`, or pass `from` to `createMailer()`.')
175
194
  return unmet
@@ -177,31 +196,55 @@ export function createMailer(options: MailerOptions = {}): Mailer {
177
196
  clearOutbox() {
178
197
  outbox.length = 0
179
198
  },
180
- async send(message) {
199
+ preview(
200
+ nameOrEntry: string | MailPreviewEntry,
201
+ renderOrComponent?: ((props?: Record<string, unknown>) => MailBody) | (() => MailBody),
202
+ samplePropsOrOptions?: Record<string, unknown> | MailPreviewRegisterOptions,
203
+ previewOptions?: MailPreviewRegisterOptions,
204
+ ) {
205
+ const entry = toPreviewEntry(nameOrEntry, renderOrComponent, samplePropsOrOptions, previewOptions)
206
+ const existingIndex = previews.findIndex(p => p.name === entry.name)
207
+ if (existingIndex >= 0)
208
+ previews[existingIndex] = entry
209
+ else
210
+ previews.push(entry)
211
+ },
212
+ async send(message: MailMessage) {
181
213
  assertNoHeaderInjection(message.subject, 'subject')
182
214
  const from = message.from ?? options.from ?? process.env.MAIL_FROM ?? 'noreply@localhost'
183
215
  const toList = normalizeList(message.to ?? options.to ?? process.env.MAIL_TO, 'to')
184
216
  if (toList.length === 0)
185
217
  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\`.`)
218
+
219
+ let html = message.html
220
+ let text = message.text
221
+ if (message.body !== undefined) {
222
+ const rendered = await renderMail(message.body)
223
+ html = html ?? rendered.html
224
+ text = text ?? rendered.text
225
+ }
226
+
186
227
  const record: SentMail = {
187
228
  id: crypto.randomUUID(),
188
229
  from: formatAddress(from, 'from'),
189
230
  to: toList,
190
231
  ...(message.replyTo !== undefined ? { replyTo: formatAddress(message.replyTo, 'replyTo') } : {}),
191
232
  subject: message.subject,
192
- ...(message.text !== undefined ? { text: message.text } : {}),
193
- ...(message.html !== undefined ? { html: message.html } : {}),
233
+ ...(text !== undefined ? { text } : {}),
234
+ ...(html !== undefined ? { html } : {}),
194
235
  sentAt: new Date().toISOString(),
195
236
  }
196
237
 
197
- const devOrTest = isDevOrTest(serverDev ?? (process.env.PRUNELLE_DEV === '1'))
198
- const transport = getTransport()
199
- if (transport !== undefined) {
200
- await transport.send(record)
201
- }
202
- else if (!devOrTest && !options.optional) {
203
- throw new MailNotConfiguredError()
204
- }
238
+ const devOrTest = isDevOrTest(serverDev ?? devFromEnv())
239
+ await deliverRecord({
240
+ record,
241
+ transport: getTransport(),
242
+ devOrTest,
243
+ optional: options.optional === true,
244
+ asyncQueue: options.asyncQueue === true,
245
+ queueName,
246
+ jobs: ensureJobsQueue(),
247
+ })
205
248
 
206
249
  // Non-dev/test runs keep no copy: the outbox holds sign-in links in plain text, and no preview reads it there.
207
250
  if (devOrTest) {
@@ -214,46 +257,3 @@ export function createMailer(options: MailerOptions = {}): Mailer {
214
257
  }
215
258
  return instance
216
259
  }
217
-
218
- export interface MailPreviewOptions {
219
- /** Dev outbox preview route (default: '/_pru/mail'). */
220
- previewRoute?: string | undefined
221
- /** Turns the outbox preview off; it is only ever mounted under `prunelle dev` or NODE_ENV development or test, never in production. */
222
- preview?: false | undefined
223
- }
224
-
225
- const MAIL_OUTBOX_CSS = 'body{font-family:system-ui,sans-serif;max-width:48rem;margin:2rem auto;padding:0 1rem;background:#f9fafb}article{border:1px solid #e5e7eb;border-radius:8px;padding:1rem;margin-bottom:1rem;background:#fff}h2{margin:0 0 .25rem;font-size:1rem}.meta,.empty{margin:0 0 .5rem;font-size:.85rem;color:#6b7280}iframe{width:100%;min-height:16rem;border:0}pre{margin:0;white-space:pre-wrap;font-size:.85rem}'
226
-
227
- function previewPlugin(
228
- outbox: readonly SentMail[],
229
- options: MailPreviewOptions,
230
- onServerInit?: (dev: boolean) => void,
231
- ): PrunellePlugin {
232
- const route = options.previewRoute ?? '/_pru/mail'
233
-
234
- return definePlugin({
235
- name: '@prunellejs/mail',
236
- server(api) {
237
- onServerInit?.(api.dev)
238
- const enablePreview = options.preview !== false && isDevOrTest(api.dev)
239
- if (!enablePreview)
240
- return
241
-
242
- api.route('GET', `${route}.json`, ctx => ctx.json({ count: outbox.length, messages: outbox }))
243
-
244
- api.route('GET', route, () => {
245
- const rows = outbox.map(m =>
246
- `<article>`
247
- + `<h2>${esc(m.subject)}</h2>`
248
- + `<p class="meta">From: ${esc(m.from)} → To: ${esc(m.to.join(', '))}${m.replyTo ? ` (Reply-To: ${esc(m.replyTo)})` : ''} · ${esc(m.sentAt)}</p>`
249
- + (m.html ? `<iframe sandbox="" srcdoc="${escAttr(m.html)}" title="${escAttr(m.subject)}"></iframe>` : `<pre>${esc(m.text ?? '')}</pre>`)
250
- + `</article>`,
251
- ).join('')
252
-
253
- const html = `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Prunelle Mail Outbox (${outbox.length})</title><style>${MAIL_OUTBOX_CSS}</style></head><body><h1>Mail Outbox (${outbox.length})</h1>${rows || '<p class="empty">No messages sent yet.</p>'}</body></html>`
254
- // prunelle adds the app's CSP with this page's <style> hash.
255
- return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } })
256
- })
257
- },
258
- })
259
- }
package/src/mime.ts ADDED
@@ -0,0 +1,163 @@
1
+ // RFC 5322 / RFC 2047 / RFC 2045 MIME message formatting and RFC 5321 DATA dot-stuffing.
2
+
3
+ import type { SentMail } from './types'
4
+ import { assertNoHeaderInjection } from './types'
5
+
6
+ const NON_ASCII_RE = /[^\x20-\x7E]/
7
+ const WHITESPACE_OR_ANGLE_RE = /[\s<>]/
8
+
9
+ // An encoded word is at most 75 characters; 42 bytes make 56 base64 chars + 12 wrapper chars = 68, fitting after `Reply-To: ` within 78.
10
+ const ENCODED_WORD_MAX_BYTES = 42
11
+ const HEADER_LINE_MAX = 78
12
+ const QP_LINE_MAX = 76
13
+ const HEADER_TOKEN_RE = /([ \t]*)([^ \t]+)/g
14
+ const ANGLE_ADDRESS_RE = /^\s*(.*?)\s*(<[^<>]+>)\s*$/
15
+ const QUOTED_NAME_RE = /^"(.*)"$/
16
+
17
+ export function validateEhloHost(value: string): string {
18
+ assertNoHeaderInjection(value, 'ehloHost')
19
+ if (value.length === 0 || WHITESPACE_OR_ANGLE_RE.test(value))
20
+ throw new RangeError('@prunellejs/mail (smtp): `ehloHost` must be a non-empty hostname without whitespace or angle brackets')
21
+ return value
22
+ }
23
+
24
+ /** Splits non-ASCII text into space-separated RFC 2047 encoded words, never cutting a UTF-8 sequence. */
25
+ function encodeRfc2047(value: string): string {
26
+ if (!NON_ASCII_RE.test(value))
27
+ return value
28
+ const words: string[] = []
29
+ let chunk = ''
30
+ let chunkBytes = 0
31
+ for (const char of value) {
32
+ const bytes = Buffer.byteLength(char, 'utf8')
33
+ if (chunkBytes + bytes > ENCODED_WORD_MAX_BYTES) {
34
+ words.push(chunk)
35
+ chunk = ''
36
+ chunkBytes = 0
37
+ }
38
+ chunk += char
39
+ chunkBytes += bytes
40
+ }
41
+ words.push(chunk)
42
+ return words.map(word => `=?UTF-8?B?${Buffer.from(word, 'utf8').toString('base64')}?=`).join(' ')
43
+ }
44
+
45
+ /** Encodes the display name of `Name <addr>` when it is not ASCII; anything else is returned as it is. */
46
+ function encodeAddressHeader(address: string): string {
47
+ const match = ANGLE_ADDRESS_RE.exec(address)
48
+ if (match === null || !NON_ASCII_RE.test(match[1]!))
49
+ return address
50
+ const name = match[1]!.replace(QUOTED_NAME_RE, '$1').replace(/\\(.)/g, '$1')
51
+ return `${encodeRfc2047(name)} ${match[2]!}`
52
+ }
53
+
54
+ /** Folds a header at whitespace so no line passes 78 characters (RFC 5322 §2.2.3); a token longer than that stays whole. */
55
+ function foldHeader(name: string, value: string): string {
56
+ if (value.length === 0)
57
+ return `${name}:`
58
+ const rest = ` ${value}`
59
+ const lines: string[] = []
60
+ let line = `${name}:`
61
+ let hasToken = false
62
+ let lastIndex = 0
63
+ for (const match of rest.matchAll(HEADER_TOKEN_RE)) {
64
+ const ws = match[1]!
65
+ const token = match[2]!
66
+ lastIndex = match.index! + match[0]!.length
67
+ if (hasToken && ws.length > 0 && line.length + ws.length + token.length > HEADER_LINE_MAX) {
68
+ lines.push(line)
69
+ line = `${ws}${token}`
70
+ }
71
+ else {
72
+ line += `${ws}${token}`
73
+ }
74
+ hasToken = true
75
+ }
76
+ if (lastIndex < rest.length)
77
+ line += rest.slice(lastIndex)
78
+ lines.push(line)
79
+ return lines.join('\r\n')
80
+ }
81
+
82
+ function quotedPrintableLine(line: string): string {
83
+ const bytes = Buffer.from(line, 'utf8')
84
+ const out: string[] = []
85
+ let current = ''
86
+ for (const [i, byte] of bytes.entries()) {
87
+ const isLast = i === bytes.length - 1
88
+ const literal = (byte >= 33 && byte <= 126 && byte !== 61) || ((byte === 32 || byte === 9) && !isLast)
89
+ const token = literal ? String.fromCharCode(byte) : `=${byte.toString(16).toUpperCase().padStart(2, '0')}`
90
+ const fits = isLast ? current.length + token.length <= QP_LINE_MAX : current.length + token.length < QP_LINE_MAX
91
+ if (!fits) {
92
+ out.push(`${current}=`)
93
+ current = ''
94
+ }
95
+ current += token
96
+ }
97
+ out.push(current)
98
+ return out.join('\r\n')
99
+ }
100
+
101
+ function normalizeCrlf(text: string): string {
102
+ return text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').replace(/\n/g, '\r\n')
103
+ }
104
+
105
+ /** RFC 2045 quoted-printable: 7-bit, lines of at most 76 characters with soft breaks, so the body needs neither 8BITMIME nor a line under 998. */
106
+ function encodeQuotedPrintable(text: string): string {
107
+ return normalizeCrlf(text).split('\r\n').map(quotedPrintableLine).join('\r\n')
108
+ }
109
+
110
+ /** Applies RFC 5321 §4.5.2 dot-stuffing and appends the terminating `\r\n.\r\n`. */
111
+ export function dotStuffSmtpData(rawMessage: string): string {
112
+ const normalized = normalizeCrlf(rawMessage)
113
+ const stuffed = normalized.replace(/(^|\r\n)\./g, '$1..')
114
+ return stuffed.endsWith('\r\n') ? `${stuffed}.\r\n` : `${stuffed}\r\n.\r\n`
115
+ }
116
+
117
+ /** Builds an RFC 5322 + MIME message (using `multipart/alternative` when both `text` and `html` are present). */
118
+ export function buildMimeMessage(mail: SentMail, domain = 'localhost'): string {
119
+ const safeDomain = validateEhloHost(domain)
120
+ 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
+ assertNoHeaderInjection(value, label)
122
+ const headers = [
123
+ foldHeader('From', encodeAddressHeader(mail.from)),
124
+ foldHeader('To', mail.to.map(encodeAddressHeader).join(', ')),
125
+ ...(mail.replyTo !== undefined ? [foldHeader('Reply-To', encodeAddressHeader(mail.replyTo))] : []),
126
+ foldHeader('Subject', encodeRfc2047(mail.subject)),
127
+ `Date: ${new Date(mail.sentAt).toUTCString()}`,
128
+ `Message-ID: <${mail.id}@${safeDomain}>`,
129
+ 'MIME-Version: 1.0',
130
+ ]
131
+
132
+ const hasText = mail.text !== undefined
133
+ const hasHtml = mail.html !== undefined
134
+
135
+ if (hasText && hasHtml) {
136
+ const boundary = `----=_PruMail_${mail.id.replace(/[^A-Za-z0-9]/g, '')}`
137
+ headers.push(`Content-Type: multipart/alternative; boundary="${boundary}"`)
138
+ return [
139
+ headers.join('\r\n'),
140
+ '',
141
+ `--${boundary}`,
142
+ 'Content-Type: text/plain; charset=utf-8',
143
+ 'Content-Transfer-Encoding: quoted-printable',
144
+ '',
145
+ encodeQuotedPrintable(mail.text!),
146
+ `--${boundary}`,
147
+ 'Content-Type: text/html; charset=utf-8',
148
+ 'Content-Transfer-Encoding: quoted-printable',
149
+ '',
150
+ encodeQuotedPrintable(mail.html!),
151
+ `--${boundary}--`,
152
+ '',
153
+ ].join('\r\n')
154
+ }
155
+
156
+ if (hasHtml) {
157
+ headers.push('Content-Type: text/html; charset=utf-8', 'Content-Transfer-Encoding: quoted-printable')
158
+ return `${headers.join('\r\n')}\r\n\r\n${encodeQuotedPrintable(mail.html!)}\r\n`
159
+ }
160
+
161
+ headers.push('Content-Type: text/plain; charset=utf-8', 'Content-Transfer-Encoding: quoted-printable')
162
+ return `${headers.join('\r\n')}\r\n\r\n${encodeQuotedPrintable(mail.text ?? '')}\r\n`
163
+ }