@prunellejs/mail 0.1.1 → 0.7.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/LICENSE +21 -0
- package/llms.txt +50 -18
- package/package.json +3 -3
- package/src/components.ts +276 -0
- package/src/index.ts +193 -193
- package/src/preview.ts +84 -0
- package/src/render.ts +119 -0
- package/src/smtp.ts +645 -0
- package/src/transports.ts +254 -0
- package/src/types.ts +161 -0
package/src/index.ts
CHANGED
|
@@ -1,167 +1,186 @@
|
|
|
1
|
-
// @prunellejs/mail —
|
|
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 {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
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
|
|
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
|
-
|
|
11
|
-
|
|
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 === '
|
|
33
|
+
return devFlag || env === 'test'
|
|
85
34
|
}
|
|
86
35
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
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
|
-
|
|
100
|
-
|
|
101
|
-
|
|
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
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
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
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
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
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
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
|
-
...
|
|
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
|
-
|
|
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
|
-
...(
|
|
193
|
-
...(
|
|
233
|
+
...(text !== undefined ? { text } : {}),
|
|
234
|
+
...(html !== undefined ? { html } : {}),
|
|
194
235
|
sentAt: new Date().toISOString(),
|
|
195
236
|
}
|
|
196
237
|
|
|
197
|
-
const devOrTest = isDevOrTest(serverDev ?? (
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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/preview.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// Dev-only outbox and live template preview rendering (`/_pru/mail` and `/_pru/mail.json`).
|
|
2
|
+
// Never emits inline `style="..."` attributes so Prunelle's strict CSP style hash covers the entire page.
|
|
3
|
+
|
|
4
|
+
import type { MailPreviewEntry, RenderedMailPreview, SentMail } from './types'
|
|
5
|
+
import { esc, escAttr } from 'prunelle/server'
|
|
6
|
+
import { renderMail } from './render'
|
|
7
|
+
|
|
8
|
+
const MAIL_OUTBOX_CSS = [
|
|
9
|
+
'body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Noto Sans","Helvetica Neue",Arial,sans-serif;max-width:52rem;margin:2rem auto;padding:0 1rem;background:#f9fafb;color:#111827}',
|
|
10
|
+
'h1{margin:0 0 1.25rem;font-size:1.5rem}',
|
|
11
|
+
'.section-title{margin:2rem 0 .75rem;font-size:1.1rem;color:#374151;border-bottom:1px solid #e5e7eb;padding-bottom:.35rem}',
|
|
12
|
+
'article{border:1px solid #e5e7eb;border-radius:8px;padding:1rem;margin-bottom:1rem;background:#fff}',
|
|
13
|
+
'h2{margin:0 0 .25rem;font-size:1rem}',
|
|
14
|
+
'.meta,.empty{margin:0 0 .5rem;font-size:.85rem;color:#6b7280}',
|
|
15
|
+
'.error{margin:0 0 .5rem;font-size:.85rem;color:#b91c1c;background:#fef2f2;padding:.5rem;border-radius:4px}',
|
|
16
|
+
'iframe{width:100%;min-height:18rem;border:1px solid #f3f4f6;border-radius:4px;background:#fff}',
|
|
17
|
+
'details{margin-top:.5rem}',
|
|
18
|
+
'summary{cursor:pointer;font-size:.8rem;color:#4b5563;user-select:none}',
|
|
19
|
+
'pre{margin:.4rem 0 0;white-space:pre-wrap;font-size:.85rem;background:#f9fafb;padding:.65rem;border-radius:4px;border:1px solid #f3f4f6}',
|
|
20
|
+
].join('')
|
|
21
|
+
|
|
22
|
+
export async function renderPreviewEntries(entries: readonly MailPreviewEntry[]): Promise<RenderedMailPreview[]> {
|
|
23
|
+
const results: RenderedMailPreview[] = []
|
|
24
|
+
for (const entry of entries) {
|
|
25
|
+
const subject = entry.subject ?? entry.name
|
|
26
|
+
try {
|
|
27
|
+
const rendered = await renderMail(entry.render())
|
|
28
|
+
results.push({
|
|
29
|
+
name: entry.name,
|
|
30
|
+
subject,
|
|
31
|
+
...(entry.props !== undefined ? { props: entry.props } : {}),
|
|
32
|
+
html: rendered.html,
|
|
33
|
+
text: rendered.text,
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
catch (err) {
|
|
37
|
+
results.push({
|
|
38
|
+
name: entry.name,
|
|
39
|
+
subject,
|
|
40
|
+
...(entry.props !== undefined ? { props: entry.props } : {}),
|
|
41
|
+
error: err instanceof Error ? err.message : String(err),
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return results
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function renderSentArticle(m: SentMail): string {
|
|
49
|
+
const meta = `From: ${esc(m.from)} → To: ${esc(m.to.join(', '))}${m.replyTo ? ` (Reply-To: ${esc(m.replyTo)})` : ''} · ${esc(m.sentAt)}`
|
|
50
|
+
let body: string
|
|
51
|
+
if (m.html) {
|
|
52
|
+
body = `<iframe sandbox="" srcdoc="${escAttr(m.html)}" title="${escAttr(m.subject)}"></iframe>`
|
|
53
|
+
+ (m.text !== undefined ? `<details><summary>Plain text</summary><pre>${esc(m.text)}</pre></details>` : '')
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
body = `<pre>${esc(m.text ?? '')}</pre>`
|
|
57
|
+
}
|
|
58
|
+
return `<article><h2>${esc(m.subject)}</h2><p class="meta">${meta}</p>${body}</article>`
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function renderPreviewArticle(p: RenderedMailPreview): string {
|
|
62
|
+
const propsMeta = p.props !== undefined ? ` · Props: ${esc(JSON.stringify(p.props))}` : ''
|
|
63
|
+
const meta = `Template: ${esc(p.name)} · Subject: ${esc(p.subject)}${propsMeta}`
|
|
64
|
+
if (p.error !== undefined)
|
|
65
|
+
return `<article><h2>${esc(p.name)}</h2><p class="meta">${meta}</p><p class="error">${esc(p.error)}</p></article>`
|
|
66
|
+
|
|
67
|
+
const frame = p.html !== undefined
|
|
68
|
+
? `<iframe sandbox="" srcdoc="${escAttr(p.html)}" title="${escAttr(p.name)}"></iframe>`
|
|
69
|
+
: ''
|
|
70
|
+
const textBlock = p.text !== undefined
|
|
71
|
+
? `<details open><summary>Plain text</summary><pre>${esc(p.text)}</pre></details>`
|
|
72
|
+
: ''
|
|
73
|
+
return `<article><h2>${esc(p.name)}</h2><p class="meta">${meta}</p>${frame}${textBlock}</article>`
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function renderOutboxHtml(outbox: readonly SentMail[], previews: readonly RenderedMailPreview[]): string {
|
|
77
|
+
const sentRows = outbox.map(renderSentArticle).join('')
|
|
78
|
+
const previewSection = previews.length > 0
|
|
79
|
+
? `<section><h2 class="section-title">Templates / Previews (${previews.length})</h2>${previews.map(renderPreviewArticle).join('')}</section>`
|
|
80
|
+
: ''
|
|
81
|
+
const sentSection = `<section><h2 class="section-title">Sent Messages (${outbox.length})</h2>${sentRows || '<p class="empty">No messages sent yet.</p>'}</section>`
|
|
82
|
+
|
|
83
|
+
return `<!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>${previewSection}${sentSection}</body></html>`
|
|
84
|
+
}
|
package/src/render.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Renders JSX/TSX email bodies (compiled Prunelle Html or direct runtime components) to HTML + clean plain text.
|
|
2
|
+
|
|
3
|
+
import type { MailBody, RenderedMail } from './types'
|
|
4
|
+
import { esc } from 'prunelle/server'
|
|
5
|
+
|
|
6
|
+
const NAMED_ENTITIES: Readonly<Record<string, string>> = {
|
|
7
|
+
amp: '&',
|
|
8
|
+
lt: '<',
|
|
9
|
+
gt: '>',
|
|
10
|
+
quot: '"',
|
|
11
|
+
apos: '\'',
|
|
12
|
+
nbsp: ' ',
|
|
13
|
+
ndash: '-',
|
|
14
|
+
mdash: '--',
|
|
15
|
+
hellip: '...',
|
|
16
|
+
copy: '(c)',
|
|
17
|
+
reg: '(R)',
|
|
18
|
+
trade: '(TM)',
|
|
19
|
+
bull: '*',
|
|
20
|
+
middot: '*',
|
|
21
|
+
zwnj: '',
|
|
22
|
+
zwj: '',
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const DOCTYPE_RE = /<!DOCTYPE[^>]*>/gi
|
|
26
|
+
const HEAD_BLOCK_RE = /<head\b[^>]*>[\s\S]*?<\/head>/gi
|
|
27
|
+
const STYLE_OR_SCRIPT_RE = /<(style|script|title)\b[^>]*>[\s\S]*?<\/\1>/gi
|
|
28
|
+
const PREVIEW_BLOCK_RE = /<div\b[^>]*\bdata-pru-preview\b[^>]*>[\s\S]*?<\/div>/gi
|
|
29
|
+
const HTML_COMMENT_RE = /<!--[\s\S]*?-->/g
|
|
30
|
+
const ANCHOR_RE = /<a\b([^>]*)>([\s\S]*?)<\/a>/gi
|
|
31
|
+
const HREF_ATTR_RE = /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i
|
|
32
|
+
const HR_RE = /<hr\b[^>]*\/?>/gi
|
|
33
|
+
const BR_RE = /<br\b[^>]*\/?>/gi
|
|
34
|
+
const LIST_ITEM_RE = /<li\b[^>]*>/gi
|
|
35
|
+
const DOUBLE_BREAK_OPEN_RE = /<(?:h[1-6]|p|blockquote|ul|ol)\b[^>]*>/gi
|
|
36
|
+
const DOUBLE_BREAK_CLOSE_RE = /<\/(?:h[1-6]|p|blockquote|ul|ol|table|section|header|footer)>/gi
|
|
37
|
+
const SINGLE_BREAK_CLOSE_RE = /<\/(?:div|tr)>/gi
|
|
38
|
+
const TAG_RE = /<[^>]+>/g
|
|
39
|
+
const ENTITY_RE = /&(#x[0-9a-f]+|#\d+|[a-z]+);/gi
|
|
40
|
+
const MULTI_SPACE_RE = /[ \t\f\v]+/g
|
|
41
|
+
const MULTI_BLANK_LINE_RE = /\n{3,}/g
|
|
42
|
+
|
|
43
|
+
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
|
|
44
|
+
return typeof value === 'object' && value !== null && 'then' in value && typeof (value as { then?: unknown }).then === 'function'
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function resolveBodyToHtml(node: unknown): Promise<string> {
|
|
48
|
+
if (typeof node === 'function')
|
|
49
|
+
return resolveBodyToHtml((node as () => unknown)())
|
|
50
|
+
if (isPromiseLike(node))
|
|
51
|
+
return resolveBodyToHtml(await node)
|
|
52
|
+
if (node == null || typeof node === 'boolean')
|
|
53
|
+
return ''
|
|
54
|
+
if (Array.isArray(node)) {
|
|
55
|
+
let out = ''
|
|
56
|
+
for (let i = 0; i < node.length; i++)
|
|
57
|
+
out += await resolveBodyToHtml(node[i])
|
|
58
|
+
return out
|
|
59
|
+
}
|
|
60
|
+
return esc(node)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function decodeHtmlEntities(text: string): string {
|
|
64
|
+
return text.replace(ENTITY_RE, (full, body: string) => {
|
|
65
|
+
if (body.startsWith('#x') || body.startsWith('#X')) {
|
|
66
|
+
const cp = Number.parseInt(body.slice(2), 16)
|
|
67
|
+
return Number.isFinite(cp) && cp >= 0 && cp <= 0x10FFFF ? String.fromCodePoint(cp) : full
|
|
68
|
+
}
|
|
69
|
+
if (body.startsWith('#')) {
|
|
70
|
+
const cp = Number.parseInt(body.slice(1), 10)
|
|
71
|
+
return Number.isFinite(cp) && cp >= 0 && cp <= 0x10FFFF ? String.fromCodePoint(cp) : full
|
|
72
|
+
}
|
|
73
|
+
return NAMED_ENTITIES[body.toLowerCase()] ?? full
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function replaceAnchorWithText(_full: string, attrs: string, inner: string): string {
|
|
78
|
+
const hrefMatch = HREF_ATTR_RE.exec(attrs)
|
|
79
|
+
const rawHref = hrefMatch !== null ? (hrefMatch[1] ?? hrefMatch[2] ?? hrefMatch[3] ?? '') : ''
|
|
80
|
+
const href = decodeHtmlEntities(rawHref).trim()
|
|
81
|
+
const label = decodeHtmlEntities(inner.replace(TAG_RE, '')).replace(MULTI_SPACE_RE, ' ').trim()
|
|
82
|
+
if (href.length === 0)
|
|
83
|
+
return label
|
|
84
|
+
if (label.length === 0)
|
|
85
|
+
return href
|
|
86
|
+
const bareHref = href.startsWith('mailto:') ? href.slice('mailto:'.length) : href
|
|
87
|
+
if (label === href || label === bareHref)
|
|
88
|
+
return label
|
|
89
|
+
return `${label} (${href})`
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Converts email HTML into a clean, readable plain-text alternative part. */
|
|
93
|
+
export function htmlToText(html: string): string {
|
|
94
|
+
let out = html
|
|
95
|
+
.replace(DOCTYPE_RE, '')
|
|
96
|
+
.replace(HEAD_BLOCK_RE, '')
|
|
97
|
+
.replace(STYLE_OR_SCRIPT_RE, '')
|
|
98
|
+
.replace(PREVIEW_BLOCK_RE, '')
|
|
99
|
+
.replace(HTML_COMMENT_RE, '')
|
|
100
|
+
.replace(ANCHOR_RE, replaceAnchorWithText)
|
|
101
|
+
.replace(HR_RE, '\n\n---\n\n')
|
|
102
|
+
.replace(BR_RE, '\n')
|
|
103
|
+
.replace(LIST_ITEM_RE, '\n- ')
|
|
104
|
+
.replace(DOUBLE_BREAK_OPEN_RE, '\n\n')
|
|
105
|
+
.replace(DOUBLE_BREAK_CLOSE_RE, '\n\n')
|
|
106
|
+
.replace(SINGLE_BREAK_CLOSE_RE, '\n')
|
|
107
|
+
.replace(TAG_RE, '')
|
|
108
|
+
|
|
109
|
+
out = decodeHtmlEntities(out).replace(/\r\n?/g, '\n')
|
|
110
|
+
|
|
111
|
+
const lines = out.split('\n').map(line => line.replace(MULTI_SPACE_RE, ' ').trim())
|
|
112
|
+
return lines.join('\n').replace(MULTI_BLANK_LINE_RE, '\n\n').trim()
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Renders a JSX/TSX email component, compiled Html, or lazy factory to both `html` and `text`. */
|
|
116
|
+
export async function renderMail(body: MailBody): Promise<RenderedMail> {
|
|
117
|
+
const html = await resolveBodyToHtml(body)
|
|
118
|
+
return { html, text: htmlToText(html) }
|
|
119
|
+
}
|