@hamur/mail 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +36 -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
package/src/html.ts ADDED
@@ -0,0 +1,274 @@
1
+ interface HtmlAttribute {
2
+ name: string
3
+ /** From the space before the name to the end of the value. */
4
+ start: number
5
+ end: number
6
+ valueStart: number
7
+ valueEnd: number
8
+ }
9
+
10
+ interface HtmlToken {
11
+ kind: "text" | "open" | "close" | "comment"
12
+ /** The tag's name, lower-cased. */
13
+ name: string
14
+ start: number
15
+ end: number
16
+ attributes: HtmlAttribute[]
17
+ }
18
+
19
+ const TAG_NAME = /<(\/?)([a-z][^\s/>]*)/iy
20
+ const TAG_END = /[\s/]*>/y
21
+ const ATTRIBUTE = /[\s/]*([^\s/>][^\s/>=]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>][^\s>]*)))?/y
22
+ /** The elements whose content is text up to their own end tag. */
23
+ const RAW_TEXT = new Set(["script", "style", "textarea", "title"])
24
+
25
+ /** The tags, comments and text of `html` in order, by position; a tag that never ends drops the rest, as in a browser. */
26
+ function* htmlTokens(html: string): Generator<HtmlToken> {
27
+ const token = (kind: HtmlToken["kind"], start: number, end: number, name = ""): HtmlToken => ({
28
+ kind,
29
+ name,
30
+ start,
31
+ end,
32
+ attributes: [],
33
+ })
34
+ let text = 0
35
+ let at = 0
36
+ while ((at = html.indexOf("<", at)) !== -1) {
37
+ let found: HtmlToken
38
+ TAG_NAME.lastIndex = at
39
+ const tag = TAG_NAME.exec(html)
40
+ if (tag) {
41
+ found = token(tag[1] ? "close" : "open", at, TAG_NAME.lastIndex, tag[2]!.toLowerCase())
42
+ for (;;) {
43
+ TAG_END.lastIndex = found.end
44
+ if (TAG_END.test(html)) {
45
+ found.end = TAG_END.lastIndex
46
+ break
47
+ }
48
+ ATTRIBUTE.lastIndex = found.end
49
+ const match = ATTRIBUTE.exec(html)
50
+ if (!match) {
51
+ if (at > text) yield token("text", text, at)
52
+ return
53
+ }
54
+ const value = match[2] ?? match[3] ?? match[4] ?? ""
55
+ const end = ATTRIBUTE.lastIndex
56
+ const valueEnd = match[2] === undefined && match[3] === undefined ? end : end - 1
57
+ found.attributes.push({
58
+ name: match[1]!.toLowerCase(),
59
+ start: found.end,
60
+ end,
61
+ valueStart: valueEnd - value.length,
62
+ valueEnd,
63
+ })
64
+ found.end = end
65
+ }
66
+ } else if (/[!?/]/.test(html[at + 1] ?? "")) {
67
+ const comment = html.startsWith("<!--", at)
68
+ const close = comment ? html.indexOf("-->", at + 2) : html.indexOf(">", at)
69
+ found = token("comment", at, close === -1 ? html.length : close + (comment ? 3 : 1))
70
+ } else {
71
+ at++
72
+ continue
73
+ }
74
+ if (at > text) yield token("text", text, at)
75
+ yield found
76
+ text = at = found.end
77
+ if (found.kind === "open" && RAW_TEXT.has(found.name)) {
78
+ const end = new RegExp(`</${found.name}(?=[\\s/>])`, "gi")
79
+ end.lastIndex = at
80
+ at = end.exec(html)?.index ?? html.length
81
+ }
82
+ }
83
+ if (html.length > text) yield token("text", text, html.length)
84
+ }
85
+
86
+ /** What the libraries' server renders write for the client alone. */
87
+ const HYDRATION = new Set(["_hk", "data-hk", "jsaction", "ng-server-context", "ng-version", "ngh"])
88
+ /** Outlook's conditional comments, the one kind a mail client reads. */
89
+ const CONDITIONAL = /^<!--(?:\[if\s|<!\[endif\])/i
90
+ const PRELOAD = /^(?:module)?preload$/i
91
+
92
+ export interface MailSite {
93
+ /** `site.url`. */
94
+ origin: string
95
+ /** `app.baseURL`. */
96
+ baseURL: string
97
+ }
98
+
99
+ /** An app path as an absolute URL, below `app.baseURL` whether or not it was written with it. */
100
+ function absoluteUrl(value: string, { origin, baseURL }: MailSite): string {
101
+ const path = value.trim()
102
+ if (!/^\/(?!\/)/.test(path)) return value
103
+ const base = baseURL.replace(/\/+$/, "")
104
+ const below = path === base || ["/", "?", "#"].some((next) => path.startsWith(base + next))
105
+ return `${origin}${below ? "" : base}${path}`
106
+ }
107
+
108
+ /** What a mail keeps of a server render: no script, hydration marker or preload, and app paths in `href` and `src` made absolute. */
109
+ export function mailHtml(html: string, site: MailSite): string {
110
+ let out = ""
111
+ let inScript = false
112
+ for (const token of htmlTokens(html)) {
113
+ if (inScript || token.name === "script") {
114
+ inScript = token.name === "script" ? token.kind === "open" : true
115
+ continue
116
+ }
117
+ const source = html.slice(token.start, token.end)
118
+ if (token.kind === "comment" && source.startsWith("<!--") && !CONDITIONAL.test(source)) continue
119
+ if (token.kind !== "open") {
120
+ out += source
121
+ continue
122
+ }
123
+ const valueOf = (attribute: HtmlAttribute) => html.slice(attribute.valueStart, attribute.valueEnd)
124
+ if (token.name === "link" && token.attributes.some((item) => item.name === "rel" && PRELOAD.test(valueOf(item))))
125
+ continue
126
+ let at = token.start
127
+ for (const attribute of token.attributes) {
128
+ if (HYDRATION.has(attribute.name)) {
129
+ out += html.slice(at, attribute.start)
130
+ at = attribute.end
131
+ } else if (attribute.name === "href" || attribute.name === "src") {
132
+ out += html.slice(at, attribute.valueStart) + absoluteUrl(valueOf(attribute), site)
133
+ at = attribute.valueEnd
134
+ }
135
+ }
136
+ out += html.slice(at, token.end)
137
+ }
138
+ return out
139
+ }
140
+
141
+ const LATIN_1 =
142
+ "nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr deg plusmn sup2 sup3 acute micro para middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml Yacute THORN szlig agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml eth ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute thorn yuml"
143
+ const ENTITIES = new Map<string, string>([
144
+ ...LATIN_1.split(" ").map((name, at): [string, string] => [name, String.fromCharCode(160 + at)]),
145
+ ["amp", "&"],
146
+ ["lt", "<"],
147
+ ["gt", ">"],
148
+ ["quot", '"'],
149
+ ["apos", "'"],
150
+ ["hellip", "…"],
151
+ ["mdash", "—"],
152
+ ["ndash", "–"],
153
+ ["lsquo", "‘"],
154
+ ["rsquo", "’"],
155
+ ["sbquo", "‚"],
156
+ ["ldquo", "“"],
157
+ ["rdquo", "”"],
158
+ ["bdquo", "„"],
159
+ ["lsaquo", "‹"],
160
+ ["rsaquo", "›"],
161
+ ["bull", "•"],
162
+ ["euro", "€"],
163
+ ["trade", "™"],
164
+ ["larr", "←"],
165
+ ["uarr", "↑"],
166
+ ["rarr", "→"],
167
+ ["darr", "↓"],
168
+ ["ensp", " "],
169
+ ["emsp", " "],
170
+ ["thinsp", " "],
171
+ ["zwnj", "‌"],
172
+ ["zwj", "‍"],
173
+ ])
174
+ const ENTITY = /&(?:#x([\da-f]+)|#(\d+)|([a-z][a-z\d]*));/gi
175
+
176
+ function decode(text: string): string {
177
+ return text.replace(ENTITY, (whole, hex?: string, decimal?: string, name?: string) => {
178
+ if (name) return ENTITIES.get(name) ?? whole
179
+ const code = Number.parseInt((hex ?? decimal)!, hex ? 16 : 10)
180
+ return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : "�"
181
+ })
182
+ }
183
+
184
+ const BLOCKS = new Set(
185
+ "address article aside blockquote body center dd details div dl dt fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hr html li main nav ol p pre section summary table tbody tfoot thead tr ul".split(
186
+ " ",
187
+ ),
188
+ )
189
+ const DROPPED = new Set(["head", "script", "style"])
190
+
191
+ type LineEnd = "line" | "bullet" | "space" | "word"
192
+
193
+ /** The text part of a mail that sets no `text`. */
194
+ export function htmlToText(html: string): string {
195
+ let out = ""
196
+ /** What the text so far ends with. */
197
+ let last: LineEnd = "line"
198
+ let dropped: string | undefined
199
+ let link: { href: string | undefined; out: string; last: LineEnd } | undefined
200
+
201
+ const write = (source: string) => {
202
+ let text = source.replace(/[ \t\r\n\f]+/g, " ")
203
+ if (last !== "word" && text.startsWith(" ")) text = text.slice(1)
204
+ if (text === "") return
205
+ out += decode(text)
206
+ last = text.endsWith(" ") ? "space" : "word"
207
+ }
208
+ const endLine = () => {
209
+ if (last === "line") return
210
+ out += "\n"
211
+ last = "line"
212
+ }
213
+ const closeLink = () => {
214
+ if (!link) return
215
+ const { href, ...before } = link
216
+ const inner = out
217
+ const text = inner.trim()
218
+ link = undefined
219
+ out = before.out
220
+ if (text === "") {
221
+ last = before.last
222
+ if (href) {
223
+ out += href
224
+ last = "word"
225
+ }
226
+ return
227
+ }
228
+ out += inner.trimEnd() + (!href || href === text ? "" : ` (${href})`)
229
+ const ended = last
230
+ last = "word"
231
+ if (ended === "line") endLine()
232
+ else if (ended === "space") write(" ")
233
+ }
234
+
235
+ for (const token of htmlTokens(html)) {
236
+ const { kind, name } = token
237
+ if (dropped) {
238
+ if (name === dropped ? kind === "close" : dropped === "head" && name === "body") dropped = undefined
239
+ continue
240
+ }
241
+ const attribute = (wanted: string) => {
242
+ const found = token.attributes.find((item) => item.name === wanted)
243
+ return found && html.slice(found.valueStart, found.valueEnd)
244
+ }
245
+ if (kind === "text") write(html.slice(token.start, token.end))
246
+ else if (kind === "open" && DROPPED.has(name)) dropped = name
247
+ else if (name === "a") {
248
+ closeLink()
249
+ if (kind === "open") {
250
+ const href = attribute("href")
251
+ link = { href: href === undefined ? undefined : decode(href.trim()), out, last }
252
+ out = ""
253
+ }
254
+ } else if (kind === "open" && name === "img") write(attribute("alt") ?? "")
255
+ else if (kind === "open" && name === "br") {
256
+ out += "\n"
257
+ last = "line"
258
+ } else if (kind === "close" && (name === "td" || name === "th")) write(" ")
259
+ else if (BLOCKS.has(name) && !(kind === "open" && last === "bullet")) {
260
+ endLine()
261
+ if (kind === "open" && name === "li") {
262
+ out += "- "
263
+ last = "bullet"
264
+ }
265
+ }
266
+ }
267
+ closeLink()
268
+ return out
269
+ .split("\n")
270
+ .map((line) => line.trimEnd())
271
+ .join("\n")
272
+ .replace(/\n{3,}/g, "\n\n")
273
+ .trim()
274
+ }
package/src/index.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { HamurEvent } from "hamur/server"
2
+ import type { MailConfig, MailMessage, MailResult } from "./types.ts"
3
+
4
+ export { default } from "./module.ts"
5
+ export type { MailAddress, MailConfig, MailMessage, MailResult } from "./types.ts"
6
+
7
+ /** Filled in by typegen from `app/mail/`: each template's name and its props. */
8
+ export interface MailTemplates {}
9
+
10
+ declare module "hamur" {
11
+ interface HamurModuleOptions {
12
+ mail?: MailConfig
13
+ }
14
+ }
15
+
16
+ declare module "hamur/server" {
17
+ interface ServerHooks {
18
+ /** Before the MIME message is written, with the rendered message; a hook may change it (headers, `bcc`), and the checks run again. */
19
+ "mail:beforeSend": (message: MailMessage, ctx: { event?: HamurEvent }) => void | Promise<void>
20
+ /** After the transport took the message. */
21
+ "mail:sent": (result: MailResult, message: MailMessage) => void | Promise<void>
22
+ /** The transport failed; `error` is what `sendMail` rejects with. To report it, not to send again: a queue may do so too. */
23
+ "mail:error": (error: Error, message: MailMessage) => void | Promise<void>
24
+ }
25
+ }
package/src/mime.ts ADDED
@@ -0,0 +1,220 @@
1
+ import { isAscii, quotedName } from "./address.ts"
2
+ import type { ParsedAddress } from "./types.ts"
3
+
4
+ const CRLF = "\r\n"
5
+ const FOLD_AT = 78
6
+ const LINE_LIMIT = 998
7
+ /** Each encoded word stays within 75 characters: `=?UTF-8?B?` and `?=` around 60 base64 characters, 45 bytes. */
8
+ const WORD_BYTES = 45
9
+ const ATTR_CHAR = /[A-Za-z0-9!#$&+\-.^_`|~]/
10
+ const encoder = new TextEncoder()
11
+
12
+ export interface MimeAttachment {
13
+ filename: string
14
+ content: Uint8Array
15
+ contentType: string
16
+ cid?: string
17
+ }
18
+
19
+ export interface MimeInput {
20
+ from: ParsedAddress
21
+ to: ParsedAddress[]
22
+ cc?: ParsedAddress[]
23
+ replyTo?: ParsedAddress
24
+ subject: string
25
+ date: Date
26
+ /** Without `<>`. */
27
+ messageId: string
28
+ html?: string
29
+ text?: string
30
+ attachments?: MimeAttachment[]
31
+ /** Headers of the app, checked by `sendMail`. */
32
+ headers?: Record<string, string>
33
+ }
34
+
35
+ interface Part {
36
+ headers: string[]
37
+ body: string
38
+ }
39
+
40
+ function binary(bytes: Uint8Array): string {
41
+ let out = ""
42
+ for (let at = 0; at < bytes.length; at += 0x8000) out += String.fromCharCode(...bytes.subarray(at, at + 0x8000))
43
+ return out
44
+ }
45
+
46
+ /** Base64 in lines of 76 characters. */
47
+ export function base64Lines(bytes: Uint8Array): string {
48
+ const text = btoa(binary(bytes))
49
+ const lines: string[] = []
50
+ for (let at = 0; at < text.length; at += 76) lines.push(text.slice(at, at + 76))
51
+ return lines.join(CRLF)
52
+ }
53
+
54
+ const hex = (byte: number): string => `=${byte.toString(16).toUpperCase().padStart(2, "0")}`
55
+
56
+ /** RFC 2045 §6.7: UTF-8 quoted-printable, CRLF hard breaks, soft breaks keeping each line within 76 characters. */
57
+ export function quotedPrintable(text: string): string {
58
+ const out: string[] = []
59
+ for (const line of text.replace(/\r\n?/g, "\n").split("\n")) {
60
+ const bytes = encoder.encode(line)
61
+ const pieces: string[] = []
62
+ bytes.forEach((byte, at) => {
63
+ const last = at === bytes.length - 1
64
+ if ((byte === 0x20 || byte === 0x09) && !last) pieces.push(String.fromCharCode(byte))
65
+ else if (byte >= 33 && byte <= 126 && byte !== 61) pieces.push(String.fromCharCode(byte))
66
+ else pieces.push(hex(byte))
67
+ })
68
+ let current = ""
69
+ pieces.forEach((piece, at) => {
70
+ const fitsLast = at === pieces.length - 1 && current.length + piece.length <= 76
71
+ if (current.length + piece.length > 75 && !fitsLast) {
72
+ out.push(`${current}=`)
73
+ current = ""
74
+ }
75
+ current += piece
76
+ })
77
+ out.push(current)
78
+ }
79
+ return out.join(CRLF)
80
+ }
81
+
82
+ /** RFC 2047 `B` encoded words of at most 45 bytes each, never splitting a character. */
83
+ export function encodedWords(text: string): string[] {
84
+ const words: string[] = []
85
+ let chunk: number[] = []
86
+ for (const char of text) {
87
+ const bytes = encoder.encode(char)
88
+ if (chunk.length + bytes.length > WORD_BYTES) {
89
+ words.push(`=?UTF-8?B?${btoa(String.fromCharCode(...chunk))}?=`)
90
+ chunk = []
91
+ }
92
+ chunk.push(...bytes)
93
+ }
94
+ if (chunk.length || !words.length) words.push(`=?UTF-8?B?${btoa(String.fromCharCode(...chunk))}?=`)
95
+ return words
96
+ }
97
+
98
+ /** `Name: tokens`, folded before a token where the line would pass 78 characters. */
99
+ function header(name: string, tokens: string[]): string {
100
+ let out = `${name}:`
101
+ let line = out.length
102
+ tokens.forEach((token, at) => {
103
+ if (at > 0 && token !== "" && line + 1 + token.length > FOLD_AT) {
104
+ out += `${CRLF} ${token}`
105
+ line = 1 + token.length
106
+ return
107
+ }
108
+ out += ` ${token}`
109
+ line += 1 + token.length
110
+ })
111
+ return out
112
+ }
113
+
114
+ const fits = (text: string): boolean => text.split(CRLF).every((line) => encoder.encode(line).length <= LINE_LIMIT)
115
+
116
+ /** Unstructured header text: its words as they are, or encoded words when it is not ASCII or a line would pass 998 octets. */
117
+ function textHeader(name: string, value: string): string {
118
+ if (isAscii(value)) {
119
+ const plain = header(name, value.split(" "))
120
+ if (fits(plain)) return plain
121
+ }
122
+ return header(name, encodedWords(value))
123
+ }
124
+
125
+ function nameTokens(name: string): string[] {
126
+ const quoted = quotedName(name)
127
+ if (isAscii(name) && quoted.length <= LINE_LIMIT - 400) return [quoted]
128
+ return encodedWords(name)
129
+ }
130
+
131
+ function addressTokens(addresses: ParsedAddress[]): string[] {
132
+ return addresses.flatMap((address, at) => {
133
+ const comma = at < addresses.length - 1 ? "," : ""
134
+ return address.name ? [...nameTokens(address.name), `<${address.address}>${comma}`] : [`${address.address}${comma}`]
135
+ })
136
+ }
137
+
138
+ /** RFC 5322 §3.3: `Thu, 03 Dec 2026 10:00:00 +0000`. */
139
+ export function mailDate(date: Date): string {
140
+ return date.toUTCString().replace(/GMT$/, "+0000")
141
+ }
142
+
143
+ function boundary(): string {
144
+ const bytes = crypto.getRandomValues(new Uint8Array(12))
145
+ return `=_hamur_${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`
146
+ }
147
+
148
+ function textPart(subtype: "plain" | "html", body: string): Part {
149
+ return {
150
+ headers: [`Content-Type: text/${subtype}; charset=utf-8`, "Content-Transfer-Encoding: quoted-printable"],
151
+ body: quotedPrintable(body),
152
+ }
153
+ }
154
+
155
+ /** RFC 2231 `filename*` with continuations of at most 60 characters, never splitting a `%XX`. */
156
+ function filenameParams(filename: string): string[] {
157
+ let encoded = "UTF-8''"
158
+ for (const byte of encoder.encode(filename)) {
159
+ const char = String.fromCharCode(byte)
160
+ encoded += byte < 0x80 && ATTR_CHAR.test(char) ? char : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`
161
+ }
162
+ if (encoded.length <= 60) return [`filename*=${encoded}`]
163
+ const chunks: string[] = []
164
+ let at = 0
165
+ while (at < encoded.length) {
166
+ let end = Math.min(at + 60, encoded.length)
167
+ const percent = encoded.lastIndexOf("%", end - 1)
168
+ if (percent >= at && percent > end - 3 && end < encoded.length) end = percent
169
+ chunks.push(encoded.slice(at, end))
170
+ at = end
171
+ }
172
+ return chunks.map((chunk, index) => `filename*${index}*=${chunk}`)
173
+ }
174
+
175
+ function attachmentPart(attachment: MimeAttachment): Part {
176
+ const disposition = attachment.cid === undefined ? "attachment" : "inline"
177
+ const params = filenameParams(attachment.filename)
178
+ const headers = [
179
+ `Content-Type: ${attachment.contentType}`,
180
+ "Content-Transfer-Encoding: base64",
181
+ `Content-Disposition: ${disposition};${params.map((param) => `${CRLF} ${param}`).join(";")}`,
182
+ ]
183
+ if (attachment.cid !== undefined) headers.push(`Content-ID: <${attachment.cid}>`)
184
+ return { headers, body: base64Lines(attachment.content) }
185
+ }
186
+
187
+ function multipart(subtype: "alternative" | "related" | "mixed", parts: Part[]): Part {
188
+ const mark = boundary()
189
+ const body = parts
190
+ .map((part) => `--${mark}${CRLF}${part.headers.join(CRLF)}${CRLF}${CRLF}${part.body}${CRLF}`)
191
+ .join("")
192
+ return { headers: [`Content-Type: multipart/${subtype};${CRLF} boundary="${mark}"`], body: `${body}--${mark}--` }
193
+ }
194
+
195
+ /** `multipart/alternative` of the text and the HTML, inside `multipart/related` for `cid` attachments, inside `multipart/mixed` for the others. */
196
+ export function writeMime(input: MimeInput): string {
197
+ const bodies: Part[] = []
198
+ if (input.text !== undefined) bodies.push(textPart("plain", input.text))
199
+ if (input.html !== undefined) bodies.push(textPart("html", input.html))
200
+ let root: Part = bodies.length === 1 ? bodies[0]! : multipart("alternative", bodies)
201
+ const attachments = input.attachments ?? []
202
+ const inline = attachments.filter((attachment) => attachment.cid !== undefined)
203
+ const attached = attachments.filter((attachment) => attachment.cid === undefined)
204
+ if (inline.length) root = multipart("related", [root, ...inline.map(attachmentPart)])
205
+ if (attached.length) root = multipart("mixed", [root, ...attached.map(attachmentPart)])
206
+
207
+ const lines = [header("From", addressTokens([input.from]))]
208
+ if (input.replyTo) lines.push(header("Reply-To", addressTokens([input.replyTo])))
209
+ if (input.to.length) lines.push(header("To", addressTokens(input.to)))
210
+ if (input.cc?.length) lines.push(header("Cc", addressTokens(input.cc)))
211
+ lines.push(
212
+ textHeader("Subject", input.subject),
213
+ `Date: ${mailDate(input.date)}`,
214
+ `Message-ID: <${input.messageId}>`,
215
+ "MIME-Version: 1.0",
216
+ )
217
+ for (const [name, value] of Object.entries(input.headers ?? {})) lines.push(textHeader(name, value))
218
+ lines.push(...root.headers)
219
+ return `${lines.join(CRLF)}${CRLF}${CRLF}${root.body}${CRLF}`
220
+ }
package/src/module.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { defineModule } from "hamur/kit"
2
+ import { setupMail } from "./build/setup.ts"
3
+ import { resolveOptions } from "./options.ts"
4
+ import type { MailConfig } from "./types.ts"
5
+
6
+ export default defineModule<MailConfig>({
7
+ meta: { name: "mail", configKey: "mail" },
8
+ setup(input, hamur) {
9
+ setupMail(resolveOptions(input), hamur)
10
+ },
11
+ })
package/src/options.ts ADDED
@@ -0,0 +1,157 @@
1
+ import { DiagnosticError, isEnvRef } from "hamur/kit"
2
+ import { asciiDomain, parseAddress } from "./address.ts"
3
+ import type { MailDkim, MailTransport, ParsedAddress } from "./types.ts"
4
+
5
+ export const TRANSPORTS = ["smtp", "resend", "postmark", "sendgrid", "mailgun", "ses", "cloudflare", "outbox"] as const
6
+
7
+ const KEYS = ["from", "replyTo", "transport", "queue", "dkim"]
8
+ const DKIM_KEYS = ["domain", "selector", "privateKey"]
9
+ /** RFC 6376 §3.1: one label of a selector. */
10
+ const SELECTOR_LABEL = /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/
11
+ const TRANSPORT_KEYS: Record<MailTransport["type"], string[]> = {
12
+ smtp: ["host", "port", "secure", "user", "password"],
13
+ resend: ["apiKey"],
14
+ postmark: ["serverToken", "messageStream"],
15
+ sendgrid: ["apiKey"],
16
+ mailgun: ["apiKey", "domain", "region"],
17
+ ses: ["region", "accessKeyId", "secretAccessKey"],
18
+ cloudflare: ["binding"],
19
+ outbox: ["dir"],
20
+ }
21
+ const SECRETS = ["password", "apiKey", "serverToken", "accessKeyId", "secretAccessKey"]
22
+ const REQUIRED: Partial<Record<MailTransport["type"], string[]>> = {
23
+ resend: ["apiKey"],
24
+ postmark: ["serverToken"],
25
+ sendgrid: ["apiKey"],
26
+ mailgun: ["apiKey", "domain"],
27
+ ses: ["region", "accessKeyId", "secretAccessKey"],
28
+ cloudflare: ["binding"],
29
+ }
30
+ const BINDING = /^[A-Za-z_][A-Za-z0-9_]*$/
31
+ const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"])
32
+
33
+ export interface ResolvedMailOptions {
34
+ from: ParsedAddress
35
+ replyTo?: ParsedAddress
36
+ /** The configured transport; undefined leaves it to `hamur dev` and tests. */
37
+ transport?: MailTransport
38
+ queue: boolean
39
+ dkim?: MailDkim
40
+ }
41
+
42
+ function fail(message: string): never {
43
+ throw new DiagnosticError("HAMUR_E6701", message)
44
+ }
45
+
46
+ function shown(value: unknown): string {
47
+ if (Array.isArray(value)) return "an array"
48
+ if (typeof value === "function") return "a function"
49
+ if (value === undefined) return "undefined"
50
+ return JSON.stringify(value)
51
+ }
52
+
53
+ const isObject = (value: unknown): value is Record<string, unknown> =>
54
+ typeof value === "object" && value !== null && !Array.isArray(value)
55
+
56
+ function address(key: string, value: unknown): ParsedAddress {
57
+ const parsed = parseAddress(value)
58
+ if (!parsed) fail(`mail.${key} must be an address such as "Acme <hello@acme.dev>" (got ${shown(value)})`)
59
+ return parsed
60
+ }
61
+
62
+ function resolveTransport(input: unknown): MailTransport {
63
+ if (!isObject(input)) fail(`mail.transport must be an object (got ${shown(input)})`)
64
+ const type = input.type
65
+ if (typeof type !== "string" || !(TRANSPORTS as readonly string[]).includes(type))
66
+ fail(
67
+ `mail.transport.type must be "smtp", "resend", "postmark", "sendgrid", "mailgun", "ses", "cloudflare" or "outbox" (got ${shown(type)})`,
68
+ )
69
+ const keys = TRANSPORT_KEYS[type as MailTransport["type"]]
70
+ for (const key of Object.keys(input)) {
71
+ if (key !== "type" && !keys.includes(key))
72
+ fail(`mail.transport has no ${JSON.stringify(key)} on the "${type}" transport (it takes: ${keys.join(", ")})`)
73
+ }
74
+ for (const key of SECRETS) {
75
+ if (input[key] !== undefined && !isEnvRef(input[key]))
76
+ fail(`mail.transport.${key} must be env("NAME"); a secret in the config file ends up in the repository`)
77
+ }
78
+ for (const key of REQUIRED[type as MailTransport["type"]] ?? []) {
79
+ if (input[key] === undefined) fail(`mail.transport.${key} is required on the "${type}" transport`)
80
+ }
81
+ const text = (key: string) => {
82
+ const value = input[key]
83
+ if (value !== undefined && (typeof value !== "string" || value === ""))
84
+ fail(`mail.transport.${key} must be a non-empty string (got ${shown(value)})`)
85
+ }
86
+ if (type === "smtp") {
87
+ const { host, port, secure, user } = input
88
+ if (typeof host !== "string" || host === "" || /[\s/]/.test(host))
89
+ fail(`mail.transport.host must be a host name (got ${shown(host)})`)
90
+ if (port !== undefined && (!Number.isInteger(port) || (port as number) < 1 || (port as number) > 65535))
91
+ fail(`mail.transport.port must be an integer from 1 to 65535 (got ${shown(port)})`)
92
+ if (secure !== undefined && secure !== "tls" && secure !== "starttls" && secure !== false)
93
+ fail(`mail.transport.secure must be "tls", "starttls" or false (got ${shown(secure)})`)
94
+ if (secure === false && !LOCAL_HOSTS.has(host.toLowerCase()))
95
+ fail(`mail.transport.secure false is allowed for localhost only (got ${shown(host)})`)
96
+ if (user !== undefined && !isEnvRef(user) && (typeof user !== "string" || user === ""))
97
+ fail(`mail.transport.user must be a string or env("NAME") (got ${shown(user)})`)
98
+ for (const [key, other] of [
99
+ ["password", "user"],
100
+ ["user", "password"],
101
+ ] as const) {
102
+ if (input[key] === undefined && input[other] !== undefined)
103
+ fail(`mail.transport.${key} is required with mail.transport.${other}`)
104
+ }
105
+ }
106
+ if (type === "postmark") text("messageStream")
107
+ if (type === "mailgun") {
108
+ text("domain")
109
+ if (input.region !== undefined && input.region !== "us" && input.region !== "eu")
110
+ fail(`mail.transport.region must be "us" or "eu" (got ${shown(input.region)})`)
111
+ }
112
+ if (type === "ses") {
113
+ text("region")
114
+ if (!/^[a-z0-9-]+$/.test(input.region as string))
115
+ fail(`mail.transport.region must be an AWS region such as "eu-west-1" (got ${shown(input.region)})`)
116
+ }
117
+ if (type === "cloudflare" && (typeof input.binding !== "string" || !BINDING.test(input.binding)))
118
+ fail(`mail.transport.binding must be a binding name (got ${shown(input.binding)})`)
119
+ if (type === "outbox") text("dir")
120
+ return { ...input } as MailTransport
121
+ }
122
+
123
+ /** No value is repeated in an error: a key pasted into the config would be in it. */
124
+ function resolveDkim(input: unknown): MailDkim {
125
+ if (!isObject(input)) fail("mail.dkim must be an object with domain, selector and privateKey")
126
+ for (const key of Object.keys(input)) {
127
+ if (!DKIM_KEYS.includes(key)) fail(`mail.dkim has no ${JSON.stringify(key)} (it takes: ${DKIM_KEYS.join(", ")})`)
128
+ }
129
+ for (const key of DKIM_KEYS) {
130
+ if (input[key] === undefined) fail(`mail.dkim.${key} is required`)
131
+ }
132
+ const { domain, selector, privateKey } = input
133
+ if (!isEnvRef(privateKey))
134
+ fail('mail.dkim.privateKey must be env("NAME"); a secret in the config file ends up in the repository')
135
+ const host = typeof domain === "string" ? asciiDomain(domain) : undefined
136
+ if (host === undefined) fail('mail.dkim.domain must be a domain such as "acme.dev"')
137
+ if (typeof selector !== "string" || !selector.split(".").every((label) => SELECTOR_LABEL.test(label)))
138
+ fail('mail.dkim.selector must be a DNS name such as "mail"')
139
+ return { domain: host, selector, privateKey }
140
+ }
141
+
142
+ /** The checked options, or the load error of the first value that is wrong. */
143
+ export function resolveOptions(input: unknown = {}): ResolvedMailOptions {
144
+ if (!isObject(input)) fail(`mail must be an object (got ${shown(input)})`)
145
+ for (const key of Object.keys(input)) {
146
+ if (!KEYS.includes(key)) fail(`mail has no ${JSON.stringify(key)} (it takes: ${KEYS.join(", ")})`)
147
+ }
148
+ const resolved: ResolvedMailOptions = { from: address("from", input.from), queue: false }
149
+ if (input.replyTo !== undefined) resolved.replyTo = address("replyTo", input.replyTo)
150
+ if (input.transport !== undefined) resolved.transport = resolveTransport(input.transport)
151
+ if (input.queue !== undefined) {
152
+ if (typeof input.queue !== "boolean") fail(`mail.queue must be a boolean (got ${shown(input.queue)})`)
153
+ resolved.queue = input.queue
154
+ }
155
+ if (input.dkim !== undefined) resolved.dkim = resolveDkim(input.dkim)
156
+ return resolved
157
+ }