Branchwell

Skillfarm / website · skillfarm.ai / src / lib / email.ts

Raw 9.9 KB on 154cbccf923a68550a73e85d66bba0b0fb8f1943
1import type { Env, User } from '../env';
2import { escapeHtml, newId, now } from './util';
3
4type Mail = { to: string; subject: string; heading: string; lines: string[]; cta?: { label: string; url: string }; kind: string; userId?: string | null };
5
6function layout(env: Env, m: Mail): string {
7 const body = m.lines.map((l) => `<p style="margin:0 0 14px;font-size:16px;line-height:1.55;color:#3A1F0F;">${l}</p>`).join('');
8 const cta = m.cta
9 ? `<p style="margin:22px 0 6px;"><a href="${escapeHtml(m.cta.url)}" style="display:inline-block;background:#5A8A4A;color:#FFFBEF;text-decoration:none;font-weight:600;font-size:16px;padding:12px 20px;border-radius:10px;">${escapeHtml(m.cta.label)}</a></p>`
10 : '';
11 return `<!doctype html><html><body style="margin:0;padding:0;background:#F6EFD9;font-family:-apple-system,Segoe UI,Helvetica,Arial,sans-serif;">
12<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#F6EFD9;padding:28px 12px;"><tr><td align="center">
13<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:560px;background:#FFFBEF;border:1px solid #E3D7B8;border-radius:16px;">
14<tr><td style="padding:22px 28px 0;font-size:18px;font-weight:700;color:#5A8A4A;">Skillfarm</td></tr>
15<tr><td style="padding:14px 28px 26px;">
16<h1 style="margin:0 0 16px;font-size:24px;line-height:1.25;color:#3A1F0F;">${escapeHtml(m.heading)}</h1>
17${body}${cta}
18</td></tr></table>
19<p style="max-width:560px;margin:14px auto 0;font-size:13px;line-height:1.5;color:#6B4A35;">You are getting this because you have a Skillfarm account. Change email notices in your <a href="${env.SITE_URL}/settings" style="color:#3F6B34;">settings</a>.</p>
20</td></tr></table></body></html>`;
21}
22
23function textVersion(m: Mail): string {
24 const strip = (s: string) => s.replace(/<[^>]+>/g, '').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'");
25 return [m.heading, '', ...m.lines.map(strip), '', m.cta ? `${m.cta.label}: ${m.cta.url}` : ''].join('\n').trim();
26}
27
28async function log(env: Env, m: Mail, status: string, detail?: string) {
29 try {
30 await env.DB.prepare('INSERT INTO email_log (id, user_id, kind, status, detail, created_at) VALUES (?,?,?,?,?,?)')
31 .bind(newId(), m.userId ?? null, m.kind, status, detail?.slice(0, 300) ?? null, now())
32 .run();
33 } catch {
34 /* logging must never break the caller */
35 }
36}
37
38export async function sendMail(env: Env, m: Mail): Promise<boolean> {
39 if (!env.RESEND_API_KEY) {
40 await log(env, m, 'skipped', 'RESEND_API_KEY is not set');
41 return false;
42 }
43 try {
44 const res = await fetch('https://api.resend.com/emails', {
45 method: 'POST',
46 headers: { authorization: `Bearer ${env.RESEND_API_KEY}`, 'content-type': 'application/json' },
47 body: JSON.stringify({ from: env.EMAIL_FROM, to: [m.to], subject: m.subject, html: layout(env, m), text: textVersion(m) }),
48 });
49 if (!res.ok) {
50 await log(env, m, 'failed', `${res.status} ${await res.text()}`);
51 return false;
52 }
53 await log(env, m, 'sent');
54 return true;
55 } catch (e) {
56 await log(env, m, 'failed', String(e));
57 return false;
58 }
59}
60
61type Recipient = Pick<User, 'id' | 'email' | 'email_notices' | 'display_name' | 'status'>;
62
63async function toUser(env: Env, user: Recipient | null, m: Omit<Mail, 'to' | 'userId'>): Promise<boolean> {
64 if (!user || !user.email || !user.email_notices) return false;
65 return sendMail(env, { ...m, to: user.email, userId: user.id });
66}
67
68const e = escapeHtml;
69
70export const mail = {
71 welcome: (env: Env, user: Recipient, handle: string) =>
72 toUser(env, user, {
73 kind: 'welcome',
74 subject: 'Welcome to Skillfarm',
75 heading: `Welcome to the farm, ${user.display_name}`,
76 lines: [
77 'Your profile is ready. Share an agent skill and you earn Seeds, which raise your tier and get your portfolio more exposure.',
78 'Every skill is reviewed before it goes live, so the first step is to plant one.',
79 ],
80 cta: { label: 'Share your first skill', url: `${env.SITE_URL}/share` },
81 }),
82 received: (env: Env, user: Recipient, title: string, url: string) =>
83 toUser(env, user, {
84 kind: 'received',
85 subject: `We received "${title}"`,
86 heading: 'Your skill is in the review queue',
87 lines: [`<strong>${e(title)}</strong> was submitted and is waiting for review. Nothing is public yet.`, 'You will get another email as soon as it is approved or denied.'],
88 cta: { label: 'View your submission', url },
89 }),
90 approved: (env: Env, user: Recipient, title: string, url: string, seeds: number) =>
91 toUser(env, user, {
92 kind: 'approved',
93 subject: `"${title}" is live on Skillfarm`,
94 heading: 'Approved. Your skill is live.',
95 lines: [
96 `<strong>${e(title)}</strong> passed review and is now public.`,
97 seeds > 0 ? `You earned <strong>${seeds} Seeds</strong> for sharing it. Installs, likes and replants earn more.` : 'This update replaces the previous version.',
98 ],
99 cta: { label: 'See it on Skillfarm', url },
100 }),
101 denied: (env: Env, user: Recipient, title: string, url: string, note: string) =>
102 toUser(env, user, {
103 kind: 'denied',
104 subject: `"${title}" was not approved`,
105 heading: 'Your skill was not approved',
106 lines: [
107 `<strong>${e(title)}</strong> did not pass review, so it is not public.`,
108 note ? `Reviewer note: ${e(note)}` : 'No reviewer note was left.',
109 'You can fix the issue and submit a new version from the skill page.',
110 ],
111 cta: { label: 'Open your submission', url },
112 }),
113 removed: (env: Env, user: Recipient, title: string, note: string) =>
114 toUser(env, user, {
115 kind: 'removed',
116 subject: `"${title}" was taken down`,
117 heading: 'Your skill was taken down',
118 lines: [`<strong>${e(title)}</strong> was removed from Skillfarm by a moderator, and the Seeds it earned were reversed.`, note ? `Moderator note: ${e(note)}` : ''].filter(Boolean),
119 }),
120 tierUp: (env: Env, user: Recipient, tierName: string, perk: string, handle: string) =>
121 toUser(env, user, {
122 kind: 'tier-up',
123 subject: `You are now a ${tierName} on Skillfarm`,
124 heading: `You grew into ${tierName}`,
125 lines: [`Your Seeds carried you to a new tier.`, `New at this tier: ${e(perk)}.`],
126 cta: { label: 'See your profile', url: `${env.SITE_URL}/u/${handle}` },
127 }),
128 repoReceived: (env: Env, user: Recipient, repo: string, queued: number, skipped: number, url: string) =>
129 toUser(env, user, {
130 kind: 'repo-received',
131 subject: `We received ${repo}`,
132 heading: 'Your repo is in the review queue',
133 lines: [
134 `Skillfarm read <strong>${e(repo)}</strong> and found ${queued === 1 ? '1 skill' : `${queued} skills`} to review.${skipped ? ` ${skipped === 1 ? '1 folder was' : `${skipped} folders were`} left out, and the page below says why.` : ''}`,
135 'Nothing is public yet. A person reviews the repo and each skill in it. You will get an email with the decision.',
136 ],
137 cta: { label: 'See what was found', url },
138 }),
139 repoDenied: (env: Env, user: Recipient, repo: string, count: number, note: string, url: string) =>
140 toUser(env, user, {
141 kind: 'repo-denied',
142 subject: `${repo} was not approved`,
143 heading: 'Your repo was not approved',
144 lines: [
145 `<strong>${e(repo)}</strong> did not pass review, so ${count === 1 ? 'its skill is' : `its ${count} skills are`} not public.`,
146 note ? `Reviewer note: ${e(note)}` : 'No reviewer note was left.',
147 'You are welcome to improve the skills and share the repo again. In the meantime you can like and comment on other skills.',
148 ],
149 cta: { label: 'Open your submission', url },
150 }),
151 repoApproved: (env: Env, user: Recipient, repo: string, titles: string[], seeds: number, url: string) =>
152 toUser(env, user, {
153 kind: 'repo-approved',
154 subject: `${titles.length === 1 ? '1 skill' : `${titles.length} skills`} from ${repo} ${titles.length === 1 ? 'is' : 'are'} live on Skillfarm`,
155 heading: 'Approved. Your skills are live.',
156 lines: [
157 `These passed review and are now on your profile: <strong>${titles.slice(0, 25).map(e).join(', ')}</strong>.`,
158 seeds > 0 ? `You earned <strong>${seeds} Seeds</strong> for sharing them. Installs, likes and replants earn more.` : '',
159 ].filter(Boolean),
160 cta: { label: 'See your profile', url },
161 }),
162 adminRepo: async (env: Env, repo: string, owner: string, count: number, url: string) => {
163 const admins = await env.DB.prepare("SELECT id, email, email_notices, display_name, status FROM users WHERE is_admin = 1 AND status = 'active'").all<Recipient>();
164 for (const a of admins.results) {
165 await toUser(env, a, {
166 kind: 'admin-repo',
167 subject: `Review needed: ${repo} by @${owner} (${count === 1 ? '1 skill' : `${count} skills`})`,
168 heading: 'A shared repo is ready for your review',
169 lines: [`<strong>${e(repo)}</strong> by @${e(owner)} holds ${count === 1 ? '1 skill' : `${count} skills`}.`, 'The AI review of each skill fills in over the next few minutes. You can deny the whole repo in one step, or approve and deny skills one by one.'],
170 cta: { label: 'Open the repo', url },
171 });
172 }
173 },
174 adminReview: async (env: Env, title: string, owner: string, recommendation: string, summary: string) => {
175 const admins = await env.DB.prepare("SELECT id, email, email_notices, display_name, status FROM users WHERE is_admin = 1 AND status = 'active'").all<Recipient>();
176 for (const a of admins.results) {
177 await toUser(env, a, {
178 kind: 'admin-review',
179 subject: `Review needed: "${title}" by @${owner} (AI: ${recommendation})`,
180 heading: 'A submission is ready for your review',
181 lines: [`<strong>${e(title)}</strong> by @${e(owner)}`, `AI recommendation: <strong>${e(recommendation)}</strong>`, e(summary)],
182 cta: { label: 'Open the review queue', url: `${env.SITE_URL}/admin` },
183 });
184 }
185 },
186};