@plyaz/notifications
v1.3.0
Published
π Unified notification system delivering real-time alerts across email, SMS, push, and in-app channels. Built for scalability with Redis queues and multi-tenant support
Downloads
77
Keywords
Readme
@plyaz/notifications
Unified, multi-channel notification system for email, SMS, and push notifications with multi-provider support, template engine, webhook tracking, and production-ready compliance features.
Installation
pnpm add @plyaz/notificationsRequirements:
- Node.js >= 22.4.0
- pnpm >= 8.0.0
Quick Start
Basic Email Notification
import { NotificationService, SendGridAdapter } from '@plyaz/notifications';
const service = new NotificationService({
providers: {
email: [new SendGridAdapter({
apiKey: process.env.SENDGRID_API_KEY!,
fromEmail: '[email protected]',
fromName: 'My App'
})],
sms: [],
push: []
}
});
// Send email with template
const result = await service.sendEmail({
recipientId: 'user-123',
to: '[email protected]',
templateId: 'welcome',
templateData: { userName: 'John' },
locale: 'en'
});
if (result.success) {
console.log('Email sent:', result.data.providerMessageId);
}Multi-Provider with Fallback
import {
NotificationService,
SendGridAdapter,
InfobipEmailAdapter,
createProductionLogger
} from '@plyaz/notifications';
const logger = createProductionLogger({ service: 'notifications' });
const service = new NotificationService({
providers: {
email: [
new SendGridAdapter({ apiKey: '...', priority: 1 }, logger), // Primary
new InfobipEmailAdapter({ apiKey: '...', priority: 2 }, logger) // Fallback
],
sms: [],
push: []
},
logger
});Template System
Create template at templates/en/email/welcome.md:
---
subject: Welcome {{userName}}!
channel: email
category: transactional
layout: branded
---
# Welcome to our platform, {{userName}}!
Thanks for signing up. Get started by clicking below:
[Get Started]({{dashboardUrl}})Webhooks (SendGrid)
import {
SendGridAdapter,
SendGridWebhookAdapter
} from '@plyaz/notifications';
const service = new NotificationService({
providers: {
email: [new SendGridAdapter({
apiKey: process.env.SENDGRID_API_KEY!,
fromEmail: '[email protected]',
webhooks: [
new SendGridWebhookAdapter({
verificationKey: process.env.SENDGRID_WEBHOOK_KEY!,
onDelivered: (event) => {
console.log('Email delivered:', event.messageId);
},
onBounced: (event) => {
console.log('Email bounced:', event.reason);
}
})
]
})],
sms: [],
push: []
}
});Features
Multi-Channel Support
- β Email - SendGrid, Infobip adapters (100% complete)
- β³ SMS - Mock adapter complete, providers pending
- β³ Push - Mock adapter complete, providers pending
Template System
- Markdown + Handlebars templates
- Multi-language support (i18n)
- 4 layout variants (branded, minimal, transactional, none)
- Automatic CSS inlining for emails
- YAML frontmatter configuration
Provider Management
- Multi-provider setup with automatic failover
- Priority-based routing (1 = highest)
- Circuit breaker pattern
- Health monitoring
- Retry logic with exponential backoff
Compliance & Security
- RFC 8058 one-click unsubscribe
- User preference management
- Token generation (AES-256-GCM, JWT, HMAC-SHA256)
- PII redaction and hashing
- Webhook signature verification
Webhooks
- SendGrid webhook support (ECDSA/HMAC verification)
- Infobip delivery & tracking webhooks
- Event normalization
- Idempotency handling
- Multiple webhook handlers
Advanced Features
- Bulk sending optimization (adapter-level bulk APIs)
- Attachment support (buffer, URL, file path)
- SMS character validation (GSM-7, UCS-2)
- URL shortening (3 adapter types)
- Inline CSS for email compatibility
- Event system (lifecycle, debug, error events)
Channel Support Matrix
| Feature | Email | SMS | Push | |---------|-------|-----|------| | Providers | SendGrid, Infobip, Mock | Mock | Mock | | Templates | β Full | β Full | β Full | | Attachments | β Yes | β No | β No | | Webhooks | β Yes | β³ Pending | β³ Pending | | Bulk Sending | β Yes | β³ Pending | β³ Pending | | Unsubscribe | β Yes | β³ Pending | β³ Pending |
Development Commands
# Development
pnpm dev # Watch mode development
pnpm build # Build for production
pnpm clean # Clean dist directory
# Testing
pnpm test # Run tests once
pnpm test:watch # Run tests in watch mode
pnpm test:coverage # Run tests with coverage
pnpm test:ui # Open Vitest UI
# Code Quality
pnpm lint # Run ESLint
pnpm lint:fix # Auto-fix linting issues
pnpm format # Format code with Prettier
pnpm type:check # TypeScript type checking
# Examples
pnpm example:order-email # Full feature showcase
pnpm example:attachments # Attachments guide
pnpm example:unsubscribe # Unsubscribe system
pnpm example:preferences # User preferences
pnpm example:webhook-complete # Production webhooks
pnpm test:sms-validation # SMS validation
pnpm test:url-shortening # URL shorteningPackage Dependencies
Per Plyaz monorepo architecture:
Uses
- @plyaz/types/notifications - Type definitions
- @plyaz/logger - Structured logging with PII redaction
- @plyaz/api - Global API configuration
- @plyaz/errors - Error handling with correlation IDs
External Dependencies
- @sendgrid/mail - SendGrid API client
- handlebars - Template engine
- marked - Markdown to HTML
- juice - CSS inlining for emails
- gray-matter - YAML frontmatter parsing
- zod - Schema validation
Documentation
- Usage Guide - Complete usage documentation with examples
- API Reference - Detailed API reference
- Implementation Status - Feature completion details
- Examples - 13 production-ready examples
Architecture
NotificationService
βββ ProviderRegistry (adapter selection & routing)
βββ TemplateEngine (Markdown + Handlebars)
βββ EventManager (lifecycle events)
βββ QueueProcessor (async processing)
βββ WebhookManager (delivery tracking)
βββ Email Adapters (SendGrid, Infobip, Mock)
βββ SMS Adapters (Mock)
βββ Push Adapters (Mock)Error Handling
Uses Result type pattern - no exceptions!
const result = await service.sendEmail({ /* ... */ });
if (result.success) {
console.log('Sent:', result.data.providerMessageId);
console.log('Retry attempts:', result.data.retryAttempts);
} else {
console.error('Failed:', result.error.message);
console.error('Error code:', result.error.code);
}Event System
const service = new NotificationService({
providers: { /* ... */ },
// Lifecycle events
events: {
onSent: (event) => console.log('Sent:', event.notificationId),
onFailed: (event) => console.error('Failed:', event.error),
onDelivered: (event) => console.log('Delivered:', event.notificationId)
},
// Debug events
debugEvents: {
onFallbackTriggered: (event) => {
console.warn('Fallback:', event.metadata?.nextProvider);
}
},
// Error handlers
errorHandlers: {
onProviderError: async (error) => {
await errorTracking.report(error);
}
}
});Contributing
When adding new features:
- Add types to
@plyaz/types/notifications - Implement feature with full TypeScript support
- Add comprehensive tests (90% coverage minimum)
- Update documentation (USAGE.md, API-REFERENCES.md)
- Add example in
examples/directory - Update IMPLEMENTATION_STATUS.md
License
ISC Β© Plyaz
