@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.
- package/LICENSE +22 -0
- package/README.md +14 -2
- package/dist/src/devtools.js +268 -0
- package/dist/src/index.js +573 -0
- package/dist/src/server/index.js +916 -0
- package/dist/src/test.js +39 -0
- package/dist/types/src/address.d.ts +14 -0
- package/dist/types/src/build/devtools.d.ts +20 -0
- package/dist/types/src/build/outbox.d.ts +35 -0
- package/dist/types/src/build/setup.d.ts +22 -0
- package/dist/types/src/build/templates.d.ts +12 -0
- package/dist/types/src/devtools-model.d.ts +12 -0
- package/dist/types/src/devtools.d.ts +2 -0
- package/dist/types/src/html.d.ts +10 -0
- package/dist/types/src/index.d.ts +24 -0
- package/dist/types/src/mime.d.ts +32 -0
- package/dist/types/src/module.d.ts +3 -0
- package/dist/types/src/options.d.ts +12 -0
- package/dist/types/src/server/deliver.d.ts +15 -0
- package/dist/types/src/server/devtools-routes.d.ts +1 -0
- package/dist/types/src/server/door-dev.d.ts +3 -0
- package/dist/types/src/server/door.d.ts +2 -0
- package/dist/types/src/server/hooks.d.ts +5 -0
- package/dist/types/src/server/index.d.ts +6 -0
- package/dist/types/src/server/message.d.ts +3 -0
- package/dist/types/src/server/plugin.d.ts +1 -0
- package/dist/types/src/server/preview.d.ts +8 -0
- package/dist/types/src/server/queue.d.ts +19 -0
- package/dist/types/src/server/runtime.d.ts +5 -0
- package/dist/types/src/server/send.d.ts +54 -0
- package/dist/types/src/server/task.d.ts +4 -0
- package/dist/types/src/server/template.d.ts +8 -0
- package/dist/types/src/smtp/client.d.ts +28 -0
- package/dist/types/src/smtp/dkim.d.ts +8 -0
- package/dist/types/src/smtp/sockets.d.ts +42 -0
- package/dist/types/src/test.d.ts +27 -0
- package/dist/types/src/transport.d.ts +28 -0
- package/dist/types/src/transports/cloudflare.d.ts +17 -0
- package/dist/types/src/transports/http.d.ts +26 -0
- package/dist/types/src/transports/mailgun.d.ts +9 -0
- package/dist/types/src/transports/outbox.d.ts +9 -0
- package/dist/types/src/transports/postmark.d.ts +8 -0
- package/dist/types/src/transports/resend.d.ts +7 -0
- package/dist/types/src/transports/sendgrid.d.ts +7 -0
- package/dist/types/src/transports/ses.d.ts +9 -0
- package/dist/types/src/transports/smtp.d.ts +3 -0
- package/dist/types/src/types.d.ts +124 -0
- package/package.json +48 -4
- package/src/address.ts +86 -0
- package/src/build/devtools.ts +81 -0
- package/src/build/outbox.ts +69 -0
- package/src/build/setup.ts +226 -0
- package/src/build/templates.ts +113 -0
- package/src/devtools-model.ts +24 -0
- package/src/devtools.ts +351 -0
- package/src/env.d.ts +36 -0
- package/src/html.ts +274 -0
- package/src/index.ts +25 -0
- package/src/mime.ts +220 -0
- package/src/module.ts +11 -0
- package/src/options.ts +157 -0
- package/src/server/deliver.ts +54 -0
- package/src/server/devtools-routes.ts +32 -0
- package/src/server/door-dev.ts +6 -0
- package/src/server/door.ts +4 -0
- package/src/server/hooks.ts +13 -0
- package/src/server/index.ts +28 -0
- package/src/server/message.ts +36 -0
- package/src/server/plugin.ts +4 -0
- package/src/server/preview.ts +41 -0
- package/src/server/queue.ts +58 -0
- package/src/server/runtime.ts +45 -0
- package/src/server/send.ts +308 -0
- package/src/server/task.ts +13 -0
- package/src/server/template.ts +37 -0
- package/src/smtp/client.ts +305 -0
- package/src/smtp/dkim.ts +72 -0
- package/src/smtp/sockets.ts +296 -0
- package/src/test.ts +70 -0
- package/src/transport.ts +35 -0
- package/src/transports/cloudflare.ts +68 -0
- package/src/transports/http.ts +75 -0
- package/src/transports/mailgun.ts +31 -0
- package/src/transports/outbox.ts +64 -0
- package/src/transports/postmark.ts +59 -0
- package/src/transports/resend.ts +46 -0
- package/src/transports/sendgrid.ts +64 -0
- package/src/transports/ses.ts +53 -0
- package/src/transports/smtp.ts +37 -0
- package/src/types.ts +104 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type HttpDeps } from "./http.ts";
|
|
2
|
+
import type { MailSender, OpenTransport } from "../transport.ts";
|
|
3
|
+
export declare function createResend(config: {
|
|
4
|
+
apiKey: unknown;
|
|
5
|
+
}, deps?: HttpDeps): MailSender;
|
|
6
|
+
declare const open: OpenTransport;
|
|
7
|
+
export default open;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type HttpDeps } from "./http.ts";
|
|
2
|
+
import type { MailSender, OpenTransport } from "../transport.ts";
|
|
3
|
+
export declare function createSendgrid(config: {
|
|
4
|
+
apiKey: unknown;
|
|
5
|
+
}, deps?: HttpDeps): MailSender;
|
|
6
|
+
declare const open: OpenTransport;
|
|
7
|
+
export default open;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type HttpDeps } from "./http.ts";
|
|
2
|
+
import type { MailSender, OpenTransport } from "../transport.ts";
|
|
3
|
+
export declare function createSes(config: {
|
|
4
|
+
region: string;
|
|
5
|
+
accessKeyId: unknown;
|
|
6
|
+
secretAccessKey: unknown;
|
|
7
|
+
}, deps?: HttpDeps): MailSender;
|
|
8
|
+
declare const open: OpenTransport;
|
|
9
|
+
export default open;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { EnvRef } from "hamur";
|
|
2
|
+
import type { MailTemplates } from "./index.ts";
|
|
3
|
+
export type { EnvRef };
|
|
4
|
+
/** `"Ada <ada@x.dev>"`, `"ada@x.dev"` or the object. */
|
|
5
|
+
export type MailAddress = string | {
|
|
6
|
+
name?: string;
|
|
7
|
+
address: string;
|
|
8
|
+
};
|
|
9
|
+
export type MailTransport = {
|
|
10
|
+
type: "smtp";
|
|
11
|
+
host: string;
|
|
12
|
+
port?: number;
|
|
13
|
+
secure?: "tls" | "starttls" | false;
|
|
14
|
+
user?: string | EnvRef;
|
|
15
|
+
password?: EnvRef;
|
|
16
|
+
} | {
|
|
17
|
+
type: "resend";
|
|
18
|
+
apiKey: EnvRef;
|
|
19
|
+
} | {
|
|
20
|
+
type: "postmark";
|
|
21
|
+
serverToken: EnvRef;
|
|
22
|
+
messageStream?: string;
|
|
23
|
+
} | {
|
|
24
|
+
type: "sendgrid";
|
|
25
|
+
apiKey: EnvRef;
|
|
26
|
+
} | {
|
|
27
|
+
type: "mailgun";
|
|
28
|
+
apiKey: EnvRef;
|
|
29
|
+
domain: string;
|
|
30
|
+
region?: "us" | "eu";
|
|
31
|
+
} | {
|
|
32
|
+
type: "ses";
|
|
33
|
+
region: string;
|
|
34
|
+
accessKeyId: EnvRef;
|
|
35
|
+
secretAccessKey: EnvRef;
|
|
36
|
+
} | {
|
|
37
|
+
type: "cloudflare";
|
|
38
|
+
binding: string;
|
|
39
|
+
} | {
|
|
40
|
+
type: "outbox";
|
|
41
|
+
dir?: string;
|
|
42
|
+
};
|
|
43
|
+
/** `selector` names the DNS record `<selector>._domainkey.<domain>` that holds the public key. */
|
|
44
|
+
export interface MailDkim {
|
|
45
|
+
domain: string;
|
|
46
|
+
selector: string;
|
|
47
|
+
/** A PKCS #8 RSA private key in PEM. */
|
|
48
|
+
privateKey: EnvRef;
|
|
49
|
+
}
|
|
50
|
+
export interface MailConfig {
|
|
51
|
+
from: MailAddress;
|
|
52
|
+
replyTo?: MailAddress;
|
|
53
|
+
transport?: MailTransport;
|
|
54
|
+
/** Default false: `sendMail` sends in the call. */
|
|
55
|
+
queue?: boolean;
|
|
56
|
+
/** Signs each message the smtp transport sends. */
|
|
57
|
+
dkim?: MailDkim;
|
|
58
|
+
}
|
|
59
|
+
export type MailTemplateName = keyof MailTemplates & string;
|
|
60
|
+
export interface MailAttachment {
|
|
61
|
+
filename: string;
|
|
62
|
+
content: Uint8Array | Blob | string;
|
|
63
|
+
contentType?: string;
|
|
64
|
+
cid?: string;
|
|
65
|
+
}
|
|
66
|
+
export interface MailMessage<T extends MailTemplateName = MailTemplateName> {
|
|
67
|
+
to: MailAddress | MailAddress[];
|
|
68
|
+
cc?: MailAddress | MailAddress[];
|
|
69
|
+
bcc?: MailAddress | MailAddress[];
|
|
70
|
+
/** Default `mail.from`. */
|
|
71
|
+
from?: MailAddress;
|
|
72
|
+
replyTo?: MailAddress;
|
|
73
|
+
subject: string;
|
|
74
|
+
template?: T;
|
|
75
|
+
props?: MailTemplates[T];
|
|
76
|
+
/** A body without a template. */
|
|
77
|
+
html?: string;
|
|
78
|
+
text?: string;
|
|
79
|
+
attachments?: MailAttachment[];
|
|
80
|
+
headers?: Record<string, string>;
|
|
81
|
+
/** Passed to HTTP providers that take tags; ignored by smtp, cloudflare and outbox. */
|
|
82
|
+
tags?: string[];
|
|
83
|
+
}
|
|
84
|
+
export interface MailResult {
|
|
85
|
+
/** The Message-ID without `<>`. */
|
|
86
|
+
id: string;
|
|
87
|
+
queued: boolean;
|
|
88
|
+
}
|
|
89
|
+
/** One address as the module checked it: the domain in its IDNA form. */
|
|
90
|
+
export interface ParsedAddress {
|
|
91
|
+
name?: string;
|
|
92
|
+
address: string;
|
|
93
|
+
}
|
|
94
|
+
/** The message `mail:beforeSend` receives and may change, `from` filled from `mail.from`, every address parsed. */
|
|
95
|
+
export interface RenderedMail {
|
|
96
|
+
from: ParsedAddress;
|
|
97
|
+
to: ParsedAddress[];
|
|
98
|
+
cc: ParsedAddress[];
|
|
99
|
+
bcc: ParsedAddress[];
|
|
100
|
+
replyTo?: ParsedAddress;
|
|
101
|
+
subject: string;
|
|
102
|
+
template?: string;
|
|
103
|
+
html: string;
|
|
104
|
+
text?: string;
|
|
105
|
+
attachments: Array<{
|
|
106
|
+
filename: string;
|
|
107
|
+
content: Uint8Array;
|
|
108
|
+
contentType: string;
|
|
109
|
+
cid?: string;
|
|
110
|
+
}>;
|
|
111
|
+
headers: Record<string, string>;
|
|
112
|
+
tags: string[];
|
|
113
|
+
}
|
|
114
|
+
/** `mail.transport` as the build resolved it: the outbox `dir` absolute, `mail.dkim` on smtp. */
|
|
115
|
+
export type ResolvedMailTransport = Exclude<MailTransport, {
|
|
116
|
+
type: "outbox" | "smtp";
|
|
117
|
+
}> | (Extract<MailTransport, {
|
|
118
|
+
type: "smtp";
|
|
119
|
+
}> & {
|
|
120
|
+
dkim?: MailDkim;
|
|
121
|
+
}) | {
|
|
122
|
+
type: "outbox";
|
|
123
|
+
dir: string;
|
|
124
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hamur/mail",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/productdevbook/hamur.git",
|
|
9
|
+
"directory": "packages/mail"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/types/src/index.d.ts",
|
|
14
|
+
"bun": "./src/index.ts",
|
|
15
|
+
"hamur-source": "./src/index.ts",
|
|
16
|
+
"node": "./dist/src/index.js",
|
|
17
|
+
"default": "./src/index.ts"
|
|
18
|
+
},
|
|
19
|
+
"./server": {
|
|
20
|
+
"types": "./dist/types/src/server/index.d.ts",
|
|
21
|
+
"bun": "./src/server/index.ts",
|
|
22
|
+
"hamur-source": "./src/server/index.ts",
|
|
23
|
+
"node": "./dist/src/server/index.js",
|
|
24
|
+
"default": "./src/server/index.ts"
|
|
25
|
+
},
|
|
26
|
+
"./devtools": {
|
|
27
|
+
"types": "./dist/types/src/devtools.d.ts",
|
|
28
|
+
"bun": "./src/devtools.ts",
|
|
29
|
+
"hamur-source": "./src/devtools.ts",
|
|
30
|
+
"node": "./dist/src/devtools.js",
|
|
31
|
+
"default": "./src/devtools.ts"
|
|
32
|
+
},
|
|
33
|
+
"./test": {
|
|
34
|
+
"types": "./dist/types/src/test.d.ts",
|
|
35
|
+
"bun": "./src/test.ts",
|
|
36
|
+
"hamur-source": "./src/test.ts",
|
|
37
|
+
"node": "./dist/src/test.js",
|
|
38
|
+
"default": "./src/test.ts"
|
|
39
|
+
},
|
|
40
|
+
"./package.json": "./package.json"
|
|
41
|
+
},
|
|
42
|
+
"files": [
|
|
43
|
+
"dist",
|
|
44
|
+
"src"
|
|
45
|
+
],
|
|
46
|
+
"dependencies": {},
|
|
47
|
+
"peerDependencies": {
|
|
48
|
+
"hamur": "~0.0.2"
|
|
49
|
+
}
|
|
50
|
+
}
|
package/src/address.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { ParsedAddress } from "./types.ts"
|
|
2
|
+
|
|
3
|
+
const CONTROL = /[\x00-\x1f\x7f]/
|
|
4
|
+
const LOCAL = /^[^\s@<>()[\],;:\\"\x00-\x1f\x7f]+$/
|
|
5
|
+
const LABEL = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/
|
|
6
|
+
const ATOM = /^[A-Za-z0-9!#$%&'*+\-/=?^_`{|}~ ]+$/
|
|
7
|
+
const ASCII = /^[\x00-\x7f]*$/
|
|
8
|
+
/** RFC 5321 §4.5.3.1: octets of the local part, and of the whole address. */
|
|
9
|
+
const MAX_LOCAL = 64
|
|
10
|
+
const MAX_ADDRESS = 254
|
|
11
|
+
const encoder = new TextEncoder()
|
|
12
|
+
|
|
13
|
+
/** A domain in its IDNA form, as `URL` writes a host name; undefined when it is not one. */
|
|
14
|
+
export function asciiDomain(domain: string): string | undefined {
|
|
15
|
+
if (domain === "" || /[\s/\\?#@:%[\]]/.test(domain)) return undefined
|
|
16
|
+
let host: string
|
|
17
|
+
try {
|
|
18
|
+
host = new URL(`http://${domain}`).hostname
|
|
19
|
+
} catch {
|
|
20
|
+
return undefined
|
|
21
|
+
}
|
|
22
|
+
if (host.length > 253 || host.split(".").some((label) => !LABEL.test(label))) return undefined
|
|
23
|
+
return host
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function parseBare(text: string): ParsedAddress | undefined {
|
|
27
|
+
const at = text.lastIndexOf("@")
|
|
28
|
+
if (at <= 0) return undefined
|
|
29
|
+
const local = text.slice(0, at)
|
|
30
|
+
if (!LOCAL.test(local) || local.startsWith(".") || local.endsWith(".") || local.includes("..")) return undefined
|
|
31
|
+
const domain = asciiDomain(text.slice(at + 1))
|
|
32
|
+
if (domain === undefined) return undefined
|
|
33
|
+
const address = `${local}@${domain}`
|
|
34
|
+
return encoder.encode(local).length > MAX_LOCAL || encoder.encode(address).length > MAX_ADDRESS
|
|
35
|
+
? undefined
|
|
36
|
+
: { address }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** `"Ada <ada@x.dev>"`, `"ada@x.dev"` or `{ name?, address }`; undefined for anything else, a CR or LF included. */
|
|
40
|
+
export function parseAddress(value: unknown): ParsedAddress | undefined {
|
|
41
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
42
|
+
const { name, address } = value as { name?: unknown; address?: unknown }
|
|
43
|
+
if (typeof address !== "string" || (name !== undefined && typeof name !== "string")) return undefined
|
|
44
|
+
if (name !== undefined && CONTROL.test(name)) return undefined
|
|
45
|
+
const parsed = parseBare(address)
|
|
46
|
+
if (!parsed) return undefined
|
|
47
|
+
const trimmed = name?.trim()
|
|
48
|
+
return trimmed ? { name: trimmed, address: parsed.address } : parsed
|
|
49
|
+
}
|
|
50
|
+
if (typeof value !== "string" || CONTROL.test(value)) return undefined
|
|
51
|
+
const text = value.trim()
|
|
52
|
+
const angle = /^(.*?)\s*<([^<>]*)>$/s.exec(text)
|
|
53
|
+
if (!angle) return parseBare(text)
|
|
54
|
+
let name = angle[1]!.trim()
|
|
55
|
+
if (name.length >= 2 && name.startsWith('"') && name.endsWith('"')) name = name.slice(1, -1).replace(/\\(.)/g, "$1")
|
|
56
|
+
else if (/[<>"]/.test(name)) return undefined
|
|
57
|
+
const parsed = parseBare(angle[2]!)
|
|
58
|
+
if (!parsed) return undefined
|
|
59
|
+
return name ? { name, address: parsed.address } : parsed
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** An address list as given: one address or an array of them. */
|
|
63
|
+
export function addressList(value: unknown): unknown[] {
|
|
64
|
+
if (value === undefined) return []
|
|
65
|
+
return Array.isArray(value) ? value : [value]
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** True when the local part needs SMTPUTF8. */
|
|
69
|
+
export function needsSmtpUtf8(address: ParsedAddress): boolean {
|
|
70
|
+
return !ASCII.test(address.address)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** RFC 5322 phrase for a display name: atoms as they are, other ASCII quoted, the rest left to the encoder. */
|
|
74
|
+
export function quotedName(name: string): string {
|
|
75
|
+
if (ATOM.test(name) && !name.startsWith(" ") && !name.endsWith(" ") && !name.includes(" ")) return name
|
|
76
|
+
return `"${name.replace(/(["\\])/g, "\\$1")}"`
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function isAscii(text: string): boolean {
|
|
80
|
+
return ASCII.test(text)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** `Ada <ada@x.dev>` for logs and the outbox record; no encoding. */
|
|
84
|
+
export function shownAddress(address: ParsedAddress): string {
|
|
85
|
+
return address.name ? `${address.name} <${address.address}>` : address.address
|
|
86
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { mkdirSync, watch } from "node:fs"
|
|
2
|
+
import { addDevtoolsTab, createResolver, extendDevtoolsRpc, useDevChannel, type HamurContext } from "hamur/kit"
|
|
3
|
+
import type { ResolvedMailTransport } from "../types.ts"
|
|
4
|
+
import { listOutbox, readOutbox, type MailSummary, type OutboxRecord } from "./outbox.ts"
|
|
5
|
+
|
|
6
|
+
const MAIL_ICON =
|
|
7
|
+
'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="2" fill="currentColor" fill-opacity="0.16" stroke="none"></rect><path d="M3 7l9 6 9-6M5 5h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z"></path></svg>'
|
|
8
|
+
|
|
9
|
+
declare module "hamur" {
|
|
10
|
+
interface HamurDevEvents {
|
|
11
|
+
/** The outbox changed; `messages` is the whole list, newest first. */
|
|
12
|
+
"devtools:mail": { messages: MailSummary[] }
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface MailListAnswer {
|
|
17
|
+
transport: string
|
|
18
|
+
messages: MailSummary[]
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
22
|
+
typeof value === "object" && value !== null && !Array.isArray(value)
|
|
23
|
+
|
|
24
|
+
/** The `mail` tab, its RPCs and the `devtools:mail` push; `hamur dev` only has the RPCs and the push. */
|
|
25
|
+
export function setupMailDevtools(
|
|
26
|
+
hamur: HamurContext,
|
|
27
|
+
options: { transport: ResolvedMailTransport | undefined; templates: () => string[] },
|
|
28
|
+
): void {
|
|
29
|
+
const { transport } = options
|
|
30
|
+
addDevtoolsTab({
|
|
31
|
+
name: "mail",
|
|
32
|
+
title: "Mail",
|
|
33
|
+
icon: MAIL_ICON,
|
|
34
|
+
view: { type: "module", entry: createResolver(import.meta.url).resolve("../devtools.ts") },
|
|
35
|
+
})
|
|
36
|
+
if (!hamur.options.dev) return
|
|
37
|
+
const dir = transport?.type === "outbox" ? transport.dir : undefined
|
|
38
|
+
let serverUrl: URL | undefined
|
|
39
|
+
hamur.hooks.hook("dev:ready", ({ url }) => {
|
|
40
|
+
serverUrl = new URL(url)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
extendDevtoolsRpc("mail:list", async (): Promise<MailListAnswer> => ({
|
|
44
|
+
transport: transport?.type ?? "none",
|
|
45
|
+
messages: dir === undefined ? [] : await listOutbox(dir),
|
|
46
|
+
}))
|
|
47
|
+
extendDevtoolsRpc("mail:message", async (args: unknown): Promise<{ record: OutboxRecord; eml: string }> => {
|
|
48
|
+
const name = isObject(args) ? args.name : undefined
|
|
49
|
+
const found = dir !== undefined && typeof name === "string" ? await readOutbox(dir, name) : undefined
|
|
50
|
+
if (!found) throw new Error(`No message ${JSON.stringify(name)} in the outbox`)
|
|
51
|
+
return found
|
|
52
|
+
})
|
|
53
|
+
extendDevtoolsRpc("mail:templates", () => ({ templates: options.templates() }))
|
|
54
|
+
extendDevtoolsRpc("mail:render", async (args: unknown): Promise<{ html: string; text: string }> => {
|
|
55
|
+
if (!serverUrl) throw new Error("The dev server is not serving yet")
|
|
56
|
+
const target = new URL(`${hamur.options.app.baseURL}_hamur/devtools/api/mail/render`, serverUrl)
|
|
57
|
+
const response = await fetch(target, {
|
|
58
|
+
method: "POST",
|
|
59
|
+
headers: { "content-type": "application/json" },
|
|
60
|
+
body: JSON.stringify(isObject(args) ? { template: args.template, props: args.props } : {}),
|
|
61
|
+
...(target.protocol === "https:" ? { tls: { rejectUnauthorized: false } } : {}),
|
|
62
|
+
})
|
|
63
|
+
const answer = (await response.json().catch(() => ({}))) as { html?: string; text?: string; error?: string }
|
|
64
|
+
if (!response.ok || typeof answer.html !== "string")
|
|
65
|
+
throw new Error(answer.error ?? `The template preview answered ${response.status}`)
|
|
66
|
+
return { html: answer.html, text: answer.text ?? "" }
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
if (dir === undefined) return
|
|
70
|
+
const channel = useDevChannel()
|
|
71
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
72
|
+
try {
|
|
73
|
+
mkdirSync(dir, { recursive: true })
|
|
74
|
+
watch(dir, { persistent: false }, () => {
|
|
75
|
+
clearTimeout(timer)
|
|
76
|
+
timer = setTimeout(() => {
|
|
77
|
+
void listOutbox(dir).then((messages) => channel.send("devtools:mail", { messages }, "devtools"))
|
|
78
|
+
}, 50)
|
|
79
|
+
})
|
|
80
|
+
} catch {}
|
|
81
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { readdir, readFile } from "node:fs/promises"
|
|
2
|
+
import { join } from "node:path"
|
|
3
|
+
|
|
4
|
+
/** The `.json` the outbox writes next to each `.eml`. */
|
|
5
|
+
export interface OutboxRecord {
|
|
6
|
+
id: string
|
|
7
|
+
date: string
|
|
8
|
+
from: string
|
|
9
|
+
to: string[]
|
|
10
|
+
cc: string[]
|
|
11
|
+
bcc: string[]
|
|
12
|
+
subject: string
|
|
13
|
+
template?: string
|
|
14
|
+
html: string
|
|
15
|
+
text: string
|
|
16
|
+
headers: Record<string, string>
|
|
17
|
+
attachments: Array<{ filename: string; contentType: string; size: number }>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** What the `mail` tab's list and the `devtools:mail` push carry of one message; `name` is the file stem. */
|
|
21
|
+
export interface MailSummary {
|
|
22
|
+
name: string
|
|
23
|
+
date: string
|
|
24
|
+
from: string
|
|
25
|
+
to: string[]
|
|
26
|
+
subject: string
|
|
27
|
+
template?: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const names = (dir: string): Promise<string[]> => readdir(dir).catch(() => [])
|
|
31
|
+
|
|
32
|
+
/** The outbox newest first. */
|
|
33
|
+
export async function listOutbox(dir: string): Promise<MailSummary[]> {
|
|
34
|
+
const stems = (await names(dir))
|
|
35
|
+
.filter((file) => file.endsWith(".json"))
|
|
36
|
+
.map((file) => file.slice(0, -".json".length))
|
|
37
|
+
.sort()
|
|
38
|
+
.reverse()
|
|
39
|
+
const summaries = await Promise.all(
|
|
40
|
+
stems.map(async (name): Promise<MailSummary | undefined> => {
|
|
41
|
+
try {
|
|
42
|
+
const record = JSON.parse(await readFile(join(dir, `${name}.json`), "utf8")) as OutboxRecord
|
|
43
|
+
const { date, from, to, subject, template } = record
|
|
44
|
+
return { name, date, from, to, subject, ...(template === undefined ? {} : { template }) }
|
|
45
|
+
} catch {
|
|
46
|
+
return undefined
|
|
47
|
+
}
|
|
48
|
+
}),
|
|
49
|
+
)
|
|
50
|
+
return summaries.filter((summary): summary is MailSummary => summary !== undefined)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** One message; `name` must be a stem the directory lists, so nothing outside the outbox is read. */
|
|
54
|
+
export async function readOutbox(
|
|
55
|
+
dir: string,
|
|
56
|
+
name: string,
|
|
57
|
+
): Promise<{ record: OutboxRecord; eml: string } | undefined> {
|
|
58
|
+
const files = await names(dir)
|
|
59
|
+
if (!files.includes(`${name}.json`) || !files.includes(`${name}.eml`)) return undefined
|
|
60
|
+
try {
|
|
61
|
+
const [record, eml] = await Promise.all([
|
|
62
|
+
readFile(join(dir, `${name}.json`), "utf8").then((text) => JSON.parse(text) as OutboxRecord),
|
|
63
|
+
readFile(join(dir, `${name}.eml`), "utf8"),
|
|
64
|
+
])
|
|
65
|
+
return { record, eml }
|
|
66
|
+
} catch {
|
|
67
|
+
return undefined
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises"
|
|
2
|
+
import { isAbsolute, join, relative, resolve } from "node:path"
|
|
3
|
+
import {
|
|
4
|
+
DiagnosticError,
|
|
5
|
+
addServer,
|
|
6
|
+
addTask,
|
|
7
|
+
addTemplate,
|
|
8
|
+
addTypeTemplate,
|
|
9
|
+
createResolver,
|
|
10
|
+
diagnostic,
|
|
11
|
+
useLogger,
|
|
12
|
+
type HamurContext,
|
|
13
|
+
} from "hamur/kit"
|
|
14
|
+
import type { ResolvedMailOptions } from "../options.ts"
|
|
15
|
+
import type { MailDkim, MailTransport, ResolvedMailTransport } from "../types.ts"
|
|
16
|
+
import { setupMailDevtools } from "./devtools.ts"
|
|
17
|
+
import { scanTemplates, styleWarnings, templatesModule, templateTypes, type MailTemplateFile } from "./templates.ts"
|
|
18
|
+
|
|
19
|
+
const SERVER = "@hamur/mail/server"
|
|
20
|
+
/** The transports this package has a file for under `src/transports/`. */
|
|
21
|
+
const BUILT = new Set(["outbox", "smtp", "resend", "postmark", "sendgrid", "mailgun", "ses", "cloudflare"])
|
|
22
|
+
/** The presets whose process keeps an SMTP connection between sends. */
|
|
23
|
+
const REUSES = new Set(["bun", "node"])
|
|
24
|
+
const WORKERS = new Set(["cloudflare", "cloudflare-pages"])
|
|
25
|
+
/** The ports smtp uses on Workers. */
|
|
26
|
+
const WORKERS_PORTS = [465, 587]
|
|
27
|
+
|
|
28
|
+
const WRANGLER_FILES = ["wrangler.json", "wrangler.jsonc"]
|
|
29
|
+
|
|
30
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
31
|
+
typeof value === "object" && value !== null && !Array.isArray(value)
|
|
32
|
+
|
|
33
|
+
/** The `send_email[].name` entries of the app's wrangler config, with `cloudflare.env`'s block over the top level as the preset writes it. */
|
|
34
|
+
export async function declaredSendEmailBindings(rootDir: string, env: string | undefined): Promise<string[]> {
|
|
35
|
+
let config: Record<string, unknown> = {}
|
|
36
|
+
for (const name of WRANGLER_FILES) {
|
|
37
|
+
const text = await readFile(join(rootDir, name), "utf8").catch(() => undefined)
|
|
38
|
+
if (text === undefined) continue
|
|
39
|
+
const parsed: unknown = Bun.JSONC.parse(text)
|
|
40
|
+
if (isObject(parsed)) config = parsed
|
|
41
|
+
break
|
|
42
|
+
}
|
|
43
|
+
const envs = isObject(config.env) ? config.env : {}
|
|
44
|
+
const chosen = env !== undefined && isObject(envs[env]) ? { ...config, ...envs[env] } : config
|
|
45
|
+
const entries = Array.isArray(chosen.send_email) ? chosen.send_email : []
|
|
46
|
+
return entries.flatMap((entry) => (isObject(entry) && typeof entry.name === "string" ? [entry.name] : []))
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface TransportRun {
|
|
50
|
+
dev: boolean
|
|
51
|
+
/** `NODE_ENV` is `test`, as for the config's `$test` block: `hamur/test` and `bun test`. */
|
|
52
|
+
test: boolean
|
|
53
|
+
/** The build is made by `hamur/test`'s `setup` or the test preload (`HAMUR_TEST_BUILD`): no configured transport is used, so a test never sends. */
|
|
54
|
+
setup?: boolean
|
|
55
|
+
rootDir: string
|
|
56
|
+
buildDir: string
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The configured transport, `outbox` under `hamur dev` and tests when none is set, the outbox `dir` made absolute. */
|
|
60
|
+
export function chooseTransport(
|
|
61
|
+
configured: ResolvedMailOptions["transport"],
|
|
62
|
+
run: TransportRun,
|
|
63
|
+
): ResolvedMailTransport | undefined {
|
|
64
|
+
const transport: MailTransport | undefined = run.setup
|
|
65
|
+
? { type: "outbox" }
|
|
66
|
+
: (configured ?? (run.dev || run.test ? { type: "outbox" } : undefined))
|
|
67
|
+
if (transport?.type !== "outbox") return transport
|
|
68
|
+
const dir = transport.dir === undefined ? join(run.buildDir, "mail") : transport.dir
|
|
69
|
+
return { type: "outbox", dir: isAbsolute(dir) ? dir : resolve(run.rootDir, dir) }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The build errors and warning of a build that is neither `hamur dev` nor a test. */
|
|
73
|
+
export function checkBuild(
|
|
74
|
+
transport: ResolvedMailTransport | undefined,
|
|
75
|
+
preset: string,
|
|
76
|
+
siteUrl: string | undefined,
|
|
77
|
+
sendEmailBindings: readonly string[] = [],
|
|
78
|
+
): string | undefined {
|
|
79
|
+
if (!transport)
|
|
80
|
+
throw new DiagnosticError(
|
|
81
|
+
"HAMUR_E6702",
|
|
82
|
+
`@hamur/mail needs mail.transport on the ${preset} preset; outbox is for hamur dev and tests`,
|
|
83
|
+
)
|
|
84
|
+
if (siteUrl === undefined)
|
|
85
|
+
throw new DiagnosticError("HAMUR_E6703", "@hamur/mail needs site.url: a mail holds absolute links")
|
|
86
|
+
if (transport.type === "cloudflare") {
|
|
87
|
+
if (preset !== "cloudflare")
|
|
88
|
+
throw new DiagnosticError(
|
|
89
|
+
"HAMUR_E6708",
|
|
90
|
+
`mail.transport cloudflare runs on the cloudflare preset only (got ${JSON.stringify(preset)})`,
|
|
91
|
+
)
|
|
92
|
+
if (!sendEmailBindings.includes(transport.binding))
|
|
93
|
+
throw new DiagnosticError(
|
|
94
|
+
"HAMUR_E6709",
|
|
95
|
+
`mail.transport.binding ${JSON.stringify(transport.binding)} is not a send_email binding of the app's wrangler config; add send_email: [{ name: ${JSON.stringify(transport.binding)} }]`,
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
if (WORKERS.has(preset)) {
|
|
99
|
+
if (transport.type === "smtp" && transport.port !== undefined && !WORKERS_PORTS.includes(transport.port))
|
|
100
|
+
throw new DiagnosticError(
|
|
101
|
+
"HAMUR_E6705",
|
|
102
|
+
`mail.transport smtp on the ${preset} preset uses ports 465 or 587; Workers refuse port 25 (got ${transport.port})`,
|
|
103
|
+
)
|
|
104
|
+
if (transport.type === "outbox")
|
|
105
|
+
throw new DiagnosticError(
|
|
106
|
+
"HAMUR_E6706",
|
|
107
|
+
`mail.transport outbox writes files, which the ${preset} preset has none of`,
|
|
108
|
+
)
|
|
109
|
+
}
|
|
110
|
+
if (transport.type === "outbox")
|
|
111
|
+
return diagnostic(
|
|
112
|
+
"HAMUR_W6704",
|
|
113
|
+
`mail.transport is outbox in a build: messages are written to ${transport.dir} and never sent`,
|
|
114
|
+
)
|
|
115
|
+
return undefined
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The warning of a build that sets `mail.dkim` and does not send through smtp. */
|
|
119
|
+
export function dkimWarning(
|
|
120
|
+
dkim: MailDkim | undefined,
|
|
121
|
+
transport: ResolvedMailTransport | undefined,
|
|
122
|
+
): string | undefined {
|
|
123
|
+
return dkim && transport?.type !== "smtp"
|
|
124
|
+
? diagnostic("HAMUR_W6710", "mail.dkim is read by the smtp transport only")
|
|
125
|
+
: undefined
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The `lang` of a template's document. */
|
|
129
|
+
function language(hamur: HamurContext): string {
|
|
130
|
+
const { i18n } = hamur.options as unknown as { i18n?: { defaultLocale?: unknown } }
|
|
131
|
+
return typeof i18n?.defaultLocale === "string" ? i18n.defaultLocale : "en"
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** `#hamur/mail/templates`, `MailTemplates`, the style warnings and the dev rebuild. */
|
|
135
|
+
function setupTemplates(hamur: HamurContext, srcDirs: string[], scan: () => MailTemplateFile[]): void {
|
|
136
|
+
const { rootDir, buildDir } = hamur.options
|
|
137
|
+
addTemplate({
|
|
138
|
+
filename: "mail/templates",
|
|
139
|
+
getContents: () => templatesModule(scan(), () => Bun.resolveSync(hamur.adapter.serverEntry, rootDir)),
|
|
140
|
+
})
|
|
141
|
+
addTypeTemplate(
|
|
142
|
+
{
|
|
143
|
+
filename: "mail.d.ts",
|
|
144
|
+
getContents: () => templateTypes(scan(), join(buildDir, "types"), hamur.adapter.name),
|
|
145
|
+
},
|
|
146
|
+
{ context: ["app", "server"] },
|
|
147
|
+
)
|
|
148
|
+
hamur.hooks.hook("build:before", () => {
|
|
149
|
+
for (const warning of styleWarnings(rootDir, scan())) useLogger("mail").warn(warning)
|
|
150
|
+
})
|
|
151
|
+
hamur.hooks.hook("dev:change", (change) => {
|
|
152
|
+
if (srcDirs.some((dir) => !relative(join(dir, "mail"), change.file).startsWith(".."))) change.rebuildServer = true
|
|
153
|
+
})
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The transport per run, the build checks, the import guard, the server door and `#hamur/mail/config`. */
|
|
157
|
+
export function setupMail(options: ResolvedMailOptions, hamur: HamurContext): void {
|
|
158
|
+
const { dev, preset, rootDir, buildDir } = hamur.options
|
|
159
|
+
const test = process.env.NODE_ENV === "test"
|
|
160
|
+
const testBuild = process.env.HAMUR_TEST_BUILD === "1"
|
|
161
|
+
const chosen = chooseTransport(options.transport, {
|
|
162
|
+
dev,
|
|
163
|
+
test,
|
|
164
|
+
setup: testBuild,
|
|
165
|
+
rootDir,
|
|
166
|
+
buildDir,
|
|
167
|
+
})
|
|
168
|
+
const transport = chosen?.type === "smtp" && options.dkim ? { ...chosen, dkim: options.dkim } : chosen
|
|
169
|
+
|
|
170
|
+
const protection = hamur.options.build.importProtection
|
|
171
|
+
const client = (protection.client ??= {})
|
|
172
|
+
;(client.deny ??= []).push(SERVER)
|
|
173
|
+
|
|
174
|
+
const srcDirs = [hamur.options.srcDir, ...hamur.options.layers.map((layer) => layer.srcDir)]
|
|
175
|
+
// the adapter is not resolved while modules set up, so every read of it is lazy
|
|
176
|
+
const scan = () => scanTemplates(srcDirs, hamur.adapter.extensions)
|
|
177
|
+
|
|
178
|
+
const r = createResolver(import.meta.url)
|
|
179
|
+
addServer(r.resolve(dev ? "../server/door-dev.ts" : "../server/door.ts"))
|
|
180
|
+
addTask({ name: "mail:send", file: r.resolve("../server/task.ts") })
|
|
181
|
+
addTemplate({
|
|
182
|
+
filename: "mail/deliver",
|
|
183
|
+
getContents: () => `export { deliverMail } from ${JSON.stringify(r.resolve("../server/deliver.ts"))};\n`,
|
|
184
|
+
})
|
|
185
|
+
const loaders =
|
|
186
|
+
transport && BUILT.has(transport.type)
|
|
187
|
+
? ` ${JSON.stringify(transport.type)}: () => import(${JSON.stringify(r.resolve(`../transports/${transport.type}.ts`))}),\n`
|
|
188
|
+
: ""
|
|
189
|
+
addTemplate({
|
|
190
|
+
filename: "mail/config",
|
|
191
|
+
getContents: () =>
|
|
192
|
+
[
|
|
193
|
+
`export const from = ${JSON.stringify(options.from)};`,
|
|
194
|
+
`export const replyTo = ${JSON.stringify(options.replyTo ?? null)};`,
|
|
195
|
+
`export const queue = ${options.queue};`,
|
|
196
|
+
`export const testBuild = ${testBuild};`,
|
|
197
|
+
`export const transport = ${JSON.stringify(transport ?? null)};`,
|
|
198
|
+
`export const reuse = ${dev || REUSES.has(preset)};`,
|
|
199
|
+
`export const dev = ${JSON.stringify(dev)};`,
|
|
200
|
+
`export const siteUrl = ${JSON.stringify(hamur.options.site.url ?? null)};`,
|
|
201
|
+
`export const baseURL = ${JSON.stringify(hamur.options.app.baseURL)};`,
|
|
202
|
+
`export const templates = ${JSON.stringify(scan().map(({ name }) => name))};`,
|
|
203
|
+
`export const lang = ${JSON.stringify(language(hamur))};`,
|
|
204
|
+
`export const transports = {\n${loaders}};`,
|
|
205
|
+
"",
|
|
206
|
+
].join("\n"),
|
|
207
|
+
})
|
|
208
|
+
|
|
209
|
+
setupTemplates(hamur, srcDirs, scan)
|
|
210
|
+
setupMailDevtools(hamur, { transport, templates: () => scan().map(({ name }) => name) })
|
|
211
|
+
|
|
212
|
+
hamur.hooks.hook("build:before", async () => {
|
|
213
|
+
if (dev || test) return
|
|
214
|
+
const bindings =
|
|
215
|
+
transport?.type === "cloudflare" ? await declaredSendEmailBindings(rootDir, hamur.options.cloudflare.env) : []
|
|
216
|
+
const warning = checkBuild(
|
|
217
|
+
transport,
|
|
218
|
+
preset,
|
|
219
|
+
hamur.options.site.url ?? (process.env.HAMUR_SITE_URL || undefined),
|
|
220
|
+
bindings,
|
|
221
|
+
)
|
|
222
|
+
if (warning) useLogger("mail").warn(warning)
|
|
223
|
+
const unsigned = dkimWarning(options.dkim, transport)
|
|
224
|
+
if (unsigned) useLogger("mail").warn(unsigned)
|
|
225
|
+
})
|
|
226
|
+
}
|