@hamur/mail 0.0.0-stage → 0.0.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.
Files changed (90) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +14 -2
  3. package/dist/src/devtools.js +268 -0
  4. package/dist/src/index.js +573 -0
  5. package/dist/src/server/index.js +916 -0
  6. package/dist/src/test.js +39 -0
  7. package/dist/types/src/address.d.ts +14 -0
  8. package/dist/types/src/build/devtools.d.ts +20 -0
  9. package/dist/types/src/build/outbox.d.ts +35 -0
  10. package/dist/types/src/build/setup.d.ts +22 -0
  11. package/dist/types/src/build/templates.d.ts +12 -0
  12. package/dist/types/src/devtools-model.d.ts +12 -0
  13. package/dist/types/src/devtools.d.ts +2 -0
  14. package/dist/types/src/html.d.ts +10 -0
  15. package/dist/types/src/index.d.ts +24 -0
  16. package/dist/types/src/mime.d.ts +32 -0
  17. package/dist/types/src/module.d.ts +3 -0
  18. package/dist/types/src/options.d.ts +12 -0
  19. package/dist/types/src/server/deliver.d.ts +15 -0
  20. package/dist/types/src/server/devtools-routes.d.ts +1 -0
  21. package/dist/types/src/server/door-dev.d.ts +3 -0
  22. package/dist/types/src/server/door.d.ts +2 -0
  23. package/dist/types/src/server/hooks.d.ts +5 -0
  24. package/dist/types/src/server/index.d.ts +6 -0
  25. package/dist/types/src/server/message.d.ts +3 -0
  26. package/dist/types/src/server/plugin.d.ts +1 -0
  27. package/dist/types/src/server/preview.d.ts +8 -0
  28. package/dist/types/src/server/queue.d.ts +19 -0
  29. package/dist/types/src/server/runtime.d.ts +5 -0
  30. package/dist/types/src/server/send.d.ts +54 -0
  31. package/dist/types/src/server/task.d.ts +4 -0
  32. package/dist/types/src/server/template.d.ts +8 -0
  33. package/dist/types/src/smtp/client.d.ts +28 -0
  34. package/dist/types/src/smtp/dkim.d.ts +8 -0
  35. package/dist/types/src/smtp/sockets.d.ts +42 -0
  36. package/dist/types/src/test.d.ts +27 -0
  37. package/dist/types/src/transport.d.ts +28 -0
  38. package/dist/types/src/transports/cloudflare.d.ts +17 -0
  39. package/dist/types/src/transports/http.d.ts +26 -0
  40. package/dist/types/src/transports/mailgun.d.ts +9 -0
  41. package/dist/types/src/transports/outbox.d.ts +9 -0
  42. package/dist/types/src/transports/postmark.d.ts +8 -0
  43. package/dist/types/src/transports/resend.d.ts +7 -0
  44. package/dist/types/src/transports/sendgrid.d.ts +7 -0
  45. package/dist/types/src/transports/ses.d.ts +9 -0
  46. package/dist/types/src/transports/smtp.d.ts +3 -0
  47. package/dist/types/src/types.d.ts +124 -0
  48. package/package.json +48 -4
  49. package/src/address.ts +86 -0
  50. package/src/build/devtools.ts +81 -0
  51. package/src/build/outbox.ts +69 -0
  52. package/src/build/setup.ts +226 -0
  53. package/src/build/templates.ts +113 -0
  54. package/src/devtools-model.ts +24 -0
  55. package/src/devtools.ts +351 -0
  56. package/src/env.d.ts +36 -0
  57. package/src/html.ts +274 -0
  58. package/src/index.ts +25 -0
  59. package/src/mime.ts +220 -0
  60. package/src/module.ts +11 -0
  61. package/src/options.ts +157 -0
  62. package/src/server/deliver.ts +54 -0
  63. package/src/server/devtools-routes.ts +32 -0
  64. package/src/server/door-dev.ts +6 -0
  65. package/src/server/door.ts +4 -0
  66. package/src/server/hooks.ts +13 -0
  67. package/src/server/index.ts +28 -0
  68. package/src/server/message.ts +36 -0
  69. package/src/server/plugin.ts +4 -0
  70. package/src/server/preview.ts +41 -0
  71. package/src/server/queue.ts +58 -0
  72. package/src/server/runtime.ts +45 -0
  73. package/src/server/send.ts +308 -0
  74. package/src/server/task.ts +13 -0
  75. package/src/server/template.ts +37 -0
  76. package/src/smtp/client.ts +305 -0
  77. package/src/smtp/dkim.ts +72 -0
  78. package/src/smtp/sockets.ts +296 -0
  79. package/src/test.ts +70 -0
  80. package/src/transport.ts +35 -0
  81. package/src/transports/cloudflare.ts +68 -0
  82. package/src/transports/http.ts +75 -0
  83. package/src/transports/mailgun.ts +31 -0
  84. package/src/transports/outbox.ts +64 -0
  85. package/src/transports/postmark.ts +59 -0
  86. package/src/transports/resend.ts +46 -0
  87. package/src/transports/sendgrid.ts +64 -0
  88. package/src/transports/ses.ts +53 -0
  89. package/src/transports/smtp.ts +37 -0
  90. package/src/types.ts +104 -0
