@weft-framework/server 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.
- package/LICENSE +21 -0
- package/README.md +4 -2
- package/dist/account.d.ts +124 -0
- package/dist/account.js +344 -0
- package/dist/action.d.ts +43 -0
- package/dist/action.js +135 -0
- package/dist/admin.d.ts +99 -0
- package/dist/admin.js +431 -0
- package/dist/api.d.ts +21 -0
- package/dist/api.js +72 -0
- package/dist/app.d.ts +202 -0
- package/dist/app.js +3692 -0
- package/dist/assets.d.ts +4 -0
- package/dist/assets.js +91 -0
- package/dist/auth.d.ts +150 -0
- package/dist/auth.js +215 -0
- package/dist/backup.d.ts +46 -0
- package/dist/backup.js +345 -0
- package/dist/build.d.ts +33 -0
- package/dist/build.js +274 -0
- package/dist/bun.d.ts +30 -0
- package/dist/bun.js +53 -0
- package/dist/calendar.d.ts +161 -0
- package/dist/calendar.js +690 -0
- package/dist/compiler.d.ts +13 -0
- package/dist/compiler.js +58 -0
- package/dist/compress.d.ts +6 -0
- package/dist/compress.js +78 -0
- package/dist/config.d.ts +26 -0
- package/dist/config.js +317 -0
- package/dist/context.d.ts +9 -0
- package/dist/context.js +1 -0
- package/dist/contract.d.ts +18 -0
- package/dist/contract.js +171 -0
- package/dist/datamap.d.ts +24 -0
- package/dist/datamap.js +365 -0
- package/dist/db-backup.d.ts +27 -0
- package/dist/db-backup.js +115 -0
- package/dist/dev-events.d.ts +14 -0
- package/dist/dev-events.js +135 -0
- package/dist/dev.d.ts +1 -0
- package/dist/dev.js +240 -0
- package/dist/devtools-client.d.ts +1 -0
- package/dist/devtools-client.js +362 -0
- package/dist/devtools.d.ts +87 -0
- package/dist/devtools.js +68 -0
- package/dist/edge.d.ts +3 -0
- package/dist/edge.js +7 -0
- package/dist/email-signin.d.ts +92 -0
- package/dist/email-signin.js +259 -0
- package/dist/env.d.ts +1 -0
- package/dist/env.js +15 -0
- package/dist/explain.d.ts +12 -0
- package/dist/explain.js +217 -0
- package/dist/files.d.ts +6 -0
- package/dist/files.js +170 -0
- package/dist/grants.d.ts +69 -0
- package/dist/grants.js +206 -0
- package/dist/image/bitmap.d.ts +11 -0
- package/dist/image/bitmap.js +172 -0
- package/dist/image/jpeg.d.ts +10 -0
- package/dist/image/jpeg.js +697 -0
- package/dist/image/png.d.ts +8 -0
- package/dist/image/png.js +282 -0
- package/dist/image/transform.d.ts +20 -0
- package/dist/image/transform.js +52 -0
- package/dist/image/worker.d.ts +1 -0
- package/dist/image/worker.js +11 -0
- package/dist/images.d.ts +39 -0
- package/dist/images.js +283 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.js +31 -0
- package/dist/inspect-hub.d.ts +42 -0
- package/dist/inspect-hub.js +14 -0
- package/dist/inspector.d.ts +51 -0
- package/dist/inspector.js +193 -0
- package/dist/job-admin.d.ts +55 -0
- package/dist/job-admin.js +89 -0
- package/dist/jobs.d.ts +222 -0
- package/dist/jobs.js +789 -0
- package/dist/live.d.ts +72 -0
- package/dist/live.js +481 -0
- package/dist/load-config.d.ts +2 -0
- package/dist/load-config.js +41 -0
- package/dist/log.d.ts +20 -0
- package/dist/log.js +143 -0
- package/dist/mail.d.ts +189 -0
- package/dist/mail.js +999 -0
- package/dist/media.d.ts +129 -0
- package/dist/media.js +470 -0
- package/dist/meta.d.ts +54 -0
- package/dist/meta.js +146 -0
- package/dist/middleware.d.ts +20 -0
- package/dist/middleware.js +101 -0
- package/dist/migrate.d.ts +12 -0
- package/dist/migrate.js +88 -0
- package/dist/node.d.ts +26 -0
- package/dist/node.js +96 -0
- package/dist/notice.d.ts +21 -0
- package/dist/notice.js +48 -0
- package/dist/npm.d.ts +16 -0
- package/dist/npm.js +347 -0
- package/dist/oauth.d.ts +76 -0
- package/dist/oauth.js +408 -0
- package/dist/otel.d.ts +57 -0
- package/dist/otel.js +293 -0
- package/dist/passkey.d.ts +99 -0
- package/dist/passkey.js +572 -0
- package/dist/password.d.ts +8 -0
- package/dist/password.js +65 -0
- package/dist/pdf.d.ts +46 -0
- package/dist/pdf.js +332 -0
- package/dist/personal-data.d.ts +22 -0
- package/dist/personal-data.js +148 -0
- package/dist/pointers.d.ts +9 -0
- package/dist/pointers.js +148 -0
- package/dist/postcss.d.ts +3 -0
- package/dist/postcss.js +89 -0
- package/dist/presence.d.ts +27 -0
- package/dist/presence.js +161 -0
- package/dist/preview.d.ts +25 -0
- package/dist/preview.js +353 -0
- package/dist/production.d.ts +16 -0
- package/dist/production.js +119 -0
- package/dist/project.d.ts +23 -0
- package/dist/project.js +536 -0
- package/dist/regions.d.ts +47 -0
- package/dist/regions.js +511 -0
- package/dist/replay.d.ts +44 -0
- package/dist/replay.js +259 -0
- package/dist/router.d.ts +29 -0
- package/dist/router.js +146 -0
- package/dist/rules-diff.d.ts +18 -0
- package/dist/rules-diff.js +165 -0
- package/dist/rules-test.d.ts +17 -0
- package/dist/rules-test.js +108 -0
- package/dist/saml.d.ts +160 -0
- package/dist/saml.js +959 -0
- package/dist/seal.d.ts +35 -0
- package/dist/seal.js +107 -0
- package/dist/secret.d.ts +14 -0
- package/dist/secret.js +110 -0
- package/dist/security.d.ts +53 -0
- package/dist/security.js +250 -0
- package/dist/seed.d.ts +16 -0
- package/dist/seed.js +94 -0
- package/dist/seo.d.ts +42 -0
- package/dist/seo.js +175 -0
- package/dist/settings.d.ts +79 -0
- package/dist/settings.js +212 -0
- package/dist/shared.d.ts +15 -0
- package/dist/shared.js +283 -0
- package/dist/shell.d.ts +12 -0
- package/dist/shell.js +118 -0
- package/dist/storage.d.ts +13 -0
- package/dist/storage.js +55 -0
- package/dist/support.d.ts +83 -0
- package/dist/support.js +236 -0
- package/dist/sync.d.ts +35 -0
- package/dist/sync.js +167 -0
- package/dist/tailwind.d.ts +14 -0
- package/dist/tailwind.js +117 -0
- package/dist/two-factor.d.ts +103 -0
- package/dist/two-factor.js +435 -0
- package/dist/uploads.d.ts +185 -0
- package/dist/uploads.js +991 -0
- package/dist/webhooks.d.ts +169 -0
- package/dist/webhooks.js +758 -0
- package/dist/webpush.d.ts +97 -0
- package/dist/webpush.js +372 -0
- package/dist/wizard.d.ts +141 -0
- package/dist/wizard.js +410 -0
- package/dist/workflows.d.ts +134 -0
- package/dist/workflows.js +511 -0
- package/package.json +186 -4
package/dist/mail.js
ADDED
|
@@ -0,0 +1,999 @@
|
|
|
1
|
+
import { withRenderContext } from "@weft-framework/runtime";
|
|
2
|
+
import { defineJob, JobError } from "./jobs.js";
|
|
3
|
+
import { isSecret } from "./secret.js";
|
|
4
|
+
export class MailError extends Error {
|
|
5
|
+
code;
|
|
6
|
+
permanent;
|
|
7
|
+
constructor(code, message, opts = {}) {
|
|
8
|
+
super(message, opts.cause !== undefined ? { cause: opts.cause } : undefined);
|
|
9
|
+
this.name = "MailError";
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.permanent = opts.permanent ?? code === "invalid";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
const invalid = (msg) => new MailError("invalid", msg);
|
|
15
|
+
const EMAIL_RE = /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+(?:[A-Za-z]{2,63}|xn--[A-Za-z0-9-]{1,59})$|^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@localhost$/;
|
|
16
|
+
const CONTROL_RE = /[\u0000-\u001f\u007f\u2028\u2029]/;
|
|
17
|
+
export function parseAddress(input) {
|
|
18
|
+
let name;
|
|
19
|
+
let email;
|
|
20
|
+
if (typeof input === "string") {
|
|
21
|
+
if (CONTROL_RE.test(input))
|
|
22
|
+
throw invalid("an address is one line");
|
|
23
|
+
const t = input.trim();
|
|
24
|
+
if (t.endsWith(">")) {
|
|
25
|
+
const lt = t.lastIndexOf("<");
|
|
26
|
+
email = lt < 0 ? "" : t.slice(lt + 1, -1);
|
|
27
|
+
if (lt < 0 || email.includes("<") || email.includes(">")) {
|
|
28
|
+
throw invalid(`not an address: ${JSON.stringify(input.slice(0, 80))}`);
|
|
29
|
+
}
|
|
30
|
+
name = t.slice(0, lt).trim();
|
|
31
|
+
if (name.length >= 2 && name.startsWith('"') && name.endsWith('"'))
|
|
32
|
+
name = name.slice(1, -1);
|
|
33
|
+
}
|
|
34
|
+
else if (t.includes("<") || t.includes(">")) {
|
|
35
|
+
throw invalid(`not an address: ${JSON.stringify(input.slice(0, 80))}`);
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
name = "";
|
|
39
|
+
email = t;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
else if (input && typeof input === "object" && typeof input.email === "string") {
|
|
43
|
+
name = input.name ?? "";
|
|
44
|
+
email = input.email;
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
throw invalid("an address is a string or { name?, email }");
|
|
48
|
+
}
|
|
49
|
+
if (typeof name !== "string" || CONTROL_RE.test(name) || /[<>]/.test(name) || name.length > 200) {
|
|
50
|
+
throw invalid("a display name is one line of at most 200 characters, without < or >");
|
|
51
|
+
}
|
|
52
|
+
if (CONTROL_RE.test(email) || email.length > 254 || !EMAIL_RE.test(email) || email.indexOf("@") > 64) {
|
|
53
|
+
throw invalid(`not an address: ${JSON.stringify(email.slice(0, 80))}`);
|
|
54
|
+
}
|
|
55
|
+
return { name: name.trim(), email };
|
|
56
|
+
}
|
|
57
|
+
function addressList(v) {
|
|
58
|
+
if (v === undefined)
|
|
59
|
+
return [];
|
|
60
|
+
return (Array.isArray(v) ? v : [v]).map(parseAddress);
|
|
61
|
+
}
|
|
62
|
+
const RESERVED_HEADERS = new Set([
|
|
63
|
+
"from", "to", "cc", "bcc", "reply-to", "subject", "date", "message-id", "mime-version", "sender",
|
|
64
|
+
"content-type", "content-transfer-encoding", "content-disposition", "return-path", "received",
|
|
65
|
+
]);
|
|
66
|
+
const HEADER_NAME_RE = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,76}$/;
|
|
67
|
+
const TAG_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
68
|
+
const CONTENT_TYPE_RE = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,63}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,63}$/;
|
|
69
|
+
const MAX_RECIPIENTS = 50;
|
|
70
|
+
const utf8 = new TextEncoder();
|
|
71
|
+
export function prepareMail(m, o) {
|
|
72
|
+
if (!m || typeof m !== "object")
|
|
73
|
+
throw invalid("a message is an object");
|
|
74
|
+
const from = m.from === undefined ? o.from : parseAddress(m.from);
|
|
75
|
+
const to = addressList(m.to);
|
|
76
|
+
const cc = addressList(m.cc);
|
|
77
|
+
const bcc = addressList(m.bcc);
|
|
78
|
+
const replyTo = addressList(m.replyTo);
|
|
79
|
+
if (to.length + cc.length + bcc.length === 0)
|
|
80
|
+
throw invalid("a message needs a recipient");
|
|
81
|
+
if (to.length + cc.length + bcc.length > MAX_RECIPIENTS)
|
|
82
|
+
throw invalid(`at most ${MAX_RECIPIENTS} recipients per message`);
|
|
83
|
+
if (typeof m.subject !== "string" || m.subject.trim() === "")
|
|
84
|
+
throw invalid("a message needs a subject");
|
|
85
|
+
if (CONTROL_RE.test(m.subject) || m.subject.length > 900)
|
|
86
|
+
throw invalid("a subject is one line of at most 900 characters");
|
|
87
|
+
const html = m.html === undefined || m.html === null ? null : String(m.html);
|
|
88
|
+
if (m.text !== undefined && typeof m.text !== "string")
|
|
89
|
+
throw invalid("text is a string");
|
|
90
|
+
if (html === null && (m.text === undefined || m.text === ""))
|
|
91
|
+
throw invalid("a message needs text or html");
|
|
92
|
+
const text = m.text !== undefined && m.text !== "" ? m.text : htmlToText(html);
|
|
93
|
+
const headers = [];
|
|
94
|
+
for (const [k, v] of Object.entries(m.headers ?? {})) {
|
|
95
|
+
if (!HEADER_NAME_RE.test(k) || RESERVED_HEADERS.has(k.toLowerCase()))
|
|
96
|
+
throw invalid(`header ${JSON.stringify(k)} cannot be set`);
|
|
97
|
+
if (typeof v !== "string" || CONTROL_RE.test(v) || v.length > 900 || /[^\x20-\x7e]/.test(v)) {
|
|
98
|
+
throw invalid(`header ${k}: one line of printable ASCII, at most 900 characters`);
|
|
99
|
+
}
|
|
100
|
+
headers.push([k, v]);
|
|
101
|
+
}
|
|
102
|
+
const tags = [];
|
|
103
|
+
for (const [k, v] of Object.entries(m.tags ?? {})) {
|
|
104
|
+
if (!TAG_RE.test(k) || typeof v !== "string" || !TAG_RE.test(v))
|
|
105
|
+
throw invalid(`tag ${JSON.stringify(k)}: names and values are [A-Za-z0-9_-]{1,64}`);
|
|
106
|
+
tags.push([k, v]);
|
|
107
|
+
}
|
|
108
|
+
const attachments = [];
|
|
109
|
+
for (const a of m.attachments ?? []) {
|
|
110
|
+
if (!a || typeof a.filename !== "string" || a.filename === "" || CONTROL_RE.test(a.filename) || a.filename.length > 200) {
|
|
111
|
+
throw invalid("an attachment needs a one-line filename of at most 200 characters");
|
|
112
|
+
}
|
|
113
|
+
const content = typeof a.content === "string" ? utf8.encode(a.content) : a.content;
|
|
114
|
+
if (!(content instanceof Uint8Array))
|
|
115
|
+
throw invalid(`attachment ${a.filename}: content is bytes or a string`);
|
|
116
|
+
const contentType = a.contentType ?? "application/octet-stream";
|
|
117
|
+
if (!CONTENT_TYPE_RE.test(contentType))
|
|
118
|
+
throw invalid(`attachment ${a.filename}: not a media type: ${contentType}`);
|
|
119
|
+
attachments.push({ filename: a.filename.replace(/^.*[\\/]/, "") || "attachment", content, contentType: contentType.toLowerCase() });
|
|
120
|
+
}
|
|
121
|
+
let size = utf8.encode(m.subject).length + utf8.encode(text).length + (html ? utf8.encode(html).length : 0);
|
|
122
|
+
for (const a of attachments)
|
|
123
|
+
size += Math.ceil(a.content.length / 3) * 4;
|
|
124
|
+
if (size > o.maxBytes)
|
|
125
|
+
throw invalid(`the message is ${size} bytes; the limit is ${o.maxBytes}`);
|
|
126
|
+
const domain = from.email.slice(from.email.indexOf("@") + 1);
|
|
127
|
+
return {
|
|
128
|
+
from,
|
|
129
|
+
to,
|
|
130
|
+
cc,
|
|
131
|
+
bcc,
|
|
132
|
+
replyTo,
|
|
133
|
+
subject: m.subject,
|
|
134
|
+
text,
|
|
135
|
+
html,
|
|
136
|
+
headers,
|
|
137
|
+
attachments,
|
|
138
|
+
tags,
|
|
139
|
+
messageId: o.messageId ?? `<${randomId()}@${domain}>`,
|
|
140
|
+
date: o.date ?? new Date(),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function randomId() {
|
|
144
|
+
const b = crypto.getRandomValues(new Uint8Array(16));
|
|
145
|
+
return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
146
|
+
}
|
|
147
|
+
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
|
|
148
|
+
function decodeEntities(s) {
|
|
149
|
+
return s.replace(/&(#x[0-9a-f]{1,6}|#[0-9]{1,7}|[a-z]+);/gi, (m, e) => {
|
|
150
|
+
if (e[0] === "#") {
|
|
151
|
+
const n = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
|
|
152
|
+
return n > 0 && n <= 0x10ffff && (n < 0xd800 || n > 0xdfff) ? String.fromCodePoint(n) : m;
|
|
153
|
+
}
|
|
154
|
+
return ENTITIES[e.toLowerCase()] ?? m;
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
function hrefOf(tag) {
|
|
158
|
+
const href = tag.toLowerCase().indexOf("href");
|
|
159
|
+
if (href < 0)
|
|
160
|
+
return "";
|
|
161
|
+
let i = href + 4;
|
|
162
|
+
while (i < tag.length && tag[i] === " ")
|
|
163
|
+
i++;
|
|
164
|
+
if (tag[i] !== "=")
|
|
165
|
+
return "";
|
|
166
|
+
i++;
|
|
167
|
+
while (i < tag.length && tag[i] === " ")
|
|
168
|
+
i++;
|
|
169
|
+
const q = tag[i];
|
|
170
|
+
if (q === '"' || q === "'") {
|
|
171
|
+
const end = tag.indexOf(q, i + 1);
|
|
172
|
+
return decodeEntities(tag.slice(i + 1, end < 0 ? tag.length : end)).trim();
|
|
173
|
+
}
|
|
174
|
+
let end = i;
|
|
175
|
+
while (end < tag.length && tag[end] !== " " && tag[end] !== ">")
|
|
176
|
+
end++;
|
|
177
|
+
return decodeEntities(tag.slice(i, end)).trim();
|
|
178
|
+
}
|
|
179
|
+
function skipBlock(html, from, name) {
|
|
180
|
+
const close = `</${name}`;
|
|
181
|
+
let j = from;
|
|
182
|
+
while (j < html.length) {
|
|
183
|
+
const at = html.toLowerCase().indexOf(close, j);
|
|
184
|
+
if (at < 0)
|
|
185
|
+
return html.length;
|
|
186
|
+
let k = at + close.length;
|
|
187
|
+
while (k < html.length && html[k] === " ")
|
|
188
|
+
k++;
|
|
189
|
+
if (html[k] === ">")
|
|
190
|
+
return k + 1;
|
|
191
|
+
j = at + close.length;
|
|
192
|
+
}
|
|
193
|
+
return html.length;
|
|
194
|
+
}
|
|
195
|
+
export function htmlToText(html) {
|
|
196
|
+
const BLOCK = new Set(["p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "table", "tr", "blockquote", "section", "article", "header", "footer", "hr", "pre"]);
|
|
197
|
+
let out = "";
|
|
198
|
+
let i = 0;
|
|
199
|
+
while (i < html.length) {
|
|
200
|
+
const lt = html.indexOf("<", i);
|
|
201
|
+
if (lt < 0) {
|
|
202
|
+
out += html.slice(i);
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
out += html.slice(i, lt);
|
|
206
|
+
if (html.startsWith("<!--", lt)) {
|
|
207
|
+
const end = html.indexOf("-->", lt + 4);
|
|
208
|
+
i = end < 0 ? html.length : end + 3;
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
const gt = html.indexOf(">", lt + 1);
|
|
212
|
+
if (gt < 0) {
|
|
213
|
+
out += html.slice(lt);
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
const raw = html.slice(lt + 1, gt);
|
|
217
|
+
const name = raw.replace(/^\s*\//, "").split(/[\s>/]/, 1)[0].toLowerCase();
|
|
218
|
+
if (name === "script" || name === "style" || name === "head" || name === "title") {
|
|
219
|
+
i = raw.trimStart().startsWith("/") ? gt + 1 : skipBlock(html, gt + 1, name);
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
if (name === "a" && !raw.trimStart().startsWith("/")) {
|
|
223
|
+
const innerFrom = gt + 1;
|
|
224
|
+
i = skipBlock(html, innerFrom, "a");
|
|
225
|
+
const closeAt = html.toLowerCase().lastIndexOf("</a", i);
|
|
226
|
+
const inner = htmlToText(html.slice(innerFrom, closeAt < innerFrom ? innerFrom : closeAt));
|
|
227
|
+
const href = hrefOf(raw);
|
|
228
|
+
const label = inner.replace(/[ \t\u00a0]+/g, " ").trim();
|
|
229
|
+
const scheme = href.trim().toLowerCase();
|
|
230
|
+
if (!href || scheme.startsWith("#") || scheme.startsWith("javascript:") || scheme.startsWith("data:") || scheme.startsWith("vbscript:")) {
|
|
231
|
+
out += label;
|
|
232
|
+
}
|
|
233
|
+
else if (label === "" || label === href || `mailto:${label}` === href) {
|
|
234
|
+
out += href.toLowerCase().startsWith("mailto:") ? href.slice(7) : href;
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
out += `${label} (${href})`;
|
|
238
|
+
}
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
if (name === "br")
|
|
242
|
+
out += "\n";
|
|
243
|
+
else if (name === "li" && !raw.trimStart().startsWith("/"))
|
|
244
|
+
out += "\n- ";
|
|
245
|
+
else if (BLOCK.has(name))
|
|
246
|
+
out += "\n\n";
|
|
247
|
+
else if ((name === "td" || name === "th") && raw.trimStart().startsWith("/"))
|
|
248
|
+
out += " ";
|
|
249
|
+
i = gt + 1;
|
|
250
|
+
}
|
|
251
|
+
return decodeEntities(out)
|
|
252
|
+
.split("\n")
|
|
253
|
+
.map((l) => l.replace(/[ \t\u00a0]+/g, " ").trim())
|
|
254
|
+
.join("\n")
|
|
255
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
256
|
+
.trim();
|
|
257
|
+
}
|
|
258
|
+
function b64(bytes) {
|
|
259
|
+
let s = "";
|
|
260
|
+
for (let i = 0; i < bytes.length; i += 0x8000)
|
|
261
|
+
s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
262
|
+
return btoa(s);
|
|
263
|
+
}
|
|
264
|
+
function fromB64(s) {
|
|
265
|
+
const bin = atob(s);
|
|
266
|
+
const out = new Uint8Array(bin.length);
|
|
267
|
+
for (let i = 0; i < bin.length; i++)
|
|
268
|
+
out[i] = bin.charCodeAt(i);
|
|
269
|
+
return out;
|
|
270
|
+
}
|
|
271
|
+
function wrap76(s) {
|
|
272
|
+
const lines = [];
|
|
273
|
+
for (let i = 0; i < s.length; i += 76)
|
|
274
|
+
lines.push(s.slice(i, i + 76));
|
|
275
|
+
return lines.join("\r\n");
|
|
276
|
+
}
|
|
277
|
+
export function quotedPrintable(text) {
|
|
278
|
+
const out = [];
|
|
279
|
+
for (const line of text.replace(/\r\n|\r|\n/g, "\n").split("\n")) {
|
|
280
|
+
const bytes = utf8.encode(line);
|
|
281
|
+
let cur = "";
|
|
282
|
+
const parts = [];
|
|
283
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
284
|
+
const b = bytes[i];
|
|
285
|
+
const last = i === bytes.length - 1;
|
|
286
|
+
const tok = (b >= 33 && b <= 126 && b !== 61) || ((b === 32 || b === 9) && !last)
|
|
287
|
+
? String.fromCharCode(b)
|
|
288
|
+
: `=${b.toString(16).toUpperCase().padStart(2, "0")}`;
|
|
289
|
+
if (cur.length + tok.length > 75) {
|
|
290
|
+
parts.push(`${cur}=`);
|
|
291
|
+
cur = "";
|
|
292
|
+
}
|
|
293
|
+
cur += tok;
|
|
294
|
+
}
|
|
295
|
+
parts.push(cur);
|
|
296
|
+
out.push(parts.join("\r\n"));
|
|
297
|
+
}
|
|
298
|
+
return out.join("\r\n");
|
|
299
|
+
}
|
|
300
|
+
function encodeWords(s) {
|
|
301
|
+
if (/^[\x20-\x7e]*$/.test(s))
|
|
302
|
+
return s;
|
|
303
|
+
const words = [];
|
|
304
|
+
let chunk = [];
|
|
305
|
+
for (const ch of s) {
|
|
306
|
+
const bytes = utf8.encode(ch);
|
|
307
|
+
if (chunk.length + bytes.length > 36) {
|
|
308
|
+
words.push(`=?UTF-8?B?${b64(Uint8Array.from(chunk))}?=`);
|
|
309
|
+
chunk = [];
|
|
310
|
+
}
|
|
311
|
+
chunk.push(...bytes);
|
|
312
|
+
}
|
|
313
|
+
if (chunk.length)
|
|
314
|
+
words.push(`=?UTF-8?B?${b64(Uint8Array.from(chunk))}?=`);
|
|
315
|
+
return words.join("\r\n ");
|
|
316
|
+
}
|
|
317
|
+
function formatAddress(a) {
|
|
318
|
+
if (a.name === "")
|
|
319
|
+
return a.email;
|
|
320
|
+
const name = /^[\x20-\x7e]*$/.test(a.name)
|
|
321
|
+
? /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~ -]*$/.test(a.name)
|
|
322
|
+
? a.name
|
|
323
|
+
: `"${a.name.replace(/[\\"]/g, "\\$&")}"`
|
|
324
|
+
: encodeWords(a.name);
|
|
325
|
+
return `${name} <${a.email}>`;
|
|
326
|
+
}
|
|
327
|
+
function addressHeader(name, list) {
|
|
328
|
+
return `${name}: ${list.map(formatAddress).join(",\r\n ")}`;
|
|
329
|
+
}
|
|
330
|
+
function filenameParams(name) {
|
|
331
|
+
const ascii = name.replace(/[^\x20-\x7e]|["\\]/g, "_");
|
|
332
|
+
if (ascii === name)
|
|
333
|
+
return `filename="${name}"`;
|
|
334
|
+
const enc = Array.from(utf8.encode(name), (b) => /[A-Za-z0-9!#$&+.^_`|~-]/.test(String.fromCharCode(b)) ? String.fromCharCode(b) : `%${b.toString(16).toUpperCase().padStart(2, "0")}`).join("");
|
|
335
|
+
return `filename="${ascii}";\r\n filename*=UTF-8''${enc}`;
|
|
336
|
+
}
|
|
337
|
+
function rfc5322Date(d) {
|
|
338
|
+
return d.toUTCString().replace(/GMT$/, "+0000");
|
|
339
|
+
}
|
|
340
|
+
export function buildMime(m) {
|
|
341
|
+
const boundary = (tag) => `=_weft_${tag}_${randomId()}`;
|
|
342
|
+
const head = [
|
|
343
|
+
addressHeader("From", [m.from]),
|
|
344
|
+
...(m.to.length ? [addressHeader("To", m.to)] : []),
|
|
345
|
+
...(m.cc.length ? [addressHeader("Cc", m.cc)] : []),
|
|
346
|
+
...(m.replyTo.length ? [addressHeader("Reply-To", m.replyTo)] : []),
|
|
347
|
+
`Subject: ${encodeWords(m.subject)}`,
|
|
348
|
+
`Date: ${rfc5322Date(m.date)}`,
|
|
349
|
+
`Message-ID: ${m.messageId}`,
|
|
350
|
+
"MIME-Version: 1.0",
|
|
351
|
+
...m.headers.map(([k, v]) => `${k}: ${v}`),
|
|
352
|
+
];
|
|
353
|
+
const textPart = (type, body) => `Content-Type: ${type}; charset=utf-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n${quotedPrintable(body)}`;
|
|
354
|
+
let body = m.html === null
|
|
355
|
+
? textPart("text/plain", m.text)
|
|
356
|
+
: (() => {
|
|
357
|
+
const b = boundary("alt");
|
|
358
|
+
return (`Content-Type: multipart/alternative;\r\n boundary="${b}"\r\n\r\n` +
|
|
359
|
+
`--${b}\r\n${textPart("text/plain", m.text)}\r\n--${b}\r\n${textPart("text/html", m.html)}\r\n--${b}--`);
|
|
360
|
+
})();
|
|
361
|
+
if (m.attachments.length) {
|
|
362
|
+
const b = boundary("mix");
|
|
363
|
+
const parts = [body, ...m.attachments.map((a) => `Content-Type: ${a.contentType}\r\nContent-Transfer-Encoding: base64\r\n` +
|
|
364
|
+
`Content-Disposition: attachment;\r\n ${filenameParams(a.filename)}\r\n\r\n${wrap76(b64(a.content))}`)];
|
|
365
|
+
body = `Content-Type: multipart/mixed;\r\n boundary="${b}"\r\n\r\n${parts.map((p) => `--${b}\r\n${p}`).join("\r\n")}\r\n--${b}--`;
|
|
366
|
+
}
|
|
367
|
+
return `${head.join("\r\n")}\r\n${body}\r\n`;
|
|
368
|
+
}
|
|
369
|
+
const reveal = (s) => (isSecret(s) ? s.reveal() : s);
|
|
370
|
+
function needSecret(what, s) {
|
|
371
|
+
if (!isSecret(s) && (typeof s !== "string" || s === ""))
|
|
372
|
+
throw new Error(`${what} is a string or a Secret`);
|
|
373
|
+
}
|
|
374
|
+
function httpFailure(provider, status, detail) {
|
|
375
|
+
const transient = status === 429 || status >= 500;
|
|
376
|
+
return new MailError(transient ? "unavailable" : "rejected", `${provider}: HTTP ${status}${detail ? `: ${detail}` : ""}`, { permanent: !transient });
|
|
377
|
+
}
|
|
378
|
+
async function post(provider, f, url, init, timeoutMs) {
|
|
379
|
+
let res;
|
|
380
|
+
try {
|
|
381
|
+
res = await f(url, { ...init, method: "POST", redirect: "error", signal: AbortSignal.timeout(timeoutMs) });
|
|
382
|
+
}
|
|
383
|
+
catch (err) {
|
|
384
|
+
throw new MailError("unavailable", `${provider}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
385
|
+
}
|
|
386
|
+
const raw = await res.text().catch(() => "");
|
|
387
|
+
let body = null;
|
|
388
|
+
try {
|
|
389
|
+
body = raw ? JSON.parse(raw) : null;
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
body = null;
|
|
393
|
+
}
|
|
394
|
+
if (!res.ok) {
|
|
395
|
+
const detail = body && typeof body === "object" ? String(body.message ?? body.Message ?? "") : "";
|
|
396
|
+
throw httpFailure(provider, res.status, detail.slice(0, 200));
|
|
397
|
+
}
|
|
398
|
+
return { status: res.status, body };
|
|
399
|
+
}
|
|
400
|
+
const httpDefaults = (o) => ({
|
|
401
|
+
fetch: o.fetch ?? ((i, init) => fetch(i, init)),
|
|
402
|
+
timeoutMs: o.timeoutMs ?? 15_000,
|
|
403
|
+
});
|
|
404
|
+
export function resend(o) {
|
|
405
|
+
needSecret("resend: apiKey", o.apiKey);
|
|
406
|
+
const { fetch: f, timeoutMs } = httpDefaults(o);
|
|
407
|
+
const endpoint = o.endpoint ?? "https://api.resend.com/emails";
|
|
408
|
+
return {
|
|
409
|
+
name: "resend",
|
|
410
|
+
async send(m) {
|
|
411
|
+
const body = {
|
|
412
|
+
from: formatAddress(m.from),
|
|
413
|
+
to: m.to.map(formatAddress),
|
|
414
|
+
...(m.cc.length ? { cc: m.cc.map(formatAddress) } : {}),
|
|
415
|
+
...(m.bcc.length ? { bcc: m.bcc.map(formatAddress) } : {}),
|
|
416
|
+
...(m.replyTo.length ? { reply_to: m.replyTo.map(formatAddress) } : {}),
|
|
417
|
+
subject: m.subject,
|
|
418
|
+
text: m.text,
|
|
419
|
+
...(m.html !== null ? { html: m.html } : {}),
|
|
420
|
+
headers: Object.fromEntries([["Message-ID", m.messageId], ...m.headers]),
|
|
421
|
+
...(m.attachments.length
|
|
422
|
+
? { attachments: m.attachments.map((a) => ({ filename: a.filename, content: b64(a.content), content_type: a.contentType })) }
|
|
423
|
+
: {}),
|
|
424
|
+
...(m.tags.length ? { tags: m.tags.map(([name, value]) => ({ name, value })) } : {}),
|
|
425
|
+
};
|
|
426
|
+
const res = await post("resend", f, endpoint, {
|
|
427
|
+
headers: {
|
|
428
|
+
authorization: `Bearer ${reveal(o.apiKey)}`,
|
|
429
|
+
"content-type": "application/json",
|
|
430
|
+
"idempotency-key": m.messageId.slice(1, -1).slice(0, 256),
|
|
431
|
+
},
|
|
432
|
+
body: JSON.stringify(body),
|
|
433
|
+
}, timeoutMs);
|
|
434
|
+
const id = res.body?.id;
|
|
435
|
+
return { id: typeof id === "string" ? id : null };
|
|
436
|
+
},
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
export function postmark(o) {
|
|
440
|
+
needSecret("postmark: serverToken", o.serverToken);
|
|
441
|
+
const { fetch: f, timeoutMs } = httpDefaults(o);
|
|
442
|
+
const endpoint = o.endpoint ?? "https://api.postmarkapp.com/email";
|
|
443
|
+
return {
|
|
444
|
+
name: "postmark",
|
|
445
|
+
async send(m) {
|
|
446
|
+
const list = (l) => l.map(formatAddress).join(", ");
|
|
447
|
+
const body = {
|
|
448
|
+
From: formatAddress(m.from),
|
|
449
|
+
To: list(m.to),
|
|
450
|
+
...(m.cc.length ? { Cc: list(m.cc) } : {}),
|
|
451
|
+
...(m.bcc.length ? { Bcc: list(m.bcc) } : {}),
|
|
452
|
+
...(m.replyTo.length ? { ReplyTo: list(m.replyTo) } : {}),
|
|
453
|
+
Subject: m.subject,
|
|
454
|
+
TextBody: m.text,
|
|
455
|
+
...(m.html !== null ? { HtmlBody: m.html } : {}),
|
|
456
|
+
Headers: [["Message-ID", m.messageId], ...m.headers].map(([Name, Value]) => ({ Name, Value })),
|
|
457
|
+
...(m.attachments.length
|
|
458
|
+
? { Attachments: m.attachments.map((a) => ({ Name: a.filename, Content: b64(a.content), ContentType: a.contentType })) }
|
|
459
|
+
: {}),
|
|
460
|
+
...(m.tags.length ? { Metadata: Object.fromEntries(m.tags) } : {}),
|
|
461
|
+
...(o.messageStream ? { MessageStream: o.messageStream } : {}),
|
|
462
|
+
};
|
|
463
|
+
const res = await post("postmark", f, endpoint, {
|
|
464
|
+
headers: { "x-postmark-server-token": reveal(o.serverToken), "content-type": "application/json", accept: "application/json" },
|
|
465
|
+
body: JSON.stringify(body),
|
|
466
|
+
}, timeoutMs);
|
|
467
|
+
const r = res.body;
|
|
468
|
+
if (r && typeof r.ErrorCode === "number" && r.ErrorCode !== 0) {
|
|
469
|
+
throw new MailError("rejected", `postmark: ${String(r.Message ?? r.ErrorCode).slice(0, 200)}`, { permanent: true });
|
|
470
|
+
}
|
|
471
|
+
return { id: typeof r?.MessageID === "string" ? r.MessageID : null };
|
|
472
|
+
},
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
const hex = (b) => Array.from(b instanceof Uint8Array ? b : new Uint8Array(b), (x) => x.toString(16).padStart(2, "0")).join("");
|
|
476
|
+
async function sha256Hex(data) {
|
|
477
|
+
return hex(await crypto.subtle.digest("SHA-256", typeof data === "string" ? utf8.encode(data) : data));
|
|
478
|
+
}
|
|
479
|
+
async function hmac(key, data) {
|
|
480
|
+
const k = await crypto.subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
481
|
+
return new Uint8Array(await crypto.subtle.sign("HMAC", k, utf8.encode(data)));
|
|
482
|
+
}
|
|
483
|
+
const awsEncode = (s) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
484
|
+
export async function signAwsRequest(r) {
|
|
485
|
+
const url = new URL(r.url);
|
|
486
|
+
const amzDate = (r.now ?? new Date()).toISOString().replace(/[-:]|\.\d{3}/g, "");
|
|
487
|
+
const day = amzDate.slice(0, 8);
|
|
488
|
+
const headers = {};
|
|
489
|
+
for (const [k, v] of Object.entries(r.headers ?? {}))
|
|
490
|
+
headers[k.toLowerCase()] = v;
|
|
491
|
+
headers.host = url.host;
|
|
492
|
+
headers["x-amz-date"] = amzDate;
|
|
493
|
+
if (r.credentials.sessionToken !== undefined)
|
|
494
|
+
headers["x-amz-security-token"] = reveal(r.credentials.sessionToken);
|
|
495
|
+
const names = Object.keys(headers).sort();
|
|
496
|
+
const canonicalHeaders = names.map((n) => `${n}:${headers[n].trim().replace(/\s+/g, " ")}\n`).join("");
|
|
497
|
+
const query = [...url.searchParams.entries()]
|
|
498
|
+
.map(([k, v]) => [awsEncode(k), awsEncode(v)])
|
|
499
|
+
.sort(([a, x], [b, y]) => (a < b ? -1 : a > b ? 1 : x < y ? -1 : x > y ? 1 : 0))
|
|
500
|
+
.map(([k, v]) => `${k}=${v}`)
|
|
501
|
+
.join("&");
|
|
502
|
+
const path = url.pathname.split("/").map((seg) => awsEncode(decodeURIComponent(seg))).join("/") || "/";
|
|
503
|
+
const canonical = [r.method.toUpperCase(), path, query, canonicalHeaders, names.join(";"), await sha256Hex(r.body ?? "")].join("\n");
|
|
504
|
+
const scope = `${day}/${r.region}/${r.service}/aws4_request`;
|
|
505
|
+
const toSign = `AWS4-HMAC-SHA256\n${amzDate}\n${scope}\n${await sha256Hex(canonical)}`;
|
|
506
|
+
let key = await hmac(utf8.encode(`AWS4${reveal(r.credentials.secretAccessKey)}`), day);
|
|
507
|
+
key = await hmac(key, r.region);
|
|
508
|
+
key = await hmac(key, r.service);
|
|
509
|
+
key = await hmac(key, "aws4_request");
|
|
510
|
+
const signature = hex(await hmac(key, toSign));
|
|
511
|
+
headers.authorization = `AWS4-HMAC-SHA256 Credential=${r.credentials.accessKeyId}/${scope}, SignedHeaders=${names.join(";")}, Signature=${signature}`;
|
|
512
|
+
return headers;
|
|
513
|
+
}
|
|
514
|
+
export function ses(o) {
|
|
515
|
+
if (typeof o.region !== "string" || !/^[a-z]{2}(-[a-z]+)+-\d$/.test(o.region))
|
|
516
|
+
throw new Error("ses: region is an AWS region name");
|
|
517
|
+
if (typeof o.accessKeyId !== "string" || o.accessKeyId === "")
|
|
518
|
+
throw new Error("ses: accessKeyId is required");
|
|
519
|
+
needSecret("ses: secretAccessKey", o.secretAccessKey);
|
|
520
|
+
const { fetch: f, timeoutMs } = httpDefaults(o);
|
|
521
|
+
const endpoint = o.endpoint ?? `https://email.${o.region}.amazonaws.com/v2/email/outbound-emails`;
|
|
522
|
+
return {
|
|
523
|
+
name: "ses",
|
|
524
|
+
async send(m) {
|
|
525
|
+
const body = JSON.stringify({
|
|
526
|
+
FromEmailAddress: formatAddress(m.from),
|
|
527
|
+
Destination: {
|
|
528
|
+
ToAddresses: m.to.map(formatAddress),
|
|
529
|
+
...(m.cc.length ? { CcAddresses: m.cc.map(formatAddress) } : {}),
|
|
530
|
+
...(m.bcc.length ? { BccAddresses: m.bcc.map(formatAddress) } : {}),
|
|
531
|
+
},
|
|
532
|
+
Content: { Raw: { Data: b64(utf8.encode(buildMime(m))) } },
|
|
533
|
+
...(m.tags.length ? { EmailTags: m.tags.map(([Name, Value]) => ({ Name, Value })) } : {}),
|
|
534
|
+
...(o.configurationSet ? { ConfigurationSetName: o.configurationSet } : {}),
|
|
535
|
+
});
|
|
536
|
+
const headers = await signAwsRequest({
|
|
537
|
+
method: "POST",
|
|
538
|
+
url: endpoint,
|
|
539
|
+
region: o.region,
|
|
540
|
+
service: "ses",
|
|
541
|
+
credentials: o,
|
|
542
|
+
headers: { "content-type": "application/json" },
|
|
543
|
+
body,
|
|
544
|
+
});
|
|
545
|
+
delete headers.host;
|
|
546
|
+
const res = await post("ses", f, endpoint, { headers, body }, timeoutMs);
|
|
547
|
+
const id = res.body?.MessageId;
|
|
548
|
+
return { id: typeof id === "string" ? id : null };
|
|
549
|
+
},
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
class SmtpConnection {
|
|
553
|
+
#buf = "";
|
|
554
|
+
#lines = [];
|
|
555
|
+
#replies = [];
|
|
556
|
+
#waiting = null;
|
|
557
|
+
#failed = null;
|
|
558
|
+
#sock;
|
|
559
|
+
#timeoutMs;
|
|
560
|
+
constructor(sock, timeoutMs) {
|
|
561
|
+
this.#timeoutMs = timeoutMs;
|
|
562
|
+
this.#sock = sock;
|
|
563
|
+
this.#attach(sock);
|
|
564
|
+
}
|
|
565
|
+
#onData = (chunk) => this.#data(String(chunk));
|
|
566
|
+
#onError = (e) => this.#fail(e ?? new Error("connection error"));
|
|
567
|
+
#onClose = () => this.#fail(new Error("connection closed"));
|
|
568
|
+
#attach(sock) {
|
|
569
|
+
sock.on("data", this.#onData);
|
|
570
|
+
sock.on("error", this.#onError);
|
|
571
|
+
sock.on("close", this.#onClose);
|
|
572
|
+
}
|
|
573
|
+
detach() {
|
|
574
|
+
this.#sock.off("data", this.#onData);
|
|
575
|
+
this.#sock.off("error", this.#onError);
|
|
576
|
+
this.#sock.off("close", this.#onClose);
|
|
577
|
+
}
|
|
578
|
+
upgrade(sock) {
|
|
579
|
+
this.#buf = "";
|
|
580
|
+
this.#lines = [];
|
|
581
|
+
this.#replies = [];
|
|
582
|
+
this.#sock = sock;
|
|
583
|
+
this.#attach(sock);
|
|
584
|
+
}
|
|
585
|
+
get socket() {
|
|
586
|
+
return this.#sock;
|
|
587
|
+
}
|
|
588
|
+
#data(s) {
|
|
589
|
+
this.#buf += s;
|
|
590
|
+
if (this.#buf.length > 1 << 20) {
|
|
591
|
+
this.#fail(new Error("reply too long"));
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
let i;
|
|
595
|
+
while ((i = this.#buf.indexOf("\n")) >= 0) {
|
|
596
|
+
const line = this.#buf.slice(0, i).replace(/\r$/, "");
|
|
597
|
+
this.#buf = this.#buf.slice(i + 1);
|
|
598
|
+
const m = /^(\d{3})([ -]|$)(.*)$/.exec(line);
|
|
599
|
+
if (!m) {
|
|
600
|
+
this.#fail(new Error(`not an SMTP reply: ${line.slice(0, 80)}`));
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
this.#lines.push(m[3]);
|
|
604
|
+
if (m[2] !== "-") {
|
|
605
|
+
const reply = { code: Number(m[1]), lines: this.#lines };
|
|
606
|
+
this.#lines = [];
|
|
607
|
+
if (this.#waiting) {
|
|
608
|
+
const w = this.#waiting;
|
|
609
|
+
this.#waiting = null;
|
|
610
|
+
w.resolve(reply);
|
|
611
|
+
}
|
|
612
|
+
else {
|
|
613
|
+
this.#replies.push(reply);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
#fail(e) {
|
|
619
|
+
if (this.#failed === null)
|
|
620
|
+
this.#failed = e;
|
|
621
|
+
if (this.#waiting) {
|
|
622
|
+
const w = this.#waiting;
|
|
623
|
+
this.#waiting = null;
|
|
624
|
+
w.reject(e);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
read() {
|
|
628
|
+
const queued = this.#replies.shift();
|
|
629
|
+
if (queued)
|
|
630
|
+
return Promise.resolve(queued);
|
|
631
|
+
if (this.#failed !== null)
|
|
632
|
+
return Promise.reject(this.#failed);
|
|
633
|
+
return new Promise((resolve, reject) => {
|
|
634
|
+
const timer = setTimeout(() => {
|
|
635
|
+
this.#waiting = null;
|
|
636
|
+
reject(new Error("timed out waiting for the server"));
|
|
637
|
+
}, this.#timeoutMs);
|
|
638
|
+
this.#waiting = {
|
|
639
|
+
resolve: (r) => (clearTimeout(timer), resolve(r)),
|
|
640
|
+
reject: (e) => (clearTimeout(timer), reject(e)),
|
|
641
|
+
};
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
async command(line, expect, what) {
|
|
645
|
+
if (line !== null)
|
|
646
|
+
this.#sock.write(`${line}\r\n`);
|
|
647
|
+
const r = await this.read();
|
|
648
|
+
if (!expect.includes(r.code)) {
|
|
649
|
+
const text = r.lines.join(" ").slice(0, 200);
|
|
650
|
+
throw new MailError(r.code >= 500 ? "rejected" : "unavailable", `smtp ${what}: ${r.code} ${text}`, { permanent: r.code >= 500 });
|
|
651
|
+
}
|
|
652
|
+
return r;
|
|
653
|
+
}
|
|
654
|
+
close() {
|
|
655
|
+
try {
|
|
656
|
+
this.#sock.destroy();
|
|
657
|
+
}
|
|
658
|
+
catch {
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
const isLoopback = (host) => host === "localhost" || /^127\./.test(host) || host === "::1" || host === "[::1]";
|
|
663
|
+
export function smtp(o) {
|
|
664
|
+
if (typeof o.host !== "string" || o.host === "" || /[\s/]/.test(o.host))
|
|
665
|
+
throw new Error("smtp: host is a host name");
|
|
666
|
+
const tlsMode = o.tls ?? (o.port === 465 ? "implicit" : "starttls");
|
|
667
|
+
if (!["implicit", "starttls", "none"].includes(tlsMode))
|
|
668
|
+
throw new Error(`smtp: tls is "implicit", "starttls" or "none"`);
|
|
669
|
+
const port = o.port ?? (tlsMode === "implicit" ? 465 : 587);
|
|
670
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
671
|
+
throw new Error("smtp: port is 1-65535");
|
|
672
|
+
if ((o.user === undefined) !== (o.pass === undefined))
|
|
673
|
+
throw new Error("smtp: user and pass go together");
|
|
674
|
+
if (o.user !== undefined) {
|
|
675
|
+
if (typeof o.user !== "string" || o.user === "" || CONTROL_RE.test(o.user))
|
|
676
|
+
throw new Error("smtp: user is one line");
|
|
677
|
+
needSecret("smtp: pass", o.pass);
|
|
678
|
+
if (tlsMode === "none" && !isLoopback(o.host))
|
|
679
|
+
throw new Error("smtp: credentials are only sent over TLS (or to a loopback test server)");
|
|
680
|
+
}
|
|
681
|
+
const name = o.name ?? "localhost";
|
|
682
|
+
if (!/^[A-Za-z0-9.-]{1,253}$|^\[[0-9a-fA-F:.]{2,45}\]$/.test(name))
|
|
683
|
+
throw new Error("smtp: name is a host name or address literal");
|
|
684
|
+
const timeoutMs = o.timeoutMs ?? 30_000;
|
|
685
|
+
const servername = o.tlsOptions?.servername ?? o.host;
|
|
686
|
+
async function open() {
|
|
687
|
+
const net = await import("node:net");
|
|
688
|
+
const tls = await import("node:tls");
|
|
689
|
+
const sock = await new Promise((resolve, reject) => {
|
|
690
|
+
const s = tlsMode === "implicit"
|
|
691
|
+
? tls.connect({ host: o.host, port, servername, ca: o.tlsOptions?.ca, rejectUnauthorized: true }, () => resolve(s))
|
|
692
|
+
: net.connect({ host: o.host, port }, () => resolve(s));
|
|
693
|
+
s.setTimeout(timeoutMs, () => s.destroy(new Error("connection timed out")));
|
|
694
|
+
s.once("error", reject);
|
|
695
|
+
});
|
|
696
|
+
return new SmtpConnection(sock, timeoutMs);
|
|
697
|
+
}
|
|
698
|
+
async function starttls(conn) {
|
|
699
|
+
const tls = await import("node:tls");
|
|
700
|
+
const plain = conn.socket;
|
|
701
|
+
conn.detach();
|
|
702
|
+
const secure = await new Promise((resolve, reject) => {
|
|
703
|
+
const s = tls.connect({ socket: plain, servername, ca: o.tlsOptions?.ca, rejectUnauthorized: true }, () => resolve(s));
|
|
704
|
+
s.once("error", reject);
|
|
705
|
+
});
|
|
706
|
+
conn.upgrade(secure);
|
|
707
|
+
}
|
|
708
|
+
return {
|
|
709
|
+
name: "smtp",
|
|
710
|
+
async send(m) {
|
|
711
|
+
let conn = null;
|
|
712
|
+
try {
|
|
713
|
+
conn = await open();
|
|
714
|
+
await conn.command(null, [220], "greeting");
|
|
715
|
+
let ehlo = await conn.command(`EHLO ${name}`, [250], "EHLO");
|
|
716
|
+
if (tlsMode === "starttls") {
|
|
717
|
+
if (!ehlo.lines.slice(1).some((l) => /^STARTTLS\b/i.test(l))) {
|
|
718
|
+
throw new MailError("unavailable", "smtp: the server does not offer STARTTLS; refusing to send in plain text");
|
|
719
|
+
}
|
|
720
|
+
await conn.command("STARTTLS", [220], "STARTTLS");
|
|
721
|
+
await starttls(conn);
|
|
722
|
+
ehlo = await conn.command(`EHLO ${name}`, [250], "EHLO");
|
|
723
|
+
}
|
|
724
|
+
if (o.user !== undefined) {
|
|
725
|
+
const auth = ehlo.lines.slice(1).find((l) => /^AUTH[ =]/i.test(l))?.toUpperCase().split(/[ =]/).slice(1) ?? [];
|
|
726
|
+
const pass = reveal(o.pass);
|
|
727
|
+
if (auth.includes("PLAIN")) {
|
|
728
|
+
await conn.command(`AUTH PLAIN ${b64(utf8.encode(`\0${o.user}\0${pass}`))}`, [235], "AUTH");
|
|
729
|
+
}
|
|
730
|
+
else if (auth.includes("LOGIN")) {
|
|
731
|
+
await conn.command("AUTH LOGIN", [334], "AUTH");
|
|
732
|
+
await conn.command(b64(utf8.encode(o.user)), [334], "AUTH");
|
|
733
|
+
await conn.command(b64(utf8.encode(pass)), [235], "AUTH");
|
|
734
|
+
}
|
|
735
|
+
else {
|
|
736
|
+
throw new MailError("rejected", "smtp: the server offers no AUTH PLAIN or LOGIN", { permanent: true });
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
await conn.command(`MAIL FROM:<${m.from.email}>`, [250], "MAIL FROM");
|
|
740
|
+
for (const r of [...m.to, ...m.cc, ...m.bcc])
|
|
741
|
+
await conn.command(`RCPT TO:<${r.email}>`, [250, 251], "RCPT TO");
|
|
742
|
+
await conn.command("DATA", [354], "DATA");
|
|
743
|
+
const data = buildMime(m).replace(/^\./gm, "..");
|
|
744
|
+
const done = await conn.command(`${data}.`, [250], "DATA");
|
|
745
|
+
await conn.command("QUIT", [221], "QUIT").catch(() => { });
|
|
746
|
+
const id = /\b(?:id=|queued as )\s*([A-Za-z0-9._@<>-]+)/i.exec(done.lines.join(" "))?.[1] ?? null;
|
|
747
|
+
return { id };
|
|
748
|
+
}
|
|
749
|
+
catch (err) {
|
|
750
|
+
if (err instanceof MailError)
|
|
751
|
+
throw err;
|
|
752
|
+
throw new MailError("unavailable", `smtp: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
753
|
+
}
|
|
754
|
+
finally {
|
|
755
|
+
conn?.close();
|
|
756
|
+
}
|
|
757
|
+
},
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
const OUTBOXES = Symbol.for("weft.mail.outboxes");
|
|
761
|
+
const outboxes = (globalThis[OUTBOXES] ??= []);
|
|
762
|
+
const order = new WeakMap();
|
|
763
|
+
let sends = 0;
|
|
764
|
+
export class Outbox {
|
|
765
|
+
name = "outbox";
|
|
766
|
+
sent = [];
|
|
767
|
+
#limit;
|
|
768
|
+
#n = 0;
|
|
769
|
+
constructor(opts = {}) {
|
|
770
|
+
this.#limit = Math.max(1, opts.limit ?? 200);
|
|
771
|
+
outboxes.push(this);
|
|
772
|
+
if (outboxes.length > 8)
|
|
773
|
+
outboxes.splice(0, outboxes.length - 8);
|
|
774
|
+
}
|
|
775
|
+
async send(mail) {
|
|
776
|
+
const sent = { mail, raw: buildMime(mail), at: new Date() };
|
|
777
|
+
order.set(sent, ++sends);
|
|
778
|
+
this.sent.push(sent);
|
|
779
|
+
if (this.sent.length > this.#limit)
|
|
780
|
+
this.sent.splice(0, this.sent.length - this.#limit);
|
|
781
|
+
return { id: `outbox-${++this.#n}` };
|
|
782
|
+
}
|
|
783
|
+
last(email) {
|
|
784
|
+
for (let i = this.sent.length - 1; i >= 0; i--) {
|
|
785
|
+
const s = this.sent[i];
|
|
786
|
+
if (email === undefined || [...s.mail.to, ...s.mail.cc, ...s.mail.bcc].some((a) => a.email.toLowerCase() === email.toLowerCase()))
|
|
787
|
+
return s;
|
|
788
|
+
}
|
|
789
|
+
return undefined;
|
|
790
|
+
}
|
|
791
|
+
clear() {
|
|
792
|
+
this.sent.length = 0;
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
const PREVIEW = "/_weft/dev/mail";
|
|
796
|
+
export function mailPreview(req, templates = {}) {
|
|
797
|
+
const path = new URL(req.url).pathname;
|
|
798
|
+
if (path !== PREVIEW && !path.startsWith(`${PREVIEW}/`))
|
|
799
|
+
return null;
|
|
800
|
+
if (req.method !== "GET" && req.method !== "HEAD")
|
|
801
|
+
return new Response("method not allowed", { status: 405 });
|
|
802
|
+
const all = outboxes.flatMap((o) => o.sent).sort((a, b) => (order.get(b) ?? 0) - (order.get(a) ?? 0));
|
|
803
|
+
const base = { "cache-control": "no-store", "x-content-type-options": "nosniff", "referrer-policy": "no-referrer" };
|
|
804
|
+
const sandboxed = "sandbox; default-src 'none'; img-src https: data:; style-src 'unsafe-inline'; font-src https: data:";
|
|
805
|
+
const t = /^\/t\/([A-Za-z0-9_/-]{1,200})\/([A-Za-z0-9_-]{1,64})\.(html|txt)$/.exec(path.slice(PREVIEW.length));
|
|
806
|
+
if (t) {
|
|
807
|
+
const tpl = templates[t[1]];
|
|
808
|
+
const props = tpl?.previews[t[2]];
|
|
809
|
+
if (!tpl || !props)
|
|
810
|
+
return new Response("no such template or sample", { status: 404, headers: base });
|
|
811
|
+
let r;
|
|
812
|
+
try {
|
|
813
|
+
r = renderTemplate(tpl, props);
|
|
814
|
+
}
|
|
815
|
+
catch (err) {
|
|
816
|
+
const text = `${tpl.file}: ${err instanceof Error ? err.message : String(err)}`;
|
|
817
|
+
return new Response(text, { status: 500, headers: { ...base, "content-type": "text/plain; charset=utf-8" } });
|
|
818
|
+
}
|
|
819
|
+
if (t[3] === "txt") {
|
|
820
|
+
const head = r.subject === null ? "" : `Subject: ${r.subject}\n\n`;
|
|
821
|
+
return new Response(head + r.text, { headers: { ...base, "content-type": "text/plain; charset=utf-8" } });
|
|
822
|
+
}
|
|
823
|
+
return new Response(r.html, { headers: { ...base, "content-type": "text/html; charset=utf-8", "content-security-policy": sandboxed } });
|
|
824
|
+
}
|
|
825
|
+
const m = /^\/(\d{1,6})\.(html|txt|eml)$/.exec(path.slice(PREVIEW.length));
|
|
826
|
+
if (m) {
|
|
827
|
+
const s = all[Number(m[1])];
|
|
828
|
+
if (!s)
|
|
829
|
+
return new Response("no such message", { status: 404, headers: base });
|
|
830
|
+
if (m[2] === "html") {
|
|
831
|
+
return new Response(s.mail.html ?? `<pre>${escapeText(s.mail.text)}</pre>`, {
|
|
832
|
+
headers: {
|
|
833
|
+
...base,
|
|
834
|
+
"content-type": "text/html; charset=utf-8",
|
|
835
|
+
"content-security-policy": sandboxed,
|
|
836
|
+
},
|
|
837
|
+
});
|
|
838
|
+
}
|
|
839
|
+
return new Response(m[2] === "txt" ? s.mail.text : s.raw, { headers: { ...base, "content-type": "text/plain; charset=utf-8" } });
|
|
840
|
+
}
|
|
841
|
+
if (path !== PREVIEW && path !== `${PREVIEW}/`)
|
|
842
|
+
return new Response("not found", { status: 404, headers: base });
|
|
843
|
+
const list = (l) => escapeText(l.map((a) => a.email).join(", "));
|
|
844
|
+
const rows = all.map((s, i) => `<li><a href="${PREVIEW}/${i}.html" target="view">${escapeText(s.mail.subject)}</a>` +
|
|
845
|
+
`<small>to ${list([...s.mail.to, ...s.mail.cc])}${s.mail.bcc.length ? `, bcc ${list(s.mail.bcc)}` : ""}<br>` +
|
|
846
|
+
`${s.at.toISOString().slice(11, 19)}, <a href="${PREVIEW}/${i}.txt" target="view">text</a>, ` +
|
|
847
|
+
`<a href="${PREVIEW}/${i}.eml" target="view">source</a></small></li>`).join("");
|
|
848
|
+
const names = Object.keys(templates).sort();
|
|
849
|
+
const tplRows = names.map((name) => {
|
|
850
|
+
const tpl = templates[name];
|
|
851
|
+
const samples = Object.keys(tpl.previews);
|
|
852
|
+
if (!samples.length)
|
|
853
|
+
return `<li><b>${escapeText(name)}</b><small>no \`preview\` export in ${escapeText(tpl.file)}</small></li>`;
|
|
854
|
+
const link = (s, ext, label) => `<a href="${PREVIEW}/t/${escapeText(name)}/${escapeText(s)}.${ext}" target="view">${escapeText(label)}</a>`;
|
|
855
|
+
return (`<li>${link(samples[0], "html", name)}<small>` +
|
|
856
|
+
samples.map((s) => `${samples.length > 1 ? `${link(s, "html", s)}: ` : ""}${link(s, "txt", "text")}`).join(", ") +
|
|
857
|
+
`</small></li>`);
|
|
858
|
+
});
|
|
859
|
+
const page = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Sent mail</title>` +
|
|
860
|
+
`<meta name="viewport" content="width=device-width, initial-scale=1"><style>` +
|
|
861
|
+
`body{margin:0;font:14px/1.45 system-ui,sans-serif;display:grid;grid-template-columns:minmax(16rem,24rem) 1fr;height:100vh;color:#1d1d1b;background:#fff}` +
|
|
862
|
+
`ol{list-style:none;margin:0;padding:0;overflow:auto;border-right:1px solid #ddd}li{padding:.6rem 1rem;border-bottom:1px solid #eee}` +
|
|
863
|
+
`li>a{display:block;color:inherit;font-weight:600;text-decoration:none}small{color:#666}small a{color:inherit}` +
|
|
864
|
+
`h1{font-size:14px;margin:0;padding:.6rem 1rem;border-bottom:1px solid #ddd}p{padding:0 1rem;color:#666}` +
|
|
865
|
+
`iframe{border:0;width:100%;height:100vh}@media (max-width:40rem){body{grid-template-columns:1fr;height:auto}iframe{height:70vh}}` +
|
|
866
|
+
`</style></head><body><div><h1>Sent mail (${all.length})</h1>` +
|
|
867
|
+
(all.length ? `<ol>${rows}</ol>` : "<p>Nothing sent yet. Messages sent through an <code>Outbox</code> transport appear here.</p>") +
|
|
868
|
+
(names.length ? `<h1>Templates (${names.length})</h1><ol>${tplRows.join("")}</ol>` : "") +
|
|
869
|
+
`</div><iframe name="view" title="Message"${all.length ? ` src="${PREVIEW}/0.html"` : ""}></iframe></body></html>`;
|
|
870
|
+
return new Response(page, {
|
|
871
|
+
headers: {
|
|
872
|
+
...base,
|
|
873
|
+
"content-type": "text/html; charset=utf-8",
|
|
874
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; frame-src 'self'; frame-ancestors 'none'",
|
|
875
|
+
},
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
export class Mail {
|
|
879
|
+
#o;
|
|
880
|
+
job;
|
|
881
|
+
constructor(o) {
|
|
882
|
+
if (!o || typeof o.transport?.send !== "function")
|
|
883
|
+
throw new Error("defineMail: transport is a MailTransport");
|
|
884
|
+
const maxBytes = o.maxBytes ?? 10 * 1024 * 1024;
|
|
885
|
+
if (!Number.isInteger(maxBytes) || maxBytes < 1024 || maxBytes > 40 * 1024 * 1024)
|
|
886
|
+
throw new Error("defineMail: maxBytes is 1 KiB-40 MiB");
|
|
887
|
+
if (o.jobs !== undefined && typeof o.jobs !== "function")
|
|
888
|
+
throw new Error("defineMail: jobs is a function returning the queue");
|
|
889
|
+
this.#o = { transport: o.transport, from: parseAddress(o.from), jobs: o.jobs, maxBytes };
|
|
890
|
+
this.job = defineJob(o.jobName ?? "weftMail", [{ name: "message", type: "string" }], async (_ctx, message) => {
|
|
891
|
+
let mail;
|
|
892
|
+
try {
|
|
893
|
+
mail = this.#revive(message);
|
|
894
|
+
}
|
|
895
|
+
catch (err) {
|
|
896
|
+
throw new JobError(`weftMail: ${err instanceof Error ? err.message : String(err)}`, { retry: false, cause: err });
|
|
897
|
+
}
|
|
898
|
+
try {
|
|
899
|
+
await this.#o.transport.send(mail);
|
|
900
|
+
}
|
|
901
|
+
catch (err) {
|
|
902
|
+
if (err instanceof MailError && err.permanent)
|
|
903
|
+
throw new JobError(err.message, { retry: false, cause: err });
|
|
904
|
+
throw err;
|
|
905
|
+
}
|
|
906
|
+
}, { attempts: o.attempts ?? 8, timeoutMs: 120_000 });
|
|
907
|
+
}
|
|
908
|
+
prepare(message) {
|
|
909
|
+
return prepareMail(message, { from: this.#o.from, maxBytes: this.#o.maxBytes });
|
|
910
|
+
}
|
|
911
|
+
async send(message) {
|
|
912
|
+
const mail = this.prepare(message);
|
|
913
|
+
const r = await this.#o.transport.send(mail);
|
|
914
|
+
return { id: r.id, messageId: mail.messageId };
|
|
915
|
+
}
|
|
916
|
+
async queue(ctx, message, opts = {}) {
|
|
917
|
+
if (!this.#o.jobs)
|
|
918
|
+
throw new Error("mail.queue: defineMail({ jobs }) names the queue");
|
|
919
|
+
const mail = this.prepare(message);
|
|
920
|
+
const stored = {
|
|
921
|
+
v: 1,
|
|
922
|
+
from: mail.from,
|
|
923
|
+
to: mail.to,
|
|
924
|
+
cc: mail.cc,
|
|
925
|
+
bcc: mail.bcc,
|
|
926
|
+
replyTo: mail.replyTo,
|
|
927
|
+
subject: mail.subject,
|
|
928
|
+
text: mail.text,
|
|
929
|
+
html: mail.html,
|
|
930
|
+
headers: mail.headers,
|
|
931
|
+
attachments: mail.attachments.map((a) => ({ filename: a.filename, content: b64(a.content), contentType: a.contentType })),
|
|
932
|
+
tags: mail.tags,
|
|
933
|
+
messageId: mail.messageId,
|
|
934
|
+
};
|
|
935
|
+
return this.#o.jobs().enqueue(ctx, this.job, { message: JSON.stringify(stored) }, opts);
|
|
936
|
+
}
|
|
937
|
+
#revive(message) {
|
|
938
|
+
const s = JSON.parse(message);
|
|
939
|
+
if (!s || s.v !== 1)
|
|
940
|
+
throw new Error("not a stored message");
|
|
941
|
+
const back = {
|
|
942
|
+
from: s.from,
|
|
943
|
+
to: s.to,
|
|
944
|
+
cc: s.cc,
|
|
945
|
+
bcc: s.bcc,
|
|
946
|
+
replyTo: s.replyTo,
|
|
947
|
+
subject: s.subject,
|
|
948
|
+
text: s.text,
|
|
949
|
+
...(s.html !== null ? { html: s.html } : {}),
|
|
950
|
+
headers: Object.fromEntries(s.headers),
|
|
951
|
+
attachments: s.attachments.map((a) => ({ filename: a.filename, content: fromB64(a.content), contentType: a.contentType })),
|
|
952
|
+
tags: Object.fromEntries(s.tags),
|
|
953
|
+
};
|
|
954
|
+
if (typeof s.messageId !== "string" || !/^<[A-Za-z0-9._-]{1,128}@[A-Za-z0-9.-]{1,253}>$/.test(s.messageId))
|
|
955
|
+
throw new Error("bad Message-ID");
|
|
956
|
+
return prepareMail(back, { from: this.#o.from, maxBytes: this.#o.maxBytes, messageId: s.messageId });
|
|
957
|
+
}
|
|
958
|
+
render(component, props, opts = {}) {
|
|
959
|
+
return renderMail(component, props, opts);
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
const escapeText = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
963
|
+
export function renderMail(component, props, opts = {}) {
|
|
964
|
+
if (typeof component !== "function" || !component.def)
|
|
965
|
+
throw new Error("renderMail: not a component");
|
|
966
|
+
const css = new Set();
|
|
967
|
+
const ctx = {
|
|
968
|
+
child(def, p) {
|
|
969
|
+
if (def.css)
|
|
970
|
+
css.add(def.css);
|
|
971
|
+
if (def.island)
|
|
972
|
+
throw new Error(`email templates are inert: ${def.name} has browser code`);
|
|
973
|
+
const inst = def.setup(p);
|
|
974
|
+
if (Object.keys(inst.handlers ?? {}).length || inst.mount?.length) {
|
|
975
|
+
throw new Error(`email templates are inert: ${def.name} has ${inst.mount?.length ? "mount hooks" : "event handlers"}`);
|
|
976
|
+
}
|
|
977
|
+
return withRenderContext(ctx, () => inst.render());
|
|
978
|
+
},
|
|
979
|
+
bindArgs: () => "",
|
|
980
|
+
};
|
|
981
|
+
const body = withRenderContext(ctx, () => component(props));
|
|
982
|
+
const lang = opts.lang && /^[A-Za-z]{2,3}(-[A-Za-z0-9]{1,8})*$/.test(opts.lang) ? opts.lang : "en";
|
|
983
|
+
const style = css.size ? `<style>${[...css].join("\n").replace(/<\//g, "<\\/")}</style>` : "";
|
|
984
|
+
const html = `<!doctype html><html lang="${lang}"><head><meta charset="utf-8">` +
|
|
985
|
+
`<meta name="viewport" content="width=device-width, initial-scale=1">` +
|
|
986
|
+
(opts.title ? `<title>${escapeText(opts.title)}</title>` : "") +
|
|
987
|
+
`${style}</head><body>${body}</body></html>`;
|
|
988
|
+
return { html, text: htmlToText(body) };
|
|
989
|
+
}
|
|
990
|
+
export function renderTemplate(t, props) {
|
|
991
|
+
const raw = typeof t.subject === "function" ? t.subject(props) : t.subject;
|
|
992
|
+
if (raw !== undefined && typeof raw !== "string")
|
|
993
|
+
throw new Error("subject must be a string or return one");
|
|
994
|
+
const subject = raw === undefined ? null : raw.replace(/\s*[\r\n]+\s*/g, " ").slice(0, 998);
|
|
995
|
+
return { ...renderMail(t.component, props, subject === null ? {} : { title: subject }), subject };
|
|
996
|
+
}
|
|
997
|
+
export function defineMail(o) {
|
|
998
|
+
return new Mail(o);
|
|
999
|
+
}
|