@prunellejs/mail 0.0.0-stage → 0.1.1
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 +45 -0
- package/package.json +24 -4
- package/src/index.ts +259 -0
- package/README.md +0 -3
package/llms.txt
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# @prunellejs/mail Reference
|
|
2
|
+
|
|
3
|
+
> Zero-dependency email delivery (Resend HTTP or custom transport) with a dev-only HTML/JSON outbox preview.
|
|
4
|
+
|
|
5
|
+
## Imports
|
|
6
|
+
|
|
7
|
+
- `@prunellejs/mail`: `createMailer`, `resend`, `MailNotConfiguredError`; types `Mailer`, `MailerOptions`, `MailPreviewOptions`, `MailMessage`, `SentMail`, `MailAddress`, `MailTransport`.
|
|
8
|
+
|
|
9
|
+
## Setup (`createMailer(options?)`)
|
|
10
|
+
|
|
11
|
+
`createMailer()` returns a single object that is both the `PrunellePlugin` (register in `prunelle.config.ts`) and the handle routes/actions call `mail.send()` on:
|
|
12
|
+
|
|
13
|
+
- `from`: default sender (`string | { name, address }`, falls back to `process.env.MAIL_FROM`, then `'noreply@localhost'` outside production: a production start refuses without one).
|
|
14
|
+
- `to`: default recipient(s) (falls back to `process.env.MAIL_TO`); `send()` with no recipient throws, in every mode.
|
|
15
|
+
- A production start refuses with no transport (`transport` or `RESEND_API_KEY`) unless `optional: true`.
|
|
16
|
+
- `transport`: `MailTransport` (`{ send(mail: SentMail): Promise<void> }`). Defaults to `resend()` when `process.env.RESEND_API_KEY` is set.
|
|
17
|
+
- `optional`: when `false`/omitted, calling `send()` in `NODE_ENV=production` without a transport throws `MailNotConfiguredError`.
|
|
18
|
+
- `previewRoute`: dev outbox URL (default `'/_pru/mail'`). `preview: false` disables the preview.
|
|
19
|
+
|
|
20
|
+
## Mounted Routes (dev/test only — never in production)
|
|
21
|
+
|
|
22
|
+
- `GET /_pru/mail` — HTML outbox viewer (HTML bodies rendered in sandboxed `<iframe>`s).
|
|
23
|
+
- `GET /_pru/mail.json` — `{ count, messages }` JSON dump of captured messages (up to 100 in memory; production keeps no copy).
|
|
24
|
+
|
|
25
|
+
## Handle & Transport API
|
|
26
|
+
|
|
27
|
+
- `await mail.send({ from?, to?, replyTo?, subject, text?, html? })` → `SentMail` (`{ id, from, to, replyTo?, subject, text?, html?, sentAt }`).
|
|
28
|
+
- `mail.isConfigured()`: `boolean`. `mail.outbox`: `SentMail[]`. `mail.clearOutbox()`.
|
|
29
|
+
- `resend({ apiKey?, endpoint?, timeoutMs?, retries? })`: built-in Resend HTTP transport using `fetch()`. Each request times out after `timeoutMs` (10 000). A `429` or `5xx` answer is retried `retries` times (2), after its `retry-after` or 0.5 s doubling, capped at 5 s, under the mail's id as `Idempotency-Key`, so a retry never sends twice.
|
|
30
|
+
- Works directly as `createAuth({ mailer: mail })` with `@prunellejs/auth`.
|
|
31
|
+
|
|
32
|
+
## Snippet
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
// src/mail.ts (and register `plugins: [mail]` in prunelle.config.ts)
|
|
36
|
+
import { createMailer, resend } from '@prunellejs/mail'
|
|
37
|
+
|
|
38
|
+
export const mail = createMailer({
|
|
39
|
+
from: 'App <noreply@example.com>',
|
|
40
|
+
transport: process.env.RESEND_API_KEY ? resend() : undefined,
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
// In an action or route:
|
|
44
|
+
await mail.send({ to: 'ada@example.com', subject: 'Welcome', text: 'Hello!' })
|
|
45
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/mail",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Zero-dependency email delivery (Resend / custom transport) and dev outbox plugin for Prunelle",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"files": [
|
|
9
|
+
"src",
|
|
10
|
+
"llms.txt"
|
|
11
|
+
],
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./src/index.ts"
|
|
14
|
+
},
|
|
15
|
+
"engines": {
|
|
16
|
+
"bun": ">=1.4.0"
|
|
17
|
+
},
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "https://github.com/Kayno0o/prunelle",
|
|
21
|
+
"directory": "packages/plugin-mail"
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"prunelle": "^0.1.1"
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
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).
|
|
3
|
+
|
|
4
|
+
import type { PrunellePlugin } from 'prunelle/config'
|
|
5
|
+
import { definePlugin } from 'prunelle/config'
|
|
6
|
+
import { esc, escAttr, nodeEnv } from 'prunelle/server'
|
|
7
|
+
|
|
8
|
+
export type MailAddress = string | { name: string, address: string }
|
|
9
|
+
|
|
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
|
+
}
|
|
79
|
+
|
|
80
|
+
function isDevOrTest(devFlag: boolean): boolean {
|
|
81
|
+
const env = nodeEnv()
|
|
82
|
+
if (env === 'production')
|
|
83
|
+
return false
|
|
84
|
+
return devFlag || env === 'development' || env === 'test'
|
|
85
|
+
}
|
|
86
|
+
|
|
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
|
+
}
|
|
92
|
+
|
|
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
|
|
98
|
+
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
|
+
},
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
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
|
|
139
|
+
}
|
|
140
|
+
|
|
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>
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function createMailer(options: MailerOptions = {}): Mailer {
|
|
150
|
+
const outbox: SentMail[] = []
|
|
151
|
+
let serverDev: boolean | undefined
|
|
152
|
+
|
|
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
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const instance: Mailer = {
|
|
162
|
+
...previewPlugin(outbox, options, (dev) => {
|
|
163
|
+
serverDev = dev
|
|
164
|
+
}),
|
|
165
|
+
outbox,
|
|
166
|
+
isConfigured() {
|
|
167
|
+
return getTransport() !== undefined
|
|
168
|
+
},
|
|
169
|
+
requires() {
|
|
170
|
+
const unmet: string[] = []
|
|
171
|
+
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).')
|
|
173
|
+
if ((options.from ?? process.env.MAIL_FROM) === undefined)
|
|
174
|
+
unmet.push('no sender, so mail goes out from noreply@localhost: set `MAIL_FROM`, or pass `from` to `createMailer()`.')
|
|
175
|
+
return unmet
|
|
176
|
+
},
|
|
177
|
+
clearOutbox() {
|
|
178
|
+
outbox.length = 0
|
|
179
|
+
},
|
|
180
|
+
async send(message) {
|
|
181
|
+
assertNoHeaderInjection(message.subject, 'subject')
|
|
182
|
+
const from = message.from ?? options.from ?? process.env.MAIL_FROM ?? 'noreply@localhost'
|
|
183
|
+
const toList = normalizeList(message.to ?? options.to ?? process.env.MAIL_TO, 'to')
|
|
184
|
+
if (toList.length === 0)
|
|
185
|
+
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\`.`)
|
|
186
|
+
const record: SentMail = {
|
|
187
|
+
id: crypto.randomUUID(),
|
|
188
|
+
from: formatAddress(from, 'from'),
|
|
189
|
+
to: toList,
|
|
190
|
+
...(message.replyTo !== undefined ? { replyTo: formatAddress(message.replyTo, 'replyTo') } : {}),
|
|
191
|
+
subject: message.subject,
|
|
192
|
+
...(message.text !== undefined ? { text: message.text } : {}),
|
|
193
|
+
...(message.html !== undefined ? { html: message.html } : {}),
|
|
194
|
+
sentAt: new Date().toISOString(),
|
|
195
|
+
}
|
|
196
|
+
|
|
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
|
+
}
|
|
205
|
+
|
|
206
|
+
// Non-dev/test runs keep no copy: the outbox holds sign-in links in plain text, and no preview reads it there.
|
|
207
|
+
if (devOrTest) {
|
|
208
|
+
outbox.unshift(record)
|
|
209
|
+
if (outbox.length > 100)
|
|
210
|
+
outbox.length = 100
|
|
211
|
+
}
|
|
212
|
+
return record
|
|
213
|
+
},
|
|
214
|
+
}
|
|
215
|
+
return instance
|
|
216
|
+
}
|
|
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/README.md
DELETED