@@ -0,0 +1,54 @@
1
+ import type { Logger } from "hamur/server"
2
+ import { addressList, parseAddress } from "../address.ts"
3
+ import type { MailMessage } from "../types.ts"
4
+ import { shown } from "../transports/http.ts"
5
+ import { messageDeps } from "./message.ts"
6
+ import { sendOnce } from "./queue.ts"
7
+ import { transmitDeps } from "./runtime.ts"
8
+ import { createSendMail } from "./send.ts"
9
+
10
+ export interface MailDelivery {
11
+ /** The same on every attempt: the left side of the Message-ID. */
12
+ id: string
13
+ /** The site URL links are absolute on; default the app's. */
14
+ site?: string
15
+ /** Whether the caller is a queued run: what `mail:sent` reports. */
16
+ queued: boolean
17
+ }
18
+
19
+ /** Each address of the message as the app wrote it and as a transport repeats it. */
20
+ function addressesOf({ from, to, cc, bcc, replyTo }: MailMessage): string[] {
21
+ return [from, to, cc, bcc, replyTo].flatMap(addressList).flatMap((value) => {
22
+ const written = typeof value === "string" ? value : (value as { address?: unknown } | undefined)?.address
23
+ return [written, parseAddress(value)?.address].filter((text): text is string => typeof text === "string")
24
+ })
25
+ }
26
+
27
+ /**
28
+ * A message sent in the call by the rule of the queue, for a delivery of another package. It rejects only when no
29
+ * recipient can have the message; a failure after which one may have it is what it resolves to. No error holds an address.
30
+ */
31
+ export async function deliverMail(
32
+ message: MailMessage,
33
+ { id, site, queued }: MailDelivery,
34
+ log: Pick<Logger, "error">,
35
+ ): Promise<Error | undefined> {
36
+ const unconfirmed: Error[] = []
37
+ const send = createSendMail({
38
+ ...messageDeps(site),
39
+ id,
40
+ queue: true,
41
+ async enqueue(mail) {
42
+ const failure = await sendOnce(transmitDeps, mail, log, queued)
43
+ if (failure) unconfirmed.push(failure)
44
+ },
45
+ })
46
+ try {
47
+ await send(message)
48
+ } catch (error) {
49
+ const text = error instanceof Error ? error.message : String(error)
50
+ const clean = shown(text, addressesOf(message))
51
+ throw clean === shown(text, []) ? error : new Error(clean)
52
+ }
53
+ return unconfirmed[0]
54
+ }
@@ -0,0 +1,32 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import { baseURL, lang, siteUrl, templates } from "#hamur/mail/config"
3
+ import { renderComponent, templates as components } from "#hamur/mail/templates"
4
+ import { defineHandler, useSiteConfig } from "hamur/server"
5
+ import { answerPreview } from "./preview.ts"
6
+ import { renderTemplate } from "./template.ts"
7
+
8
+ export const devtoolsMailRender = defineHandler({
9
+ route: "/_hamur/devtools/api/mail/render",
10
+ method: "*",
11
+ raw: true,
12
+ meta: { hidden: true },
13
+ handler: (_, { event }) => {
14
+ const { pathname } = new URL(event.request.url)
15
+ if (!pathname.endsWith("/_hamur/devtools/api/mail/render"))
16
+ return new Response(JSON.stringify({ error: 'No devtools data route "mail/render"' }), {
17
+ status: 404,
18
+ headers: { "content-type": "application/json" },
19
+ })
20
+ return answerPreview(event.request, {
21
+ templates,
22
+ async render(name, props, request) {
23
+ const { default: component } = await components[name]!()
24
+ let origin = siteUrl ?? new URL(request.url).origin
25
+ try {
26
+ origin = useSiteConfig(event).url ?? origin
27
+ } catch {}
28
+ return renderTemplate(renderComponent!, component, props, { origin, baseURL, lang })
29
+ },
30
+ })
31
+ },
32
+ })
@@ -0,0 +1,6 @@
1
+ import { defineServer } from "hamur/server"
2
+ import { mailPlugin } from "./plugin.ts"
3
+
4
+ export { devtoolsMailRender } from "./devtools-routes.ts"
5
+
6
+ export default defineServer({ plugins: [mailPlugin] })
@@ -0,0 +1,4 @@
1
+ import { defineServer } from "hamur/server"
2
+ import { mailPlugin } from "./plugin.ts"
3
+
4
+ export default defineServer({ plugins: [mailPlugin] })
@@ -0,0 +1,13 @@
1
+ import type { Hooks } from "hamur/kit"
2
+ import type { ServerHooks } from "hamur/server"
3
+
4
+ let current: Hooks<ServerHooks> | undefined
5
+
6
+ /** The door's plugin hands over the server's hooks at start, before any request. */
7
+ export function setServerHooks(hooks: Hooks<ServerHooks>): void {
8
+ current = hooks
9
+ }
10
+
11
+ export function serverHooks(): Hooks<ServerHooks> | undefined {
12
+ return current
13
+ }
@@ -0,0 +1,28 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import { queue, testBuild } from "#hamur/mail/config"
3
+ import { enqueue, useLogger, type TaskName } from "hamur/server"
4
+ import type { MailMessage, MailResult, MailTemplateName } from "../types.ts"
5
+ import { messageDeps } from "./message.ts"
6
+ import { packMail, sendQueued } from "./queue.ts"
7
+ import { transmitDeps } from "./runtime.ts"
8
+ import { createSendMail } from "./send.ts"
9
+
10
+ /** A string, since `TaskName` holds the task only in an app with `@hamur/mail`. */
11
+ const TASK: string = "mail:send"
12
+
13
+ const send = createSendMail({
14
+ ...messageDeps(),
15
+ queue,
16
+ enqueue: (mail, delay) =>
17
+ testBuild
18
+ ? sendQueued(transmitDeps, mail, useLogger())
19
+ : enqueue(TASK as TaskName, packMail(mail) as never, delay === undefined ? {} : { delay }),
20
+ })
21
+
22
+ /** Checks the message, runs `mail:beforeSend`, writes the MIME message and hands it to `mail.transport` or the queue. */
23
+ export function sendMail<T extends MailTemplateName>(
24
+ message: MailMessage<T>,
25
+ options?: { queue?: boolean; delay?: number },
26
+ ): Promise<MailResult> {
27
+ return send(message as MailMessage, options)
28
+ }
@@ -0,0 +1,36 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import { baseURL, from, lang, replyTo, templates } from "#hamur/mail/config"
3
+ import { renderComponent, templates as components } from "#hamur/mail/templates"
4
+ import { useEvent, type HamurEvent } from "hamur/server"
5
+ import { siteOrigin, transmitDeps } from "./runtime.ts"
6
+ import type { SendMailDeps } from "./send.ts"
7
+ import { renderTemplate } from "./template.ts"
8
+
9
+ function currentEvent(): HamurEvent | undefined {
10
+ try {
11
+ return useEvent()
12
+ } catch {
13
+ return undefined
14
+ }
15
+ }
16
+
17
+ /** What checking, rendering and sending a message takes in this app; `site` replaces the site URL of the request it is called in. */
18
+ export const messageDeps = (site?: string): Omit<SendMailDeps, "queue" | "enqueue"> => ({
19
+ ...transmitDeps,
20
+ from,
21
+ ...(replyTo ? { replyTo } : {}),
22
+ templates,
23
+ async render(name, props, event) {
24
+ const { default: component } = await components[name]!()
25
+ return renderTemplate(renderComponent!, component, props, {
26
+ origin: site ?? siteOrigin(event) ?? "http://localhost",
27
+ baseURL,
28
+ lang,
29
+ })
30
+ },
31
+ event: currentEvent,
32
+ host: (event) => {
33
+ const origin = site ?? siteOrigin(event)
34
+ return origin ? new URL(origin).hostname : "localhost"
35
+ },
36
+ })
@@ -0,0 +1,4 @@
1
+ import { definePlugin } from "hamur/server"
2
+ import { setServerHooks } from "./hooks.ts"
3
+
4
+ export const mailPlugin = definePlugin((server) => setServerHooks(server.hooks))
@@ -0,0 +1,41 @@
1
+ import { htmlToText } from "../html.ts"
2
+
3
+ const BODY_MAX = 1024 * 1024
4
+ const HEADERS = { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff" }
5
+
6
+ const answer = (body: unknown, status = 200, extra: Record<string, string> = {}): Response =>
7
+ new Response(JSON.stringify(body), { status, headers: { ...HEADERS, ...extra } })
8
+
9
+ export interface PreviewDeps {
10
+ /** The names of the `app/mail/` templates. */
11
+ templates: readonly string[]
12
+ /** The HTML document of a template, as `sendMail` renders it. */
13
+ render(template: string, props: Record<string, unknown>, request: Request): Promise<string>
14
+ }
15
+
16
+ /** `POST api/mail/render` with `{ template, props? }`: the template's document and its text part; nothing is sent. */
17
+ export async function answerPreview(request: Request, deps: PreviewDeps): Promise<Response> {
18
+ if (request.method !== "POST")
19
+ return answer({ error: 'Devtools data route "mail/render" answers POST' }, 405, { allow: "POST" })
20
+ const text = await request.text()
21
+ if (text.length > BODY_MAX) return answer({ error: `The body is over ${BODY_MAX} bytes` }, 413)
22
+ let body: unknown
23
+ try {
24
+ body = JSON.parse(text)
25
+ } catch {
26
+ return answer({ error: "The body is not JSON" }, 400)
27
+ }
28
+ if (typeof body !== "object" || body === null || Array.isArray(body))
29
+ return answer({ error: "The body must be an object: { template, props? }" }, 400)
30
+ const { template, props = {} } = body as { template?: unknown; props?: unknown }
31
+ if (typeof template !== "string" || !deps.templates.includes(template))
32
+ return answer({ error: `No mail template ${JSON.stringify(template)}` }, 404)
33
+ if (typeof props !== "object" || props === null || Array.isArray(props))
34
+ return answer({ error: "props must be a JSON object" }, 400)
35
+ try {
36
+ const html = await deps.render(template, props as Record<string, unknown>, request)
37
+ return answer({ html, text: htmlToText(html) })
38
+ } catch (error) {
39
+ return answer({ error: error instanceof Error ? error.message : String(error) }, 500)
40
+ }
41
+ }
@@ -0,0 +1,58 @@
1
+ import type { Logger } from "hamur/server"
2
+ import { shown } from "../transports/http.ts"
3
+ import { UnconfirmedError, type OutgoingMail } from "../transport.ts"
4
+ import type { MailMessage, RenderedMail } from "../types.ts"
5
+ import { mailFailure, outgoingMail, transmit, type TransmitDeps } from "./send.ts"
6
+
7
+ /** The payload of `mail:send`: the message as rendered. The run writes its MIME text, which would hold each body a second time. */
8
+ export interface QueuedMail {
9
+ id: string
10
+ date: Date
11
+ message: RenderedMail
12
+ }
13
+
14
+ export function packMail({ id, date, message }: OutgoingMail): QueuedMail {
15
+ return { id, date, message }
16
+ }
17
+
18
+ export function unpackMail({ id, date, message }: QueuedMail): OutgoingMail {
19
+ return outgoingMail(id, date, message)
20
+ }
21
+
22
+ /** `failure` for a log, a span or a queue's own record: its reason without an address, and no `cause`, which the logger prints. */
23
+ function withoutAddresses(failure: Error, { from, to, cc, bcc, replyTo }: RenderedMail): Error {
24
+ const addresses = [from, ...to, ...cc, ...bcc, ...(replyTo ? [replyTo] : [])].map(({ address }) => address)
25
+ return new Error(shown(failure.message, addresses))
26
+ }
27
+
28
+ /**
29
+ * One attempt. It rejects only when no recipient can have the message; after an `UnconfirmedError` it resolves to the
30
+ * failure, and a hook that throws is logged. `queued` is what `mail:sent` reports.
31
+ */
32
+ export async function sendOnce(
33
+ deps: TransmitDeps,
34
+ mail: OutgoingMail,
35
+ log: Pick<Logger, "error">,
36
+ queued: boolean,
37
+ ): Promise<Error | undefined> {
38
+ const message = mail.message as unknown as MailMessage
39
+ const hooks = deps.hooks()
40
+ try {
41
+ await transmit(deps, mail)
42
+ } catch (recorded) {
43
+ const failure = mailFailure(recorded)
44
+ await hooks?.callHook("mail:error", failure, message).catch((error: unknown) => log.error(error))
45
+ const reported = withoutAddresses(failure, mail.message)
46
+ if (!(failure.cause instanceof UnconfirmedError)) throw reported
47
+ return reported
48
+ }
49
+ await hooks?.callHook("mail:sent", { id: mail.id, queued }, message).catch((error: unknown) => log.error(error))
50
+ deps.sent?.({ label: mail.message.template ?? "html", to: mail.message.to, event: undefined })
51
+ return undefined
52
+ }
53
+
54
+ /** The run of `mail:send`: it rejects, so that the queue runs it again, when `sendOnce` does. */
55
+ export async function sendQueued(deps: TransmitDeps, mail: OutgoingMail, log: Pick<Logger, "error">): Promise<void> {
56
+ const unconfirmed = await sendOnce(deps, mail, log, true)
57
+ if (unconfirmed) log.error(unconfirmed, `${unconfirmed.message}; the queue does not send it again`)
58
+ }
@@ -0,0 +1,45 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import { baseURL, dev, reuse, siteUrl, transport, transports } from "#hamur/mail/config"
3
+ import { useLogger, useSiteConfig, withSpan, type HamurEvent } from "hamur/server"
4
+ import type { MailSender } from "../transport.ts"
5
+ import { serverHooks } from "./hooks.ts"
6
+ import type { TransmitDeps } from "./send.ts"
7
+
8
+ let opened: Promise<MailSender> | undefined
9
+
10
+ function open(): Promise<MailSender> {
11
+ return (opened ??= (async () => {
12
+ if (!transport) throw new Error("@hamur/mail has no mail.transport in this run")
13
+ const load = transports[transport.type]
14
+ if (!load) throw new Error(`the ${transport.type} transport is not part of this version of @hamur/mail`)
15
+ return (await load()).default(transport, { reuse })
16
+ })().catch((error: unknown) => {
17
+ opened = undefined
18
+ throw error
19
+ }))
20
+ }
21
+
22
+ export function siteOrigin(event: HamurEvent | undefined): string | undefined {
23
+ try {
24
+ return useSiteConfig(event).url ?? siteUrl ?? undefined
25
+ } catch {
26
+ return siteUrl ?? undefined
27
+ }
28
+ }
29
+
30
+ /** What a send in the call and the task `mail:send` share. */
31
+ export const transmitDeps: TransmitDeps = {
32
+ transport: transport?.type ?? "none",
33
+ open,
34
+ hooks: serverHooks,
35
+ span: (name, fn, options) => withSpan(name, fn, options),
36
+ sent({ label, to, event }) {
37
+ if (!dev || transport?.type !== "outbox") return
38
+ const origin = event ? new URL(event.request.url).origin : (siteOrigin(undefined) ?? "")
39
+ useLogger(event)
40
+ .child({ name: "mail" })
41
+ .info(
42
+ `${label} → ${to.map((address) => address.address).join(", ")} (open in devtools: ${origin}${baseURL}_hamur/devtools/#/mail)`,
43
+ )
44
+ },
45
+ }
@@ -0,0 +1,308 @@
1
+ import type { Hooks } from "hamur/kit"
2
+ import type { HamurEvent, ServerHooks } from "hamur/server"
3
+ import { contentType as typeOfFile } from "hamur/server/http"
4
+ import { addressList, parseAddress } from "../address.ts"
5
+ import { htmlToText } from "../html.ts"
6
+ import { writeMime } from "../mime.ts"
7
+ import type { MailSender, OutgoingMail } from "../transport.ts"
8
+ import type { MailMessage, MailResult, ParsedAddress, RenderedMail } from "../types.ts"
9
+
10
+ /** Headers `sendMail` writes itself, each with the option that sets it where there is one. */
11
+ const OWN_HEADERS: Record<string, string | undefined> = {
12
+ from: "from",
13
+ to: "to",
14
+ cc: "cc",
15
+ bcc: "bcc",
16
+ subject: "subject",
17
+ "reply-to": "replyTo",
18
+ date: undefined,
19
+ "message-id": undefined,
20
+ "mime-version": undefined,
21
+ "content-type": undefined,
22
+ "content-transfer-encoding": undefined,
23
+ }
24
+ /** RFC 5322 field-name characters, at most 76 so the name and its colon fit a 78-character line. */
25
+ const HEADER_NAME = /^[!-9;-~]{1,76}$/
26
+ /** Every C0 control but HTAB, and DEL: none may reach a header line. */
27
+ const CONTROL = /[\x00-\x08\x0a-\x1f\x7f]/
28
+ /** `Content-Type: ` or `Content-ID: <>` and the value stay within 998 octets. */
29
+ const MAX_PART_VALUE = 900
30
+ const TOKEN = "[!#$%&'*+.^_`|~0-9A-Za-z-]+"
31
+ const CONTENT_TYPE = new RegExp(`^${TOKEN}/${TOKEN}(?:\\s*;\\s*${TOKEN}=(?:${TOKEN}|"[^"\\\\\\x00-\\x1f\\x7f]*"))*$`)
32
+ const CONTENT_ID = /^[!#-;=?-~]+$/
33
+ const encoder = new TextEncoder()
34
+
35
+ const isContentType = (value: string): boolean => value.length <= MAX_PART_VALUE && CONTENT_TYPE.test(value)
36
+
37
+ type Span = <T>(
38
+ name: string,
39
+ fn: () => Promise<T>,
40
+ options: { kind: "client"; attributes: Record<string, string> },
41
+ ) => Promise<T>
42
+
43
+ /** What handing one message to the transport takes. */
44
+ export interface TransmitDeps {
45
+ /** `mail.transport.type` of the run, for messages and the span. */
46
+ transport: string
47
+ open: () => Promise<MailSender>
48
+ hooks: () => Hooks<ServerHooks> | undefined
49
+ span: Span
50
+ /** Called after each send; the server logs the dev line from it. */
51
+ sent?: (info: { label: string; to: ParsedAddress[]; event: HamurEvent | undefined }) => void
52
+ }
53
+
54
+ export interface SendMailDeps extends TransmitDeps {
55
+ from: ParsedAddress
56
+ replyTo?: ParsedAddress
57
+ /** The names of the `app/mail/` templates. */
58
+ templates: readonly string[]
59
+ /** The HTML document of a template. */
60
+ render: (template: string, props: Record<string, unknown>, event: HamurEvent | undefined) => Promise<string>
61
+ event: () => HamurEvent | undefined
62
+ /** The host of `site.url`, the right side of each Message-ID. */
63
+ host: (event: HamurEvent | undefined) => string
64
+ /** The left side of the Message-ID; default a random UUID. */
65
+ id?: string
66
+ /** `mail.queue`. */
67
+ queue: boolean
68
+ /** Hands the message to the task `mail:send`; resolves when the queue took it. */
69
+ enqueue: (mail: OutgoingMail, delay: number | undefined) => Promise<void>
70
+ }
71
+
72
+ const isObject = (value: unknown): value is Record<string, unknown> =>
73
+ typeof value === "object" && value !== null && !Array.isArray(value)
74
+
75
+ function shown(value: unknown): string {
76
+ if (value === undefined) return "undefined"
77
+ if (typeof value === "function") return "a function"
78
+ return JSON.stringify(value)
79
+ }
80
+
81
+ function addresses(field: "to" | "cc" | "bcc", value: unknown): ParsedAddress[] {
82
+ return addressList(value).map((item, at) => {
83
+ const parsed = parseAddress(item)
84
+ if (!parsed) throw new TypeError(`sendMail ${field}[${at}] ${shown(item)} is not an address`)
85
+ return parsed
86
+ })
87
+ }
88
+
89
+ function single(field: "from" | "replyTo", value: unknown): ParsedAddress | undefined {
90
+ if (value === undefined) return undefined
91
+ const parsed = parseAddress(value)
92
+ if (!parsed) throw new TypeError(`sendMail ${field} ${shown(value)} is not an address`)
93
+ return parsed
94
+ }
95
+
96
+ function checkHeaders(headers: unknown): Record<string, string> {
97
+ if (headers === undefined) return {}
98
+ if (!isObject(headers)) throw new TypeError(`sendMail headers must be an object (got ${shown(headers)})`)
99
+ const checked: Record<string, string> = {}
100
+ for (const [name, value] of Object.entries(headers)) {
101
+ if (!HEADER_NAME.test(name)) throw new TypeError(`sendMail headers[${JSON.stringify(name)}] is not a header name`)
102
+ const lower = name.toLowerCase()
103
+ if (Object.hasOwn(OWN_HEADERS, lower)) {
104
+ const option = OWN_HEADERS[lower]
105
+ throw new TypeError(
106
+ `sendMail headers cannot set ${JSON.stringify(lower)}; ${option ? `use the ${option} option` : "Hamur writes it"}`,
107
+ )
108
+ }
109
+ if (typeof value !== "string")
110
+ throw new TypeError(`sendMail headers[${JSON.stringify(name)}] must be a string (got ${shown(value)})`)
111
+ if (CONTROL.test(value)) throw new TypeError(`sendMail headers[${JSON.stringify(name)}] holds a line break`)
112
+ checked[name] = value
113
+ }
114
+ return checked
115
+ }
116
+
117
+ function checkAttachments(value: unknown): Array<Record<string, unknown>> {
118
+ if (value === undefined) return []
119
+ if (!Array.isArray(value)) throw new TypeError(`sendMail attachments must be an array (got ${shown(value)})`)
120
+ return value.map((attachment: unknown, at) => {
121
+ const label = `sendMail attachments[${at}]`
122
+ if (!isObject(attachment)) throw new TypeError(`${label} must be an object (got ${shown(attachment)})`)
123
+ const { filename, content, contentType, cid } = attachment
124
+ if (typeof filename !== "string" || filename === "")
125
+ throw new TypeError(`${label}.filename must be a non-empty string (got ${shown(filename)})`)
126
+ if (!(typeof content === "string" || content instanceof Uint8Array || content instanceof Blob))
127
+ throw new TypeError(`${label}.content must be a Uint8Array, Blob or string`)
128
+ if (contentType !== undefined && (typeof contentType !== "string" || !isContentType(contentType)))
129
+ throw new TypeError(`${label}.contentType ${shown(contentType)} is not a content type`)
130
+ if (cid !== undefined && (typeof cid !== "string" || cid.length > MAX_PART_VALUE || !CONTENT_ID.test(cid)))
131
+ throw new TypeError(`${label}.cid ${shown(cid)} is not a content id`)
132
+ return attachment
133
+ })
134
+ }
135
+
136
+ /** The checks every message passes, before rendering and again after `mail:beforeSend`. */
137
+ function checkMessage(message: Record<string, unknown>) {
138
+ const to = addresses("to", message.to)
139
+ const cc = addresses("cc", message.cc)
140
+ const bcc = addresses("bcc", message.bcc)
141
+ if (!to.length && !cc.length && !bcc.length) throw new TypeError("sendMail needs to (got no address)")
142
+ const from = single("from", message.from)
143
+ const replyTo = single("replyTo", message.replyTo)
144
+ const { subject } = message
145
+ if (typeof subject !== "string") throw new TypeError(`sendMail subject must be a string (got ${shown(subject)})`)
146
+ if (CONTROL.test(subject)) throw new TypeError("sendMail subject holds a line break")
147
+ for (const key of ["html", "text"] as const) {
148
+ if (message[key] !== undefined && typeof message[key] !== "string")
149
+ throw new TypeError(`sendMail ${key} must be a string (got ${shown(message[key])})`)
150
+ }
151
+ const tags = message.tags ?? []
152
+ if (!Array.isArray(tags) || tags.some((tag) => typeof tag !== "string"))
153
+ throw new TypeError(`sendMail tags must be an array of strings (got ${shown(tags)})`)
154
+ return {
155
+ to,
156
+ cc,
157
+ bcc,
158
+ from,
159
+ replyTo,
160
+ subject,
161
+ headers: checkHeaders(message.headers),
162
+ attachments: checkAttachments(message.attachments),
163
+ tags: tags as string[],
164
+ }
165
+ }
166
+
167
+ async function bytesOf(content: unknown): Promise<Uint8Array> {
168
+ if (typeof content === "string") return encoder.encode(content)
169
+ if (content instanceof Blob) return new Uint8Array(await content.arrayBuffer())
170
+ return content as Uint8Array
171
+ }
172
+
173
+ function providerText(error: unknown): string {
174
+ return error instanceof Error ? error.message : String(error)
175
+ }
176
+
177
+ /** `message` with its MIME text and envelope. */
178
+ export function outgoingMail(id: string, date: Date, message: RenderedMail): OutgoingMail {
179
+ const { from, to, cc, bcc } = message
180
+ return {
181
+ id,
182
+ date,
183
+ raw: writeMime({ ...message, date, messageId: id }),
184
+ envelope: { from: from.address, to: [...new Set([...to, ...cc, ...bcc].map((address) => address.address))] },
185
+ message,
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Hands `mail` to the transport in the span `mail.send`. A rejection is safe for a span, which records the message and stack of
191
+ * what it sees thrown: it names the template and the transport, and the transport's text, which may hold an address, is its `cause`.
192
+ */
193
+ export async function transmit(deps: TransmitDeps, mail: OutgoingMail): Promise<void> {
194
+ const { template } = mail.message
195
+ await deps.span(
196
+ "mail.send",
197
+ async () => {
198
+ try {
199
+ const sender = await deps.open()
200
+ await sender.send(mail)
201
+ } catch (cause) {
202
+ throw new Error(
203
+ `Mail ${template === undefined ? "html" : JSON.stringify(template)} failed on ${deps.transport}`,
204
+ { cause },
205
+ )
206
+ }
207
+ },
208
+ {
209
+ kind: "client",
210
+ attributes: {
211
+ "mail.transport": deps.transport,
212
+ ...(template === undefined ? {} : { "mail.template": template }),
213
+ },
214
+ },
215
+ )
216
+ }
217
+
218
+ /** The failure an app sees for a rejection of `transmit`: with the transport's text. */
219
+ export function mailFailure(recorded: unknown): Error {
220
+ const { message, cause } = recorded as Error
221
+ return new Error(`${message}: ${providerText(cause)}`, { cause })
222
+ }
223
+
224
+ /** `sendMail` over a transport, the hooks and the span. */
225
+ export function createSendMail(deps: SendMailDeps) {
226
+ return async function sendMail(
227
+ message: MailMessage,
228
+ options: { queue?: boolean; delay?: number } = {},
229
+ ): Promise<MailResult> {
230
+ const queued = options.queue ?? deps.queue
231
+ if (!queued && options.delay !== undefined) throw new TypeError("sendMail delay needs queue: true")
232
+ const input: Record<string, unknown> = isObject(message) ? message : {}
233
+ const hasTemplate = input.template !== undefined
234
+ if (!hasTemplate && input.html === undefined) throw new TypeError("sendMail needs template or html (got neither)")
235
+ if (hasTemplate && input.html !== undefined) throw new TypeError("sendMail takes template or html, not both")
236
+ checkMessage(input)
237
+ if (hasTemplate && !deps.templates.includes(input.template as string))
238
+ throw new TypeError(
239
+ `No mail template ${JSON.stringify(input.template)} (templates: ${[...deps.templates].sort().join(", ")})`,
240
+ )
241
+
242
+ const event = deps.event()
243
+ const ready: MailMessage = {
244
+ ...message,
245
+ ...(hasTemplate
246
+ ? { html: await deps.render(input.template as string, isObject(input.props) ? input.props : {}, event) }
247
+ : {}),
248
+ to: addressList(message.to) as MailMessage["to"],
249
+ cc: addressList(message.cc) as MailMessage["cc"],
250
+ bcc: addressList(message.bcc) as MailMessage["bcc"],
251
+ from: message.from ?? deps.from,
252
+ ...(message.replyTo === undefined && deps.replyTo ? { replyTo: deps.replyTo } : {}),
253
+ headers: { ...message.headers },
254
+ attachments: [...(message.attachments ?? [])],
255
+ }
256
+ const hooks = deps.hooks()
257
+ await hooks?.callHook("mail:beforeSend", ready, { event })
258
+
259
+ const checked = checkMessage(ready as unknown as Record<string, unknown>)
260
+ if (typeof ready.html !== "string") throw new TypeError(`sendMail html must be a string (got ${shown(ready.html)})`)
261
+ const attachments = await Promise.all(
262
+ checked.attachments.map(async (attachment) => ({
263
+ filename: attachment.filename as string,
264
+ content: await bytesOf(attachment.content),
265
+ contentType:
266
+ (attachment.contentType as string | undefined) ||
267
+ (attachment.content instanceof Blob && isContentType(attachment.content.type)
268
+ ? attachment.content.type
269
+ : typeOfFile(attachment.filename as string)),
270
+ ...(attachment.cid === undefined ? {} : { cid: attachment.cid as string }),
271
+ })),
272
+ )
273
+ const template = hasTemplate ? (input.template as string) : undefined
274
+ const text = ready.text ?? (htmlToText(ready.html) || undefined)
275
+ const mail: RenderedMail = {
276
+ from: checked.from ?? deps.from,
277
+ to: checked.to,
278
+ cc: checked.cc,
279
+ bcc: checked.bcc,
280
+ ...(checked.replyTo ? { replyTo: checked.replyTo } : {}),
281
+ subject: checked.subject,
282
+ ...(template === undefined ? {} : { template }),
283
+ html: ready.html,
284
+ ...(text === undefined ? {} : { text }),
285
+ attachments,
286
+ headers: checked.headers,
287
+ tags: checked.tags,
288
+ }
289
+ const id = `${deps.id ?? crypto.randomUUID()}@${deps.host(event)}`
290
+ const outgoing = outgoingMail(id, new Date(), mail)
291
+ if (queued) {
292
+ await deps.enqueue(outgoing, options.delay)
293
+ return { id, queued: true }
294
+ }
295
+
296
+ try {
297
+ await transmit(deps, outgoing)
298
+ } catch (recorded) {
299
+ const failure = mailFailure(recorded)
300
+ await hooks?.callHook("mail:error", failure, ready)
301
+ throw failure
302
+ }
303
+ const result: MailResult = { id, queued: false }
304
+ await hooks?.callHook("mail:sent", result, ready)
305
+ deps.sent?.({ label: template ?? "html", to: mail.to, event })
306
+ return result
307
+ }
308
+ }
@@ -0,0 +1,13 @@
1
+ import { defineTask } from "hamur/server"
2
+ import { sendQueued, unpackMail, type QueuedMail } from "./queue.ts"
3
+ import { transmitDeps } from "./runtime.ts"
4
+
5
+ /** Sends a message that `sendMail` queued. */
6
+ export default defineTask({
7
+ description: "Send a message that sendMail queued",
8
+ async run(payload: QueuedMail, ctx): Promise<void> {
9
+ if (typeof payload?.message?.html !== "string")
10
+ throw new TypeError("mail:send takes a message that sendMail queued")
11
+ await sendQueued(transmitDeps, unpackMail(payload), ctx.log)
12
+ },
13
+ })