@prunellejs/mail 0.0.0-stage → 0.7.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt ADDED
@@ -0,0 +1,77 @@
1
+ # @prunellejs/mail Reference
2
+
3
+ > Zero-dependency email delivery with JSX/TSX templates (auto HTML + plain text), email-safe components, native SMTP/SMTPS/STARTTLS, Resend, Postmark, `MAIL_URL`, `@prunellejs/jobs` retry integration, and a dev-only outbox + template preview.
4
+
5
+ ## Imports
6
+
7
+ - `@prunellejs/mail`:
8
+ - Core: `createMailer`, `renderMail`, `htmlToText`, `MailNotConfiguredError`
9
+ - Transports: `smtp`, `resend`, `postmark`, `transportFromUrl`, `buildMimeMessage`, `dotStuffSmtpData`
10
+ - Components: `Email`, `Section`, `Heading`, `Text`, `Button`, `Divider`, `Footer`, `Link`
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`.
12
+
13
+ ## Setup (`createMailer(options?)`)
14
+
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
+
17
+ - `from`: default sender (`string | { name, address }`, falls back to `process.env.MAIL_FROM`, then `'noreply@localhost'` outside production: a production start refuses without one).
18
+ - `to`: default recipient(s) (falls back to `process.env.MAIL_TO`); `send()` with no recipient throws, in every mode.
19
+ - `transport`: `MailTransport` (`{ send(mail: SentMail): Promise<void> }`). Resolution order:
20
+ 1. Explicit `options.transport`
21
+ 2. `process.env.MAIL_URL` (`smtp://`, `smtps://`, `resend://`, `postmark://`)
22
+ 3. `process.env.RESEND_API_KEY` (`resend()`)
23
+ - A production start refuses with no transport (`transport`, `MAIL_URL`, or `RESEND_API_KEY`) unless `optional: true`.
24
+ - `optional`: when `false`/omitted, calling `send()` in `NODE_ENV=production` without a transport throws `MailNotConfiguredError`.
25
+ - `previewRoute`: dev outbox URL (default `'/_pru/mail'`). `preview: false` disables the preview.
26
+ - `previews`: array of `{ name, subject?, props?, render: () => MailBody }` templates rendered live in the dev outbox. You can also register previews imperatively via `mail.preview(name, Component, sampleProps, { subject? })` or `mail.preview(name, () => <Welcome ... />, { subject? })`.
27
+ - `retries`: `{ queue?: string, attempts?: number, backoff?: 'exponential' | 'fixed' | number }` used when `@prunellejs/jobs` (`JOBS_SERVICE`) is registered. On transport failure, delivery is enqueued on `mail.deliver` with `{ key: record.id }` for durable deduplicated retries. Set `asyncQueue: true` to enqueue upfront without attempting inline send first.
28
+
29
+ ## JSX/TSX Templates & Components
30
+
31
+ - `await mail.send({ to, subject, body: <Welcome name="Ada" /> })` renders both `html` and a clean `text` alternative automatically (explicit `text` or `html` overrides the rendered part).
32
+ - `await renderMail(node)` returns `{ html, text }` from any JSX/TSX element, compiled `Html`, async component result, or render factory.
33
+ - Built-in email-safe components work identically in compiled Prunelle routes and direct Bun execution:
34
+ - `Email({ lang? (default: `lang` from `prunelle.config.ts`, else `en`), title?, preview?, backgroundColor?, containerBackgroundColor?, width?, children })` — full HTML email document with Outlook MSO namespaces & DPI XML, dark-mode `<meta>` + `@media (prefers-color-scheme: dark)` CSS, hidden preheader, and centered 600px table layout.
35
+ - `Section`, `Heading` (`h1`–`h3`), `Text` (`muted?`), `Button` (Outlook VML roundrect as wide as its label + dark-mode CTA), `Divider`, `Footer`, `Link`.
36
+
37
+ ## Transports & `MAIL_URL`
38
+
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)
41
+ - `smtps://[user:pass@]host[:port]` (default port 465; implicit TLS)
42
+ - `resend://<apiKey>` or `resend://:<apiKey>@api.resend.com`
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` or `requireTls: false`), `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`. 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
+ - `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
+
48
+ ## Mounted Routes (`prunelle dev` or `NODE_ENV=test` only — never in production or built servers outside test)
49
+
50
+ - `GET /_pru/mail` — HTML outbox viewer showing registered template previews (HTML iframe + plain text) and sent messages (sandboxed `<iframe>`s + plain text).
51
+ - `GET /_pru/mail.json` — `{ count, messages, previews }` JSON dump (up to 100 sent messages in memory; production keeps no copy).
52
+
53
+ ## Snippet
54
+
55
+ ```tsx
56
+ // src/mail.tsx (and register `plugins: [mail]` in prunelle.config.ts)
57
+ import { Button, createMailer, Email, Footer, Heading, Text } from '@prunellejs/mail'
58
+
59
+ export function Welcome({ name }: { name: string }) {
60
+ return (
61
+ <Email preview="Welcome aboard">
62
+ <Heading>Welcome, {name}!</Heading>
63
+ <Text>Your account is ready.</Text>
64
+ <Button href="https://example.com/start">Get started</Button>
65
+ <Footer>Acme Inc.</Footer>
66
+ </Email>
67
+ )
68
+ }
69
+
70
+ export const mail = createMailer({
71
+ from: 'App <noreply@example.com>',
72
+ previews: [{ name: 'Welcome', subject: 'Welcome!', render: () => <Welcome name="Ada" /> }],
73
+ })
74
+
75
+ // In an action or route (uses MAIL_URL or RESEND_API_KEY automatically):
76
+ await mail.send({ to: 'ada@example.com', subject: 'Welcome!', body: <Welcome name="Ada" /> })
77
+ ```
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@prunellejs/mail",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.2",
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
+ "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.7.2"
25
+ }
26
+ }
@@ -0,0 +1,276 @@
1
+ // Email-safe JSX/TSX components with table layouts, inline styles, Outlook MSO VML fallbacks, and dark-mode CSS.
2
+ // Built with `raw`/`esc`/`escAttr` from `prunelle/server` so they render identically both in compiled Prunelle routes and direct Bun execution.
3
+
4
+ import type { Html, PrunelleChild } from 'prunelle/jsx-runtime'
5
+ import { esc, escAttr, raw, safeRedirect } from 'prunelle/server'
6
+
7
+ export type TextAlign = 'left' | 'center' | 'right'
8
+
9
+ export interface EmailProps {
10
+ /** Document language attribute (default: `lang` from `prunelle.config.ts`, else `'en'`). */
11
+ lang?: string | undefined
12
+ /** Optional `<title>` inside `<head>`. */
13
+ title?: string | undefined
14
+ /** Hidden inbox preheader text (excluded from auto-derived plain text). */
15
+ preview?: string | undefined
16
+ /** Outer email canvas background color (default `'#f4f4f5'`). */
17
+ backgroundColor?: string | undefined
18
+ /** Inner card background color (default `'#ffffff'`). */
19
+ containerBackgroundColor?: string | undefined
20
+ /** Max container width in pixels (default `600`). */
21
+ width?: number | undefined
22
+ children?: PrunelleChild | undefined
23
+ }
24
+
25
+ export interface SectionProps {
26
+ padding?: string | undefined
27
+ backgroundColor?: string | undefined
28
+ align?: TextAlign | undefined
29
+ style?: string | undefined
30
+ children?: PrunelleChild | undefined
31
+ }
32
+
33
+ export interface HeadingProps {
34
+ as?: 'h1' | 'h2' | 'h3' | undefined
35
+ align?: TextAlign | undefined
36
+ style?: string | undefined
37
+ children?: PrunelleChild | undefined
38
+ }
39
+
40
+ export interface TextProps {
41
+ align?: TextAlign | undefined
42
+ muted?: boolean | undefined
43
+ style?: string | undefined
44
+ children?: PrunelleChild | undefined
45
+ }
46
+
47
+ export interface ButtonProps {
48
+ href: string
49
+ backgroundColor?: string | undefined
50
+ color?: string | undefined
51
+ borderRadius?: number | undefined
52
+ align?: TextAlign | undefined
53
+ style?: string | undefined
54
+ children?: PrunelleChild | undefined
55
+ }
56
+
57
+ export interface DividerProps {
58
+ color?: string | undefined
59
+ margin?: string | undefined
60
+ style?: string | undefined
61
+ }
62
+
63
+ export interface FooterProps {
64
+ align?: TextAlign | undefined
65
+ style?: string | undefined
66
+ children?: PrunelleChild | undefined
67
+ }
68
+
69
+ export interface LinkProps {
70
+ href: string
71
+ color?: string | undefined
72
+ style?: string | undefined
73
+ children?: PrunelleChild | undefined
74
+ }
75
+
76
+ const SAFE_URL_SCHEME_RE = /^(?:https?:|mailto:|tel:)/i
77
+ const HAS_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i
78
+ const CONTROL_OR_BACKSLASH_RE = /[\u0000-\u001F\u007F\\]/
79
+
80
+ const EMAIL_HEAD_CSS = [
81
+ ':root{color-scheme:light dark;supported-color-schemes:light dark;}',
82
+ 'body{margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;}',
83
+ 'table,td{border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt;}',
84
+ 'img{border:0;height:auto;line-height:100%;outline:none;text-decoration:none;}',
85
+ '@media (prefers-color-scheme: dark){',
86
+ '.pru-email-bg{background-color:#09090b!important;color:#f4f4f5!important;}',
87
+ '.pru-email-card{background-color:#18181b!important;border-color:#27272a!important;}',
88
+ '.pru-email-heading,.pru-email-text{color:#f4f4f5!important;}',
89
+ '.pru-email-muted{color:#a1a1aa!important;}',
90
+ '.pru-email-divider{border-top-color:#27272a!important;}',
91
+ '.pru-email-link{color:#60a5fa!important;}',
92
+ '.pru-email-btn{background-color:#f4f4f5!important;color:#09090b!important;}',
93
+ '}',
94
+ '[data-ogsc] .pru-email-bg{background-color:#09090b!important;color:#f4f4f5!important;}',
95
+ '[data-ogsc] .pru-email-card{background-color:#18181b!important;border-color:#27272a!important;}',
96
+ '[data-ogsc] .pru-email-heading,[data-ogsc] .pru-email-text{color:#f4f4f5!important;}',
97
+ '[data-ogsc] .pru-email-muted{color:#a1a1aa!important;}',
98
+ '[data-ogsc] .pru-email-link{color:#60a5fa!important;}',
99
+ '@media only screen and (max-width:620px){.pru-email-pad{padding:24px 16px!important;}}',
100
+ ].join('')
101
+
102
+ const HEADING_STYLES: Readonly<Record<'h1' | 'h2' | 'h3', string>> = {
103
+ h1: 'margin:0 0 16px;font-size:24px;line-height:1.3;font-weight:700;color:#18181b;',
104
+ h2: 'margin:0 0 12px;font-size:20px;line-height:1.35;font-weight:700;color:#18181b;',
105
+ h3: 'margin:0 0 8px;font-size:16px;line-height:1.4;font-weight:600;color:#18181b;',
106
+ }
107
+
108
+ const PREVIEW_SPACER = '&zwnj;&nbsp;'.repeat(24)
109
+
110
+ function safeEmailUrl(href: string, component: string): string {
111
+ const trimmed = href.trim()
112
+ // A browser drops a tab or newline from a URL, so `java\tscript:` is `javascript:` and `/\t/host` is `//host`: no control character or backslash is let through, and a path goes through the same check as a redirect.
113
+ const unsafe = CONTROL_OR_BACKSLASH_RE.test(trimmed)
114
+ || (trimmed.startsWith('/') ? safeRedirect(trimmed, '') !== trimmed : HAS_SCHEME_RE.test(trimmed) && !SAFE_URL_SCHEME_RE.test(trimmed))
115
+ if (unsafe)
116
+ throw new RangeError(`@prunellejs/mail: <${component}> refused unsafe URL "${href}"`)
117
+ return trimmed
118
+ }
119
+
120
+ function appendExtraStyle(base: string, extra?: string): string {
121
+ if (!extra)
122
+ return base
123
+ const normalized = extra.trim()
124
+ if (normalized.length === 0)
125
+ return base
126
+ return base.endsWith(';') ? `${base}${normalized}` : `${base};${normalized}`
127
+ }
128
+
129
+ const TAG_RE = /<[^>]*>/g
130
+ const ENTITY_RE = /&#?\w+;/g
131
+
132
+ // Characters a reader sees in escaped HTML: tags dropped, each entity one character.
133
+ function visibleLength(html: string): number {
134
+ return html.replace(TAG_RE, '').replace(ENTITY_RE, '_').length
135
+ }
136
+
137
+ function safeAlign(align?: TextAlign): TextAlign {
138
+ return align === 'center' || align === 'right' ? align : 'left'
139
+ }
140
+
141
+ let appLang: string | undefined
142
+
143
+ /** Set by the mail plugin from `prunelle.config.ts`, so an email speaks the app's language unless it says otherwise. */
144
+ export function setAppLang(lang: string | undefined): void {
145
+ appLang = lang
146
+ }
147
+
148
+ /** Root HTML email document with Outlook MSO namespaces/DPI settings, dark-mode meta + CSS, and centered 600px table container. */
149
+ export function Email(props: EmailProps = {}): Html {
150
+ const lang = props.lang ?? appLang ?? 'en'
151
+ const bg = props.backgroundColor ?? '#f4f4f5'
152
+ const cardBg = props.containerBackgroundColor ?? '#ffffff'
153
+ const width = props.width ?? 600
154
+ const titleTag = props.title !== undefined ? `<title>${esc(props.title)}</title>` : ''
155
+ const previewBlock = props.preview !== undefined
156
+ ? `<div data-pru-preview style="display:none;overflow:hidden;line-height:1px;opacity:0;max-height:0;max-width:0;font-size:1px;">${esc(props.preview)}${PREVIEW_SPACER}</div>`
157
+ : ''
158
+
159
+ return raw(
160
+ `<!DOCTYPE html>`
161
+ + `<html lang="${escAttr(lang)}" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">`
162
+ + `<head>`
163
+ + `<meta charset="utf-8">`
164
+ + `<meta name="viewport" content="width=device-width,initial-scale=1">`
165
+ + `<meta http-equiv="X-UA-Compatible" content="IE=edge">`
166
+ + `<meta name="x-apple-disable-message-reformatting">`
167
+ + `<meta name="color-scheme" content="light dark">`
168
+ + `<meta name="supported-color-schemes" content="light dark">`
169
+ + titleTag
170
+ + `<!--[if gte mso 9]><xml><o:OfficeDocumentSettings><o:AllowPNG/><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml><![endif]-->`
171
+ + `<style>${EMAIL_HEAD_CSS}</style>`
172
+ + `</head>`
173
+ + `<body class="pru-email-bg" style="margin:0;padding:0;background-color:${escAttr(bg)};color:#18181b;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;">`
174
+ + previewBlock
175
+ + `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" class="pru-email-bg" style="background-color:${escAttr(bg)};width:100%;margin:0;padding:24px 0;">`
176
+ + `<tr><td align="center" style="padding:0 12px;">`
177
+ + `<!--[if mso]><table role="presentation" align="center" border="0" cellspacing="0" cellpadding="0" width="${width}"><tr><td width="${width}"><![endif]-->`
178
+ + `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" class="pru-email-card" style="max-width:${width}px;width:100%;margin:0 auto;background-color:${escAttr(cardBg)};border-radius:8px;border:1px solid #e4e4e7;overflow:hidden;">`
179
+ + `<tr><td class="pru-email-pad" style="padding:32px 28px;">${esc(props.children)}</td></tr>`
180
+ + `</table>`
181
+ + `<!--[if mso]></td></tr></table><![endif]-->`
182
+ + `</td></tr></table>`
183
+ + `</body></html>`,
184
+ )
185
+ }
186
+
187
+ /** Table-based email layout section with inline padding and optional background color. */
188
+ export function Section(props: SectionProps = {}): Html {
189
+ const align = safeAlign(props.align)
190
+ let tdStyle = `padding:${props.padding ?? '8px 0'};`
191
+ if (props.backgroundColor !== undefined)
192
+ tdStyle += `background-color:${props.backgroundColor};`
193
+ tdStyle = appendExtraStyle(tdStyle, props.style)
194
+
195
+ return raw(
196
+ `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;">`
197
+ + `<tr><td align="${align}" style="${escAttr(tdStyle)}">${esc(props.children)}</td></tr>`
198
+ + `</table>`,
199
+ )
200
+ }
201
+
202
+ /** Email-safe heading (`h1`–`h3`) with inline typography and dark-mode class. */
203
+ export function Heading(props: HeadingProps = {}): Html {
204
+ const tag = props.as === 'h2' || props.as === 'h3' ? props.as : 'h1'
205
+ let style = HEADING_STYLES[tag]
206
+ if (props.align !== undefined)
207
+ style += `text-align:${safeAlign(props.align)};`
208
+ style = appendExtraStyle(style, props.style)
209
+ return raw(`<${tag} class="pru-email-heading" style="${escAttr(style)}">${esc(props.children)}</${tag}>`)
210
+ }
211
+
212
+ /** Email-safe paragraph with readable line height, inline styles, and optional muted tone. */
213
+ export function Text(props: TextProps = {}): Html {
214
+ const cls = props.muted ? 'pru-email-muted' : 'pru-email-text'
215
+ const color = props.muted ? '#71717a' : '#27272a'
216
+ let style = `margin:0 0 16px;font-size:15px;line-height:1.6;color:${color};`
217
+ if (props.align !== undefined)
218
+ style += `text-align:${safeAlign(props.align)};`
219
+ style = appendExtraStyle(style, props.style)
220
+ return raw(`<p class="${cls}" style="${escAttr(style)}">${esc(props.children)}</p>`)
221
+ }
222
+
223
+ /** Bulletproof Outlook VML + dark-mode CTA button. */
224
+ export function Button(props: ButtonProps): Html {
225
+ const href = safeEmailUrl(props.href, 'Button')
226
+ const bg = props.backgroundColor ?? '#18181b'
227
+ const color = props.color ?? '#ffffff'
228
+ const radius = props.borderRadius ?? 6
229
+ const align = safeAlign(props.align)
230
+ const arcsize = Math.min(50, Math.max(0, Math.round((radius / 44) * 100)))
231
+ const label = esc(props.children)
232
+ // VML cannot size to its text: about 8.5px per character of 15px semibold, plus the 24px side padding.
233
+ const vmlWidth = Math.max(120, Math.round(visibleLength(label) * 8.5) + 48)
234
+ const linkStyle = appendExtraStyle(
235
+ `display:inline-block;padding:12px 24px;background-color:${bg};color:${color};font-size:15px;font-weight:600;line-height:1.2;text-decoration:none;border-radius:${radius}px;mso-hide:all;`,
236
+ props.style,
237
+ )
238
+
239
+ return raw(
240
+ `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;margin:20px 0;">`
241
+ + `<tr><td align="${align}">`
242
+ + `<!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="${escAttr(href)}" style="height:44px;v-text-anchor:middle;width:${vmlWidth}px;" arcsize="${arcsize}%" stroke="f" fillcolor="${escAttr(bg)}"><w:anchorlock/><center style="color:${escAttr(color)};font-family:sans-serif;font-size:15px;font-weight:600;">${label}</center></v:roundrect><![endif]-->`
243
+ + `<!--[if !mso]><!--><a href="${escAttr(href)}" class="pru-email-btn" style="${escAttr(linkStyle)}">${label}</a><!--<![endif]-->`
244
+ + `</td></tr></table>`,
245
+ )
246
+ }
247
+
248
+ /** Horizontal rule styled for email clients and dark mode. */
249
+ export function Divider(props: DividerProps = {}): Html {
250
+ const color = props.color ?? '#e4e4e7'
251
+ const margin = props.margin ?? '24px 0'
252
+ const style = appendExtraStyle(`border:0;border-top:1px solid ${color};margin:${margin};`, props.style)
253
+ return raw(`<hr class="pru-email-divider" style="${escAttr(style)}">`)
254
+ }
255
+
256
+ /** Muted footer section separated by a top border. */
257
+ export function Footer(props: FooterProps = {}): Html {
258
+ const align = safeAlign(props.align)
259
+ const tdStyle = appendExtraStyle(
260
+ 'padding-top:16px;font-size:12px;line-height:1.5;color:#71717a;',
261
+ props.style,
262
+ )
263
+ return raw(
264
+ `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" class="pru-email-divider" style="width:100%;margin-top:24px;border-top:1px solid #e4e4e7;">`
265
+ + `<tr><td align="${align}" class="pru-email-muted" style="${escAttr(tdStyle)}">${esc(props.children)}</td></tr>`
266
+ + `</table>`,
267
+ )
268
+ }
269
+
270
+ /** Styled inline hyperlink for email bodies. */
271
+ export function Link(props: LinkProps): Html {
272
+ const href = safeEmailUrl(props.href, 'Link')
273
+ const color = props.color ?? '#2563eb'
274
+ const style = appendExtraStyle(`color:${color};text-decoration:underline;`, props.style)
275
+ return raw(`<a href="${escAttr(href)}" class="pru-email-link" style="${escAttr(style)}">${esc(props.children)}</a>`)
276
+ }
package/src/index.ts ADDED
@@ -0,0 +1,259 @@
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
+
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'
15
+
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'
25
+
26
+ const DEFAULT_QUEUE_NAME = 'mail.deliver'
27
+ const DEFAULT_RETRY_OPTIONS: JobsQueueOptions = { attempts: 3, backoff: 'exponential' }
28
+
29
+ function isDevOrTest(devFlag: boolean): boolean {
30
+ const env = nodeEnv()
31
+ if (env === 'production')
32
+ return false
33
+ return devFlag || env === 'test'
34
+ }
35
+
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')
46
+
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
59
+ return {
60
+ name: nameOrEntry,
61
+ subject: opts?.subject,
62
+ render: renderOrComponent as () => MailBody,
63
+ }
64
+ }
65
+
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
+ }
84
+ }
85
+
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
+ }
117
+ }
118
+
119
+ export function createMailer(options: MailerOptions = {}): Mailer {
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
+
129
+ let serverDev: boolean | undefined
130
+ let injectJobs: (() => JobsService | undefined) | undefined
131
+ const registeredJobs = new WeakSet<JobsService>()
132
+ const getTransport = createTransportResolver(options.transport)
133
+
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
148
+ }
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
+
182
+ const instance: Mailer = {
183
+ ...plugin,
184
+ outbox,
185
+ isConfigured() {
186
+ return getTransport() !== undefined
187
+ },
188
+ requires() {
189
+ const unmet: string[] = []
190
+ if (getTransport() === undefined && !options.optional)
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).')
192
+ 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()`.')
194
+ return unmet
195
+ },
196
+ clearOutbox() {
197
+ outbox.length = 0
198
+ },
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) {
213
+ assertNoHeaderInjection(message.subject, 'subject')
214
+ const from = message.from ?? options.from ?? process.env.MAIL_FROM ?? 'noreply@localhost'
215
+ const toList = normalizeList(message.to ?? options.to ?? process.env.MAIL_TO, 'to')
216
+ if (toList.length === 0)
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
+
227
+ const record: SentMail = {
228
+ id: crypto.randomUUID(),
229
+ from: formatAddress(from, 'from'),
230
+ to: toList,
231
+ ...(message.replyTo !== undefined ? { replyTo: formatAddress(message.replyTo, 'replyTo') } : {}),
232
+ subject: message.subject,
233
+ ...(text !== undefined ? { text } : {}),
234
+ ...(html !== undefined ? { html } : {}),
235
+ sentAt: new Date().toISOString(),
236
+ }
237
+
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
+ })
248
+
249
+ // Non-dev/test runs keep no copy: the outbox holds sign-in links in plain text, and no preview reads it there.
250
+ if (devOrTest) {
251
+ outbox.unshift(record)
252
+ if (outbox.length > 100)
253
+ outbox.length = 100
254
+ }
255
+ return record
256
+ },
257
+ }
258
+ return instance
259
+ }