@classytic/notifications 0.0.1 → 2.0.0

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/README.md CHANGED
@@ -1,280 +1,640 @@
1
- # @classytic/notifications
2
-
3
- > Multi-channel notification system for event-driven applications
4
-
5
- Framework-agnostic, pluggable notification dispatcher with zero dependencies. Send notifications to Email, Push, SMS, In-App, Slack, or any custom channel from a single event.
6
-
7
- ## Features
8
-
9
- - ✅ **Multi-Channel** - Email, Push, SMS, In-App, Slack, Discord, etc.
10
- - ✅ **Framework-Agnostic** - Works with Express, Fastify, NestJS, Next.js
11
- - ✅ **Zero Dependencies** - Pure JavaScript, no external deps
12
- - ✅ **Event-Driven** - Integrate with any event system (hooks, EventEmitter)
13
- - ✅ **Pluggable** - Add custom channels by extending base class
14
- - ✅ **Spam Prevention** - Per-channel event whitelists
15
- - ✅ **Fire-and-Forget** - Non-blocking, error-safe
16
- - ✅ **TypeScript Ready** - Full type definitions (coming soon)
17
-
18
- ## Installation
19
-
20
- ```bash
21
- npm install @classytic/notifications
22
- ```
23
-
24
- ## Quick Start
25
-
26
- ### 1. Create a Channel
27
-
28
- ```javascript
29
- import { NotificationChannel } from '@classytic/notifications';
30
-
31
- class EmailChannel extends NotificationChannel {
32
- async send({ event, recipient, data }) {
33
- if (!recipient.email) {
34
- return { status: 'skipped', reason: 'no_email' };
35
- }
36
-
37
- await yourEmailService.send({
38
- to: recipient.email,
39
- subject: `Event: ${event}`,
40
- body: `Amount: ${data.amount}`,
41
- });
42
-
43
- return { status: 'sent' };
44
- }
45
-
46
- getSupportedEvents() {
47
- // Whitelist events (empty = all events)
48
- return ['payment.verified', 'payment.failed'];
49
- }
50
- }
51
- ```
52
-
53
- ### 2. Configure Notifications
54
-
55
- ```javascript
56
- import { createNotificationHandlers } from '@classytic/notifications';
57
-
58
- const channels = [
59
- new EmailChannel({ enabled: true }),
60
- ];
61
-
62
- const configs = [
63
- {
64
- event: 'payment.verified',
65
- enabled: true,
66
- getRecipient: async ({ transaction }) => ({
67
- email: transaction.customerEmail
68
- }),
69
- getTemplateData: ({ transaction }) => ({
70
- amount: transaction.amount
71
- }),
72
- },
73
- ];
74
-
75
- const handlers = createNotificationHandlers(configs, channels);
76
- ```
77
-
78
- ### 3. Use with Your Event System
79
-
80
- **With @classytic/revenue:**
81
- ```javascript
82
- import { createRevenue } from '@classytic/revenue';
83
- import { mergeHooks } from '@classytic/notifications';
84
-
85
- const revenue = createRevenue({
86
- hooks: mergeHooks(
87
- loggingHooks,
88
- createNotificationHandlers(configs, channels)
89
- ),
90
- });
91
- ```
92
-
93
- **With EventEmitter:**
94
- ```javascript
95
- import EventEmitter from 'events';
96
-
97
- const emitter = new EventEmitter();
98
-
99
- Object.entries(handlers).forEach(([event, fns]) => {
100
- fns.forEach(fn => emitter.on(event, fn));
101
- });
102
-
103
- emitter.emit('payment.verified', { transaction });
104
- ```
105
-
106
- **With Custom Hooks:**
107
- ```javascript
108
- const hooks = createNotificationHandlers(configs, channels);
109
-
110
- // Later in your code:
111
- for (const handler of hooks['payment.verified']) {
112
- await handler(eventData);
113
- }
114
- ```
115
-
116
- ## API Reference
117
-
118
- ### NotificationChannel
119
-
120
- Base class for all channels.
121
-
122
- ```javascript
123
- class MyChannel extends NotificationChannel {
124
- async send({ event, recipient, data }) {
125
- // Implement notification logic
126
- return { status: 'sent' };
127
- }
128
-
129
- getSupportedEvents() {
130
- return ['event1', 'event2']; // Or [] for all events
131
- }
132
- }
133
- ```
134
-
135
- ### createDispatcher(channels)
136
-
137
- Creates dispatcher function.
138
-
139
- ```javascript
140
- const dispatcher = createDispatcher([emailChannel, pushChannel]);
141
- await dispatcher(event, eventData, recipientResolver, dataExtractor);
142
- ```
143
-
144
- ### createNotificationHandlers(configs, channels)
145
-
146
- Creates notification handlers from configurations.
147
-
148
- ```javascript
149
- const handlers = createNotificationHandlers(
150
- [{ event: 'user.created', getRecipient: ..., getTemplateData: ... }],
151
- [new EmailChannel()]
152
- );
153
- // Returns: { 'user.created': [Function] }
154
- ```
155
-
156
- ### mergeHooks(...hookConfigs)
157
-
158
- Merges multiple hook configurations.
159
-
160
- ```javascript
161
- const combined = mergeHooks(
162
- { 'event1': [handler1] },
163
- { 'event1': [handler2], 'event2': [handler3] }
164
- );
165
- // Returns: { 'event1': [handler1, handler2], 'event2': [handler3] }
166
- ```
167
-
168
- ## Built-in Channels
169
-
170
- This library provides the **core system only**. Channels are intentionally kept separate for flexibility.
171
-
172
- **Reference implementations:**
173
- - Email (Nodemailer, SendGrid, AWS SES)
174
- - Push (Firebase, OneSignal, Pusher)
175
- - SMS (Twilio, AWS SNS, Vonage)
176
- - In-App (Database storage)
177
- - Slack/Discord (Webhooks)
178
-
179
- See `/examples` directory for channel implementations.
180
-
181
- ## Advanced Usage
182
-
183
- ### Spam Prevention
184
-
185
- ```javascript
186
- new EmailChannel({
187
- enabled: true,
188
- events: [
189
- 'payment.verified', // ✅ Send
190
- 'payment.failed', // ✅ Send
191
- // 'user.login', // ❌ Don't send (too frequent)
192
- ],
193
- })
194
- ```
195
-
196
- ### Multi-Provider Setup
197
-
198
- ```javascript
199
- const channels = [
200
- new EmailChannel({ events: ['payment.verified', 'payment.failed'] }),
201
- new PushChannel({ events: ['payment.verified'] }), // Real-time only
202
- new InAppChannel({ events: [] }), // All events (history)
203
- new SlackChannel({ events: ['payment.failed'] }), // Admin alerts
204
- ];
205
- ```
206
-
207
- ### Conditional Sending
208
-
209
- ```javascript
210
- {
211
- event: 'payment.verified',
212
- enabled: process.env.NODE_ENV === 'production',
213
- getRecipient: async ({ transaction }) => {
214
- // Custom logic
215
- if (transaction.amount < 1000) return null; // Skip small transactions
216
- return getCustomer(transaction.customerId);
217
- },
218
- }
219
- ```
220
-
221
- ## Examples
222
-
223
- See `examples/` directory for:
224
- - Email channel (Nodemailer)
225
- - Push channel (Firebase)
226
- - SMS channel (Twilio)
227
- - Slack channel (Webhooks)
228
- - In-app notifications (MongoDB)
229
-
230
- ## Framework Integration
231
-
232
- ### Express
233
- ```javascript
234
- app.post('/webhook', async (req, res) => {
235
- const handlers = notificationHandlers['payment.verified'];
236
- for (const handler of handlers) {
237
- await handler(req.body);
238
- }
239
- res.json({ success: true });
240
- });
241
- ```
242
-
243
- ### Fastify
244
- ```javascript
245
- fastify.post('/webhook', async (request, reply) => {
246
- const handlers = notificationHandlers['payment.verified'];
247
- for (const handler of handlers) {
248
- await handler(request.body);
249
- }
250
- reply.send({ success: true });
251
- });
252
- ```
253
-
254
- ### NestJS
255
- ```javascript
256
- @Post('webhook')
257
- async handleWebhook(@Body() data) {
258
- const handlers = this.notificationHandlers['payment.verified'];
259
- for (const handler of handlers) {
260
- await handler(data);
261
- }
262
- }
263
- ```
264
-
265
- ## Design Philosophy
266
-
267
- - **KISS** - Simple core, powerful extensions
268
- - **DRY** - One dispatcher, many channels
269
- - **YAGNI** - No unused features
270
- - **Open/Closed** - Open for extension, closed for modification
271
-
272
- ## License
273
-
274
- MIT © Classytic
275
-
276
- ## Related Packages
277
-
278
- - `@classytic/revenue` - Revenue management system (perfect pair)
279
- - `@classytic/mongokit` - MongoDB repository pattern
280
-
1
+ # @classytic/notifications
2
+
3
+ > Multi-channel notification system for TypeScript/Node.js
4
+
5
+ Pluggable channels, templates, retry with backoff, rate limiting, delivery tracking, and user preferences. Zero required dependencies — bring your own providers.
6
+
7
+ ## Features
8
+
9
+ - **Multi-Channel** — Email, SMS, Push, Webhook, Console, or build your own
10
+ - **Zero Required Deps** — Nodemailer is the only optional peer dep; SMS/Push use BYOP (Bring Your Own Provider)
11
+ - **Rate Limiting** — Per-channel token bucket (e.g., Gmail 500/day, SendGrid 100/sec)
12
+ - **Delivery Tracking** — Built-in audit log for every send attempt (sent, skipped, failed)
13
+ - **Queue Adapter** — Crash-resilient delivery with pluggable queue backends
14
+ - **Templates** — Built-in `${var}` interpolation or plug any engine (React Email, MJML, etc.)
15
+ - **Retry + Backoff** — Exponential, linear, or fixed backoff with jitter. Per-channel overrides
16
+ - **User Preferences** — Per-user, per-event, per-channel opt-in/out with quiet hours
17
+ - **Idempotency** — Built-in deduplication with pluggable stores (memory, Redis, DB)
18
+ - **Lifecycle Events** — `before:send`, `after:send`, `send:success`, `send:failed`, `send:retry`, `send:rate_limited`, `send:queued`
19
+ - **Hook Factories** — Generate event handlers for EventEmitter, MongoKit, or any hook system
20
+ - **TypeScript** — Full type definitions, ESM-only
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ npm install @classytic/notifications
26
+ ```
27
+
28
+ **For EmailChannel** (optional — only if you use email):
29
+
30
+ ```bash
31
+ npm install nodemailer
32
+ ```
33
+
34
+ ## Quick Start
35
+
36
+ ```typescript
37
+ import { NotificationService } from '@classytic/notifications';
38
+ import { EmailChannel, SmsChannel, PushChannel, ConsoleChannel } from '@classytic/notifications/channels';
39
+ import { MemoryDeliveryLog, createSimpleResolver } from '@classytic/notifications/utils';
40
+
41
+ const notifications = new NotificationService({
42
+ channels: [
43
+ new EmailChannel({
44
+ from: 'App <noreply@app.com>',
45
+ transport: { host: 'smtp.gmail.com', port: 587, auth: { user, pass } },
46
+ rateLimit: { maxPerWindow: 500, windowMs: 86_400_000 }, // Gmail 500/day
47
+ }),
48
+ new SmsChannel({
49
+ from: '+15551234567',
50
+ provider: {
51
+ send: async ({ to, from, body }) => {
52
+ const msg = await twilioClient.messages.create({ to, from, body });
53
+ return { sid: msg.sid };
54
+ },
55
+ },
56
+ }),
57
+ new PushChannel({
58
+ provider: {
59
+ send: async ({ token, title, body, data }) => {
60
+ const result = await admin.messaging().send({ token, notification: { title, body }, data });
61
+ return { messageId: result };
62
+ },
63
+ },
64
+ }),
65
+ new ConsoleChannel(), // dev/testing
66
+ ],
67
+ templates: createSimpleResolver({
68
+ welcome: {
69
+ subject: 'Welcome, ${name}!',
70
+ html: '<h1>Hi ${name}</h1><p>Thanks for joining.</p>',
71
+ },
72
+ }),
73
+ retry: { maxAttempts: 3, backoff: 'exponential' },
74
+ deliveryLog: new MemoryDeliveryLog(),
75
+ });
76
+
77
+ await notifications.send({
78
+ event: 'user.created',
79
+ recipient: { email: 'user@example.com', phone: '+15559876543', name: 'John' },
80
+ data: { name: 'John' },
81
+ template: 'welcome',
82
+ });
83
+ ```
84
+
85
+ ## Channels
86
+
87
+ ### EmailChannel (Nodemailer)
88
+
89
+ Requires: `npm install nodemailer`
90
+
91
+ ```typescript
92
+ import { EmailChannel } from '@classytic/notifications/channels';
93
+
94
+ // SMTP
95
+ const email = new EmailChannel({
96
+ from: 'App <noreply@app.com>',
97
+ transport: { host: 'smtp.gmail.com', port: 587, auth: { user, pass } },
98
+ rateLimit: { maxPerWindow: 500, windowMs: 86_400_000 }, // Gmail 500/day
99
+ });
100
+
101
+ // Gmail shorthand
102
+ const gmail = new EmailChannel({
103
+ from: 'noreply@app.com',
104
+ transport: { service: 'gmail', auth: { user, pass } },
105
+ });
106
+
107
+ // Pre-created transporter (SES, custom)
108
+ import nodemailer from 'nodemailer';
109
+ const email = new EmailChannel({
110
+ from: 'noreply@app.com',
111
+ transporter: nodemailer.createTransport({ /* SES config */ }),
112
+ });
113
+ ```
114
+
115
+ ### SmsChannel (BYOP)
116
+
117
+ Zero dependencies — bring your own SMS SDK.
118
+
119
+ ```typescript
120
+ import { SmsChannel } from '@classytic/notifications/channels';
121
+
122
+ // Twilio
123
+ import twilio from 'twilio';
124
+ const client = twilio(process.env.TWILIO_SID, process.env.TWILIO_TOKEN);
125
+
126
+ const sms = new SmsChannel({
127
+ from: '+15551234567',
128
+ provider: {
129
+ send: async ({ to, from, body }) => {
130
+ const msg = await client.messages.create({ to, from, body });
131
+ return { sid: msg.sid };
132
+ },
133
+ },
134
+ });
135
+
136
+ // AWS SNS
137
+ import { SNSClient, PublishCommand } from '@aws-sdk/client-sns';
138
+ const sns = new SNSClient({ region: 'us-east-1' });
139
+
140
+ const snsSms = new SmsChannel({
141
+ from: 'MyApp',
142
+ provider: {
143
+ send: async ({ to, body }) => {
144
+ const res = await sns.send(new PublishCommand({ PhoneNumber: to, Message: body }));
145
+ return { sid: res.MessageId ?? '' };
146
+ },
147
+ },
148
+ });
149
+ ```
150
+
151
+ ### PushChannel (BYOP)
152
+
153
+ Zero dependencies — bring your own push SDK.
154
+
155
+ ```typescript
156
+ import { PushChannel } from '@classytic/notifications/channels';
157
+
158
+ // Firebase Cloud Messaging
159
+ import admin from 'firebase-admin';
160
+
161
+ const push = new PushChannel({
162
+ provider: {
163
+ send: async ({ token, title, body, data }) => {
164
+ const result = await admin.messaging().send({
165
+ token,
166
+ notification: { title, body },
167
+ data,
168
+ });
169
+ return { messageId: result };
170
+ },
171
+ },
172
+ });
173
+
174
+ // Expo Push
175
+ import { Expo } from 'expo-server-sdk';
176
+ const expo = new Expo();
177
+
178
+ const expoPush = new PushChannel({
179
+ name: 'expo-push',
180
+ provider: {
181
+ send: async ({ token, title, body, data }) => {
182
+ const [receipt] = await expo.sendPushNotificationsAsync([
183
+ { to: token, title, body, data },
184
+ ]);
185
+ return { messageId: receipt.id };
186
+ },
187
+ },
188
+ });
189
+ ```
190
+
191
+ ### WebhookChannel
192
+
193
+ Zero dependencies — uses native `fetch`.
194
+
195
+ ```typescript
196
+ import { WebhookChannel } from '@classytic/notifications/channels';
197
+
198
+ const slack = new WebhookChannel({
199
+ url: 'https://hooks.slack.com/services/...',
200
+ events: ['order.completed', 'user.created'],
201
+ });
202
+
203
+ // With HMAC-SHA256 signing
204
+ const signed = new WebhookChannel({
205
+ url: 'https://api.partner.com/webhooks',
206
+ secret: process.env.WEBHOOK_SECRET!,
207
+ headers: { 'X-API-Key': process.env.PARTNER_KEY! },
208
+ timeout: 5000,
209
+ });
210
+ ```
211
+
212
+ ### ConsoleChannel
213
+
214
+ Logs to console. Useful for development and testing.
215
+
216
+ ```typescript
217
+ import { ConsoleChannel } from '@classytic/notifications/channels';
218
+
219
+ const dev = new ConsoleChannel();
220
+ const scoped = new ConsoleChannel({ events: ['user.*'] });
221
+ ```
222
+
223
+ ### Custom Channels
224
+
225
+ Extend `BaseChannel` or implement the `Channel` interface directly:
226
+
227
+ ```typescript
228
+ import { BaseChannel } from '@classytic/notifications/channels';
229
+ import type { NotificationPayload, SendResult, ChannelConfig } from '@classytic/notifications';
230
+
231
+ interface SlackConfig extends ChannelConfig {
232
+ webhookUrl: string;
233
+ }
234
+
235
+ class SlackChannel extends BaseChannel<SlackConfig> {
236
+ constructor(config: SlackConfig) {
237
+ super({ name: 'slack', ...config });
238
+ }
239
+
240
+ async send(payload: NotificationPayload): Promise<SendResult> {
241
+ const res = await fetch(this.config.webhookUrl, {
242
+ method: 'POST',
243
+ headers: { 'Content-Type': 'application/json' },
244
+ body: JSON.stringify({ text: String(payload.data.message) }),
245
+ });
246
+ if (!res.ok) return { status: 'failed', channel: this.name, error: res.statusText };
247
+ return { status: 'sent', channel: this.name };
248
+ }
249
+ }
250
+ ```
251
+
252
+ ## Rate Limiting
253
+
254
+ Prevent exceeding provider limits with per-channel rate limiting:
255
+
256
+ ```typescript
257
+ new EmailChannel({
258
+ from: 'noreply@app.com',
259
+ transport: { service: 'gmail', auth: { user, pass } },
260
+ rateLimit: {
261
+ maxPerWindow: 500, // max 500 emails
262
+ windowMs: 86_400_000, // per 24 hours
263
+ },
264
+ });
265
+ ```
266
+
267
+ Rate-limited sends return `status: 'skipped'` with `error: 'Rate limited'` and emit a `send:rate_limited` event. The built-in `MemoryRateLimitStore` is created automatically. For distributed systems, implement `RateLimitStore`:
268
+
269
+ ```typescript
270
+ import type { RateLimitStore, RateLimitConfig } from '@classytic/notifications/utils';
271
+
272
+ class RedisRateLimitStore implements RateLimitStore {
273
+ async consume(channel: string, config: RateLimitConfig): Promise<boolean> {
274
+ // Sliding window rate limiter with Redis
275
+ }
276
+ async remaining(channel: string, config: RateLimitConfig): Promise<number> { /* ... */ }
277
+ async reset(channel: string): Promise<void> { /* ... */ }
278
+ }
279
+
280
+ const service = new NotificationService({
281
+ channels: [...],
282
+ rateLimitStore: new RedisRateLimitStore(),
283
+ });
284
+ ```
285
+
286
+ ## Delivery Tracking
287
+
288
+ Every notification attempt — sent, skipped, or failed — is logged:
289
+
290
+ ```typescript
291
+ import { MemoryDeliveryLog } from '@classytic/notifications/utils';
292
+
293
+ const log = new MemoryDeliveryLog();
294
+ const service = new NotificationService({
295
+ channels: [...],
296
+ deliveryLog: log,
297
+ });
298
+
299
+ // Query history
300
+ const entries = log.query({
301
+ recipientId: 'u1',
302
+ event: 'user.created',
303
+ status: 'delivered',
304
+ after: new Date('2026-01-01'),
305
+ limit: 50,
306
+ });
307
+
308
+ // Get a specific entry
309
+ const entry = log.get(entries[0].id);
310
+ ```
311
+
312
+ For production, implement `DeliveryLog` with your database:
313
+
314
+ ```typescript
315
+ import type { DeliveryLog } from '@classytic/notifications/utils';
316
+
317
+ class MongoDeliveryLog implements DeliveryLog {
318
+ async record(payload, dispatch) { /* insert to MongoDB */ }
319
+ async query(filter) { /* query MongoDB */ }
320
+ async get(id) { /* findById */ }
321
+ }
322
+ ```
323
+
324
+ ## Queue Adapter
325
+
326
+ For crash-resilient delivery, attach a queue. The service owns the queue — it calls `process()` on construction. When configured, `send()` enqueues and returns immediately:
327
+
328
+ ```typescript
329
+ import { MemoryQueue } from '@classytic/notifications/utils';
330
+
331
+ const service = new NotificationService({
332
+ channels: [...],
333
+ queue: new MemoryQueue(),
334
+ });
335
+
336
+ // Sends are now queued and processed async
337
+ await service.send({ ... }); // Returns immediately with { queued: true }
338
+ ```
339
+
340
+ > **Note:** If your app already has its own queue (BullMQ, SQS, etc.), don't pass it here. The service owns its queue. Instead, have your existing worker call `service.send()` directly when it picks up a job.
341
+
342
+ For production, implement `QueueAdapter` with BullMQ, Redis, or your database:
343
+
344
+ ```typescript
345
+ import type { QueueAdapter } from '@classytic/notifications/utils';
346
+
347
+ class BullMQAdapter implements QueueAdapter {
348
+ async enqueue(payload, options?) { /* add to BullMQ */ }
349
+ async process(processor) { /* worker.on('job', ...) */ }
350
+ async getJob(id) { /* ... */ }
351
+ size() { /* ... */ }
352
+ pause() { /* ... */ }
353
+ resume() { /* ... */ }
354
+ drain() { /* ... */ }
355
+ }
356
+ ```
357
+
358
+ ## Scheduled / Delayed Delivery
359
+
360
+ Add `delay` (milliseconds) to any payload. Requires a queue adapter:
361
+
362
+ ```typescript
363
+ // Send reminder in 1 hour
364
+ await service.send({
365
+ event: 'interview.reminder',
366
+ recipient: { email: 'candidate@example.com' },
367
+ data: { subject: 'Interview in 1 hour' },
368
+ delay: 3_600_000,
369
+ });
370
+ ```
371
+
372
+ Without a queue adapter, `delay` is ignored with a warning log.
373
+
374
+ > **For long-delay scheduling** (days/weeks), use a persistent queue backend (BullMQ with Redis) or a workflow engine like `@classytic/streamline` which survives process restarts.
375
+
376
+ ## Channel Fallback
377
+
378
+ Try channels in priority order, stopping at the first success:
379
+
380
+ ```typescript
381
+ import { withFallback } from '@classytic/notifications/utils';
382
+
383
+ // Try push first, fall back to SMS, then email
384
+ const result = await withFallback(service, payload, ['push', 'sms', 'email'], {
385
+ onFallback: (failed, error, next) => {
386
+ console.log(`${failed} failed (${error}), trying ${next}`);
387
+ },
388
+ });
389
+ ```
390
+
391
+ Works with both direct and queued delivery. In queue mode, the first accepted enqueue stops the fallback (no duplicate jobs).
392
+
393
+ ## Status Webhook Handler
394
+
395
+ Ingest delivery status updates from providers (Twilio, SES, SendGrid, FCM):
396
+
397
+ ```typescript
398
+ import { createStatusHandler } from '@classytic/notifications/utils';
399
+
400
+ const handler = createStatusHandler({
401
+ onStatusChange: async (update) => {
402
+ // Persist to your DB, metrics, delivery log, etc.
403
+ await db.notificationStatuses.insert(update);
404
+ },
405
+ });
406
+
407
+ // In your Express/Fastify route:
408
+ app.post('/webhooks/twilio', (req, res) => {
409
+ handler.handle({
410
+ provider: 'twilio',
411
+ notificationId: req.body.MessageSid,
412
+ channel: 'sms',
413
+ status: mapTwilioStatus(req.body.MessageStatus), // from examples/providers.ts
414
+ timestamp: new Date(),
415
+ rawPayload: req.body,
416
+ });
417
+ res.sendStatus(200);
418
+ });
419
+ ```
420
+
421
+ **Delivery statuses:** `queued` | `accepted` | `sent` | `delivered` | `undelivered` | `bounced` | `opened` | `clicked` | `complained` | `unsubscribed`
422
+
423
+ ## Templates
424
+
425
+ ### Built-in Simple Resolver
426
+
427
+ Zero-dependency `${var}` interpolation with nested access:
428
+
429
+ ```typescript
430
+ import { createSimpleResolver } from '@classytic/notifications/utils';
431
+
432
+ const service = new NotificationService({
433
+ templates: createSimpleResolver({
434
+ welcome: {
435
+ subject: 'Welcome, ${name}!',
436
+ html: '<h1>Hi ${name}</h1><p>From ${company}.</p>',
437
+ },
438
+ 'order-confirmation': {
439
+ subject: 'Order #${orderId} confirmed',
440
+ html: '<p>Hi ${user.name}, your ${total} order is confirmed.</p>',
441
+ },
442
+ }),
443
+ });
444
+ ```
445
+
446
+ ### Custom Template Engine
447
+
448
+ Plug any engine via the `TemplateResolver` interface:
449
+
450
+ ```typescript
451
+ // React Email
452
+ import { render } from '@react-email/render';
453
+ import WelcomeEmail from './emails/welcome';
454
+
455
+ const service = new NotificationService({
456
+ templates: async (id, data) => {
457
+ if (id === 'welcome') {
458
+ return { subject: `Welcome ${data.name}!`, html: render(WelcomeEmail(data)) };
459
+ }
460
+ throw new Error(`Unknown template: ${id}`);
461
+ },
462
+ });
463
+ ```
464
+
465
+ ## User Preferences
466
+
467
+ Filter channels per-user with a preference resolver:
468
+
469
+ ```typescript
470
+ const notifications = new NotificationService({
471
+ preferences: async (recipientId, event) => {
472
+ const prefs = await db.getUserPrefs(recipientId);
473
+ return {
474
+ channels: { email: true, sms: false }, // opt-out of SMS
475
+ events: { 'marketing.promo': false }, // opt-out of promos
476
+ quiet: {
477
+ start: '22:00',
478
+ end: '07:00',
479
+ timezone: 'America/New_York',
480
+ },
481
+ };
482
+ },
483
+ });
484
+ ```
485
+
486
+ ## Idempotency / Deduplication
487
+
488
+ Prevent duplicate notifications with idempotency keys:
489
+
490
+ ```typescript
491
+ const notifications = new NotificationService({
492
+ channels: [...],
493
+ idempotency: {}, // uses MemoryIdempotencyStore, 24h TTL
494
+ });
495
+
496
+ await notifications.send({
497
+ event: 'order.completed',
498
+ recipient: { email: 'user@example.com' },
499
+ data: { orderId: '123' },
500
+ idempotencyKey: 'order-completed-123', // duplicate sends are skipped
501
+ });
502
+ ```
503
+
504
+ For distributed systems, implement `IdempotencyStore` with Redis:
505
+
506
+ ```typescript
507
+ import type { IdempotencyStore } from '@classytic/notifications/utils';
508
+
509
+ class RedisIdempotencyStore implements IdempotencyStore {
510
+ async has(key: string): Promise<boolean> {
511
+ return !!(await redis.exists(`idemp:${key}`));
512
+ }
513
+ async set(key: string, ttlMs: number): Promise<void> {
514
+ await redis.set(`idemp:${key}`, '1', 'PX', ttlMs);
515
+ }
516
+ }
517
+ ```
518
+
519
+ ## Batch Sending
520
+
521
+ Send thousands of notifications with controlled concurrency:
522
+
523
+ ```typescript
524
+ const batch = await notifications.sendBatch(payloads, {
525
+ concurrency: 20,
526
+ onProgress: ({ completed, total }) => console.log(`${completed}/${total}`),
527
+ });
528
+
529
+ console.log(`Sent: ${batch.sent}, Failed: ${batch.failed}, Skipped: ${batch.skipped}`);
530
+ ```
531
+
532
+ ## Retry + Backoff
533
+
534
+ ```typescript
535
+ const notifications = new NotificationService({
536
+ retry: {
537
+ maxAttempts: 3, // default: 1 (no retry)
538
+ backoff: 'exponential', // 'exponential' | 'linear' | 'fixed'
539
+ initialDelay: 500, // ms, default: 500
540
+ maxDelay: 30_000, // ms, default: 30000
541
+ },
542
+ });
543
+ ```
544
+
545
+ Jitter (+-25%) is applied automatically to prevent thundering herd. Per-channel overrides are supported.
546
+
547
+ ## Lifecycle Events
548
+
549
+ ```typescript
550
+ notifications.on('before:send', (payload) => { /* validation, rate limiting */ });
551
+ notifications.on('after:send', (result) => { /* always fires, even for skipped */ });
552
+ notifications.on('send:success', (result) => { /* at least one channel sent */ });
553
+ notifications.on('send:failed', (result) => { /* at least one channel failed */ });
554
+ notifications.on('send:retry', ({ channel, attempt, error }) => { /* ... */ });
555
+ notifications.on('send:rate_limited', ({ channel, event }) => { /* ... */ });
556
+ notifications.on('send:queued', ({ jobId, payload }) => { /* ... */ });
557
+ ```
558
+
559
+ ## Hook Factories
560
+
561
+ Generate event handlers for any hook/event system:
562
+
563
+ ```typescript
564
+ const hooks = notifications.createHooks([
565
+ {
566
+ event: 'user.created',
567
+ getRecipient: (user) => ({ email: user.email, name: user.name }),
568
+ getData: (user) => ({ name: user.name }),
569
+ template: 'welcome',
570
+ },
571
+ ]);
572
+
573
+ // With EventEmitter
574
+ emitter.on('user.created', hooks['user.created'][0]);
575
+ ```
576
+
577
+ ## API Reference
578
+
579
+ ### `NotificationService`
580
+
581
+ | Method | Description |
582
+ |--------|-------------|
583
+ | `send(payload)` | Send notification to all matching channels |
584
+ | `sendBatch(payloads, options?)` | Send multiple notifications with concurrency control |
585
+ | `addChannel(channel)` | Register a channel at runtime |
586
+ | `removeChannel(name)` | Remove a channel by name |
587
+ | `getChannel(name)` | Get a channel by name |
588
+ | `getChannelNames()` | List all registered channel names |
589
+ | `getDeliveryLog()` | Get the delivery log instance |
590
+ | `createHooks(configs)` | Create event-specific hook handlers |
591
+ | `on(event, handler)` | Listen to lifecycle events |
592
+ | `off(event, handler)` | Remove a lifecycle listener |
593
+
594
+ ### Pluggable Interfaces
595
+
596
+ | Interface | Purpose | Built-in |
597
+ |-----------|---------|----------|
598
+ | `SmsProvider` | SMS delivery | — (BYOP) |
599
+ | `PushProvider` | Push notification delivery | — (BYOP) |
600
+ | `TemplateResolver` | Template rendering | `createSimpleResolver()` |
601
+ | `RateLimitStore` | Rate limit state | `MemoryRateLimitStore` |
602
+ | `DeliveryLog` | Audit trail | `MemoryDeliveryLog` |
603
+ | `QueueAdapter` | Crash-resilient queue | `MemoryQueue` |
604
+ | `IdempotencyStore` | Deduplication | `MemoryIdempotencyStore` |
605
+ | `PreferenceResolver` | User preference filtering | — (BYOP) |
606
+
607
+ ### Exports
608
+
609
+ ```typescript
610
+ // Core
611
+ import { NotificationService } from '@classytic/notifications';
612
+
613
+ // Channels
614
+ import {
615
+ BaseChannel, EmailChannel, WebhookChannel,
616
+ ConsoleChannel, SmsChannel, PushChannel,
617
+ } from '@classytic/notifications/channels';
618
+
619
+ // Utilities
620
+ import {
621
+ createSimpleResolver, withFallback, createStatusHandler,
622
+ MemoryDeliveryLog, MemoryRateLimitStore, MemoryQueue,
623
+ MemoryIdempotencyStore, mergeHooks, pMap,
624
+ withRetry, Emitter, isQuietHours,
625
+ NotificationError, ChannelError, ProviderNotInstalledError,
626
+ } from '@classytic/notifications/utils';
627
+
628
+ // Types
629
+ import type {
630
+ SmsProvider, PushProvider, DeliveryLog, DeliveryStatus,
631
+ StatusUpdate, StatusHandler, RateLimitStore, FallbackOptions,
632
+ QueueAdapter, IdempotencyStore, TemplateResolver,
633
+ Channel, ChannelConfig, NotificationPayload, SendResult,
634
+ DispatchResult, BatchOptions, BatchResult,
635
+ } from '@classytic/notifications';
636
+ ```
637
+
638
+ ## License
639
+
640
+ MIT