communication-systems
Email, notifications, and messaging system patterns
What this skill does
# Communication Systems
## Overview
Building email systems, push notifications, in-app messaging, and webhook integrations.
---
## Email Systems
### Transactional Email
```typescript
import { Resend } from 'resend';
const resend = new Resend(process.env.RESEND_API_KEY);
interface EmailOptions {
to: string | string[];
subject: string;
html?: string;
text?: string;
template?: string;
data?: Record<string, any>;
attachments?: Array<{
filename: string;
content: Buffer | string;
}>;
}
async function sendEmail(options: EmailOptions) {
let html = options.html;
// Use template if specified
if (options.template) {
html = await renderTemplate(options.template, options.data);
}
const { data, error } = await resend.emails.send({
from: '[email protected]',
to: options.to,
subject: options.subject,
html,
text: options.text,
attachments: options.attachments,
});
if (error) {
console.error('Email send failed:', error);
throw error;
}
// Log for tracking
await prisma.emailLog.create({
data: {
messageId: data.id,
to: Array.isArray(options.to) ? options.to.join(',') : options.to,
subject: options.subject,
template: options.template,
status: 'sent',
},
});
return data;
}
// Email templates with React Email
import { render } from '@react-email/render';
import { WelcomeEmail } from './templates/WelcomeEmail';
import { PasswordResetEmail } from './templates/PasswordResetEmail';
const templates = {
welcome: WelcomeEmail,
passwordReset: PasswordResetEmail,
};
async function renderTemplate(name: string, data: Record<string, any>) {
const Template = templates[name];
if (!Template) throw new Error(`Template ${name} not found`);
return render(<Template {...data} />);
}
// React Email template
import {
Html, Head, Body, Container, Text, Button, Img,
} from '@react-email/components';
function WelcomeEmail({ name, actionUrl }: { name: string; actionUrl: string }) {
return (
<Html>
<Head />
<Body style={{ fontFamily: 'Arial, sans-serif' }}>
<Container>
<Img src="https://example.com/logo.png" width="120" height="40" alt="Logo" />
<Text>Hi {name},</Text>
<Text>Welcome to our platform! Get started by setting up your account.</Text>
<Button
href={actionUrl}
style={{ background: '#007bff', color: '#fff', padding: '12px 24px' }}
>
Get Started
</Button>
</Container>
</Body>
</Html>
);
}
```
### Email Queue
```typescript
import Bull from 'bull';
const emailQueue = new Bull('email', process.env.REDIS_URL);
// Add to queue
async function queueEmail(options: EmailOptions, delay?: number) {
return emailQueue.add('send', options, {
delay,
attempts: 3,
backoff: { type: 'exponential', delay: 60000 },
});
}
// Process queue
emailQueue.process('send', async (job) => {
await sendEmail(job.data);
});
// Handle failures
emailQueue.on('failed', async (job, error) => {
console.error(`Email job ${job.id} failed:`, error);
await prisma.emailLog.update({
where: { jobId: job.id },
data: { status: 'failed', error: error.message },
});
});
// Bulk email with rate limiting
async function sendBulkEmail(recipients: string[], template: string, data: Record<string, any>) {
const jobs = recipients.map((to, index) => ({
name: 'send',
data: { to, template, data },
opts: { delay: index * 100 }, // Stagger sends
}));
await emailQueue.addBulk(jobs);
}
```
---
## Push Notifications
### Web Push
```typescript
import webpush from 'web-push';
webpush.setVapidDetails(
'mailto:[email protected]',
process.env.VAPID_PUBLIC_KEY!,
process.env.VAPID_PRIVATE_KEY!
);
interface PushSubscription {
endpoint: string;
keys: {
p256dh: string;
auth: string;
};
}
// Store subscription
async function saveSubscription(userId: string, subscription: PushSubscription) {
await prisma.pushSubscription.upsert({
where: { endpoint: subscription.endpoint },
update: { keys: subscription.keys },
create: {
userId,
endpoint: subscription.endpoint,
keys: subscription.keys,
},
});
}
// Send push notification
async function sendPush(userId: string, payload: {
title: string;
body: string;
icon?: string;
url?: string;
data?: Record<string, any>;
}) {
const subscriptions = await prisma.pushSubscription.findMany({
where: { userId },
});
const results = await Promise.allSettled(
subscriptions.map(async (sub) => {
try {
await webpush.sendNotification(
{ endpoint: sub.endpoint, keys: sub.keys },
JSON.stringify(payload)
);
} catch (error) {
if (error.statusCode === 410) {
// Subscription expired, remove it
await prisma.pushSubscription.delete({ where: { id: sub.id } });
}
throw error;
}
})
);
return results;
}
// Service worker handler
// public/sw.js
self.addEventListener('push', (event) => {
const data = event.data.json();
event.waitUntil(
self.registration.showNotification(data.title, {
body: data.body,
icon: data.icon || '/icon-192.png',
data: data,
})
);
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
if (event.notification.data.url) {
event.waitUntil(clients.openWindow(event.notification.data.url));
}
});
```
### Mobile Push (FCM)
```typescript
import admin from 'firebase-admin';
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
interface MobileNotification {
title: string;
body: string;
imageUrl?: string;
data?: Record<string, string>;
}
async function sendMobilePush(
tokens: string[],
notification: MobileNotification
) {
const message: admin.messaging.MulticastMessage = {
tokens,
notification: {
title: notification.title,
body: notification.body,
imageUrl: notification.imageUrl,
},
data: notification.data,
android: {
priority: 'high',
notification: {
sound: 'default',
clickAction: 'OPEN_ACTIVITY',
},
},
apns: {
payload: {
aps: {
sound: 'default',
badge: 1,
},
},
},
};
const response = await admin.messaging().sendEachForMulticast(message);
// Handle failures
response.responses.forEach((resp, idx) => {
if (!resp.success) {
const errorCode = resp.error?.code;
if (
errorCode === 'messaging/invalid-registration-token' ||
errorCode === 'messaging/registration-token-not-registered'
) {
// Remove invalid token
removeDeviceToken(tokens[idx]);
}
}
});
return response;
}
```
---
## In-App Notifications
```typescript
interface Notification {
id: string;
userId: string;
type: string;
title: string;
message: string;
data?: Record<string, any>;
read: boolean;
createdAt: Date;
}
// Create notification
async function createNotification(params: {
userId: string;
type: string;
title: string;
message: string;
data?: Record<string, any>;
}) {
const notification = await prisma.notification.create({
data: {
...params,
read: false,
},
});
// Send real-time update
await pubsub.publish(`notifications:${params.userId}`, {
type: 'NEW_NOTIFICATION',
notification,
});
return notification;
}
// Get notifications with pagination
async function getNotifications(userId: string, options: {
page?: number;
limit?: number;
unreadOnly?: boolean;
}) {
const { page = 1, limit = 20, unreadOnly = false } = options;
const where = {
userId,
...(unreadOnly && { read: false }),
};
const [notifications, total, unreadCount] = await Promise.all([
prisma.notification.findMany({
where,
orderBy: { createdAt: 'desc'Related in Productivity
gitea-workflow
IncludedOrchestrate agile development workflows for Gitea repositories using the tea CLI. Use when working with Gitea-hosted repos and asking to 'run the workflow', 'continue working', 'what's next', 'complete the task cycle', 'start my day', 'end the sprint', 'implement the next task', or wanting guided step-by-step development assistance. Keywords: workflow, orchestrate, agile, task cycle, sprint, daily, implement, review, PR, standup, retrospective, gitea, tea.
microsoft-graph-gateway
IncludedRoute Microsoft Graph work in this workspace. Use when users want to read or write Outlook mail, calendar events, contacts, OneDrive or SharePoint files, Teams, Planner, To Do, users, groups, directory data, or arbitrary Microsoft Graph endpoints from VS Code. Prefer WorkIQ for common read scenarios. Use Microsoft Graph for write actions and gap-read scenarios that need exact Graph properties, filters, permissions, or endpoints.
copilotkit
IncludedUse when building with CopilotKit — setup, development, integrations, debugging, upgrading, or contributing. Routes to the appropriate specialized skill based on the task.
wordly-wisdom
IncludedProvides calibrated decision analysis using Charlie Munger-style multiple mental models, inversion, incentive mapping, circle-of-competence checks, misjudgment audits, second-order effects, and forecast updates. Use when the user asks for an oracle take, a hard call, a decision memo, a premortem, an outside view, a red-team, a sanity-check, what am I missing, think this through, or wants a strategy, hire, investment, plan, product, partnership, or major life choice analysed. Avoid for simple factual lookups or time-sensitive legal, medical, or market questions without fresh evidence.
swain-session
IncludedSession management and project status dashboard. Owns the full session lifecycle (start/work/close/resume), focus lane, bookmarks, worktree detection, and tab naming. Also serves as the project status dashboard — shows active epics, progress, actionable next steps, blocked items, tasks, GitHub issues, and recommendations. Worktree creation is deferred to swain-do task dispatch (SPEC-195). Triggers on: 'session', 'status', 'what's next', 'dashboard', 'overview', 'where are we', 'what should I work on', 'show me priorities', 'bookmark', 'focus on', 'session info'.
gandi
IncludedComprehensive Gandi domain registrar integration for domain and DNS management. Register and manage domains, create/update/delete DNS records (A, AAAA, CNAME, MX, TXT, SRV, and more), configure email forwarding and aliases, check SSL certificate status, create DNS snapshots for safe rollback, bulk update zone files, and monitor domain expiration. Supports multi-domain management, zone file import/export, and automated DNS backups. Includes both read-only and destructive operations with safety controls.