@classytic/notifications 1.2.0 → 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
@@ -2,20 +2,21 @@
2
2
 
3
3
  > Multi-channel notification system for TypeScript/Node.js
4
4
 
5
- Pluggable channels, templates, retry with backoff, and user preferences. Zero required dependencies — bring your own providers.
5
+ Pluggable channels, templates, retry with backoff, rate limiting, delivery tracking, and user preferences. Zero required dependencies — bring your own providers.
6
6
 
7
7
  ## Features
8
8
 
9
- - **Multi-Channel** — Email (Nodemailer — Gmail, SES, SMTP, any transport), Webhook, Console, or build your own
10
- - **Zero Required Deps** — Nodemailer is an optional peer dependency, loaded lazily
11
- - **Templates** — Plug any template engine (React Email, MJML, Handlebars, etc.)
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.)
12
15
  - **Retry + Backoff** — Exponential, linear, or fixed backoff with jitter. Per-channel overrides
13
16
  - **User Preferences** — Per-user, per-event, per-channel opt-in/out with quiet hours
14
- - **Quiet Hours** — Timezone-aware quiet period enforcement (no external deps)
15
17
  - **Idempotency** — Built-in deduplication with pluggable stores (memory, Redis, DB)
16
- - **Lifecycle Events** — `before:send`, `after:send`, `send:success`, `send:failed`, `send:retry`
18
+ - **Lifecycle Events** — `before:send`, `after:send`, `send:success`, `send:failed`, `send:retry`, `send:rate_limited`, `send:queued`
17
19
  - **Hook Factories** — Generate event handlers for EventEmitter, MongoKit, or any hook system
18
- - **Webhook Signing** — HMAC-SHA256 payload signing out of the box
19
20
  - **TypeScript** — Full type definitions, ESM-only
20
21
 
21
22
  ## Installation
@@ -34,30 +35,48 @@ npm install nodemailer
34
35
 
35
36
  ```typescript
36
37
  import { NotificationService } from '@classytic/notifications';
37
- import { EmailChannel, WebhookChannel, ConsoleChannel } from '@classytic/notifications/channels';
38
+ import { EmailChannel, SmsChannel, PushChannel, ConsoleChannel } from '@classytic/notifications/channels';
39
+ import { MemoryDeliveryLog, createSimpleResolver } from '@classytic/notifications/utils';
38
40
 
39
41
  const notifications = new NotificationService({
40
42
  channels: [
41
43
  new EmailChannel({
42
44
  from: 'App <noreply@app.com>',
43
45
  transport: { host: 'smtp.gmail.com', port: 587, auth: { user, pass } },
46
+ rateLimit: { maxPerWindow: 500, windowMs: 86_400_000 }, // Gmail 500/day
44
47
  }),
45
- new WebhookChannel({
46
- url: 'https://hooks.slack.com/services/...',
47
- events: ['order.*'],
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
+ },
48
64
  }),
49
65
  new ConsoleChannel(), // dev/testing
50
66
  ],
51
- templates: async (id, data) => ({
52
- subject: `Notification: ${id}`,
53
- html: `<p>${JSON.stringify(data)}</p>`,
67
+ templates: createSimpleResolver({
68
+ welcome: {
69
+ subject: 'Welcome, ${name}!',
70
+ html: '<h1>Hi ${name}</h1><p>Thanks for joining.</p>',
71
+ },
54
72
  }),
55
73
  retry: { maxAttempts: 3, backoff: 'exponential' },
74
+ deliveryLog: new MemoryDeliveryLog(),
56
75
  });
57
76
 
58
77
  await notifications.send({
59
78
  event: 'user.created',
60
- recipient: { email: 'user@example.com', name: 'John' },
79
+ recipient: { email: 'user@example.com', phone: '+15559876543', name: 'John' },
61
80
  data: { name: 'John' },
62
81
  template: 'welcome',
63
82
  });
@@ -65,9 +84,7 @@ await notifications.send({
65
84
 
66
85
  ## Channels
67
86
 
68
- ### Built-in Channels
69
-
70
- #### EmailChannel (Nodemailer)
87
+ ### EmailChannel (Nodemailer)
71
88
 
72
89
  Requires: `npm install nodemailer`
73
90
 
@@ -78,6 +95,7 @@ import { EmailChannel } from '@classytic/notifications/channels';
78
95
  const email = new EmailChannel({
79
96
  from: 'App <noreply@app.com>',
80
97
  transport: { host: 'smtp.gmail.com', port: 587, auth: { user, pass } },
98
+ rateLimit: { maxPerWindow: 500, windowMs: 86_400_000 }, // Gmail 500/day
81
99
  });
82
100
 
83
101
  // Gmail shorthand
@@ -94,7 +112,83 @@ const email = new EmailChannel({
94
112
  });
95
113
  ```
96
114
 
97
- #### WebhookChannel
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
98
192
 
99
193
  Zero dependencies — uses native `fetch`.
100
194
 
@@ -115,7 +209,7 @@ const signed = new WebhookChannel({
115
209
  });
116
210
  ```
117
211
 
118
- #### ConsoleChannel
212
+ ### ConsoleChannel
119
213
 
120
214
  Logs to console. Useful for development and testing.
121
215
 
@@ -155,68 +249,218 @@ class SlackChannel extends BaseChannel<SlackConfig> {
155
249
  }
156
250
  ```
157
251
 
158
- ### Event Filtering
252
+ ## Rate Limiting
159
253
 
160
- Channels only receive events matching their `events` whitelist. Supports wildcards:
254
+ Prevent exceeding provider limits with per-channel rate limiting:
161
255
 
162
256
  ```typescript
163
- new WebhookChannel({
164
- url: '...',
165
- events: ['order.*'], // matches order.created, order.completed, etc.
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
+ },
166
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';
167
271
 
168
- new ConsoleChannel({
169
- events: [], // empty = all events (default)
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(),
170
283
  });
171
284
  ```
172
285
 
173
- ### Per-Channel Retry Override
286
+ ## Delivery Tracking
174
287
 
175
- Channels can override the global retry config, including disabling retry:
288
+ Every notification attempt — sent, skipped, or failed — is logged:
176
289
 
177
290
  ```typescript
178
- const notifications = new NotificationService({
179
- retry: { maxAttempts: 3, backoff: 'exponential' }, // global default
180
- channels: [
181
- new EmailChannel({
182
- from: 'noreply@app.com',
183
- transport: { ... },
184
- retry: { maxAttempts: 5 }, // more retries for email
185
- }),
186
- new WebhookChannel({
187
- url: '...',
188
- retry: { maxAttempts: 1 }, // disable retry for webhooks
189
- }),
190
- ],
291
+ import { MemoryDeliveryLog } from '@classytic/notifications/utils';
292
+
293
+ const log = new MemoryDeliveryLog();
294
+ const service = new NotificationService({
295
+ channels: [...],
296
+ deliveryLog: log,
191
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);
192
310
  ```
193
311
 
194
- ## Templates
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
+ ```
195
323
 
196
- Plug any template engine via a resolver function:
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:
197
327
 
198
328
  ```typescript
199
- const notifications = new NotificationService({
200
- templates: async (templateId, data) => {
201
- const templates: Record<string, { subject: string; html: string }> = {
202
- welcome: {
203
- subject: `Welcome ${data.name}!`,
204
- html: `<h1>Hello ${data.name}</h1>`,
205
- },
206
- };
207
- return templates[templateId] ?? { subject: templateId, text: JSON.stringify(data) };
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}`);
208
387
  },
209
388
  });
389
+ ```
210
390
 
211
- await notifications.send({
212
- event: 'user.created',
213
- recipient: { email: 'user@example.com' },
214
- data: { name: 'John' },
215
- template: 'welcome', // resolved before sending
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
+ }),
216
443
  });
217
444
  ```
218
445
 
219
- Template values are merged into `payload.data`, with template values taking precedence.
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
+ ```
220
464
 
221
465
  ## User Preferences
222
466
 
@@ -229,7 +473,7 @@ const notifications = new NotificationService({
229
473
  return {
230
474
  channels: { email: true, sms: false }, // opt-out of SMS
231
475
  events: { 'marketing.promo': false }, // opt-out of promos
232
- quiet: { // quiet hours
476
+ quiet: {
233
477
  start: '22:00',
234
478
  end: '07:00',
235
479
  timezone: 'America/New_York',
@@ -239,67 +483,27 @@ const notifications = new NotificationService({
239
483
  });
240
484
  ```
241
485
 
242
- ### Quiet Hours
243
-
244
- Notifications are automatically skipped when the recipient is in their quiet period. Times use `HH:MM` format, timezone uses IANA names. Overnight ranges (e.g. 22:00–07:00) are supported.
245
-
246
- ```typescript
247
- // Quiet hours are returned from the preference resolver
248
- preferences: async (recipientId) => ({
249
- quiet: {
250
- start: '22:00', // inclusive
251
- end: '07:00', // exclusive
252
- timezone: 'Asia/Dhaka', // IANA timezone (defaults to UTC)
253
- },
254
- });
255
-
256
- // You can also use the utility directly
257
- import { isQuietHours } from '@classytic/notifications/utils';
258
-
259
- if (isQuietHours({ start: '22:00', end: '07:00', timezone: 'Asia/Dhaka' })) {
260
- console.log('Shhh!');
261
- }
262
- ```
263
-
264
486
  ## Idempotency / Deduplication
265
487
 
266
- Prevent duplicate notifications by providing an `idempotencyKey` on the payload. The key is only recorded after at least one channel succeeds.
488
+ Prevent duplicate notifications with idempotency keys:
267
489
 
268
490
  ```typescript
269
491
  const notifications = new NotificationService({
270
- channels: [new EmailChannel({ ... })],
271
- idempotency: {}, // uses MemoryIdempotencyStore, 24h TTL
272
- });
273
-
274
- await notifications.send({
275
- event: 'order.completed',
276
- recipient: { email: 'user@example.com' },
277
- data: { orderId: '123' },
278
- idempotencyKey: 'order-completed-123', // duplicate sends are skipped
492
+ channels: [...],
493
+ idempotency: {}, // uses MemoryIdempotencyStore, 24h TTL
279
494
  });
280
495
 
281
- // Second send with same key → skipped (sent: 0, skipped: 1)
282
496
  await notifications.send({
283
497
  event: 'order.completed',
284
498
  recipient: { email: 'user@example.com' },
285
499
  data: { orderId: '123' },
286
- idempotencyKey: 'order-completed-123',
500
+ idempotencyKey: 'order-completed-123', // duplicate sends are skipped
287
501
  });
288
502
  ```
289
503
 
290
- ### Custom Store + TTL
504
+ For distributed systems, implement `IdempotencyStore` with Redis:
291
505
 
292
506
  ```typescript
293
- import { MemoryIdempotencyStore } from '@classytic/notifications/utils';
294
-
295
- // Custom TTL (1 hour)
296
- const notifications = new NotificationService({
297
- idempotency: {
298
- ttl: 60 * 60 * 1000, // 1 hour in ms (default: 24h)
299
- },
300
- });
301
-
302
- // Custom store (e.g. Redis for distributed systems)
303
507
  import type { IdempotencyStore } from '@classytic/notifications/utils';
304
508
 
305
509
  class RedisIdempotencyStore implements IdempotencyStore {
@@ -310,51 +514,21 @@ class RedisIdempotencyStore implements IdempotencyStore {
310
514
  await redis.set(`idemp:${key}`, '1', 'PX', ttlMs);
311
515
  }
312
516
  }
313
-
314
- const notifications = new NotificationService({
315
- idempotency: { store: new RedisIdempotencyStore() },
316
- });
317
517
  ```
318
518
 
319
519
  ## Batch Sending
320
520
 
321
- Send thousands of notifications with controlled concurrency using a worker-pool pattern:
521
+ Send thousands of notifications with controlled concurrency:
322
522
 
323
523
  ```typescript
324
- const payloads = students.map(s => ({
325
- event: 'birthday',
326
- recipient: { id: s.id, email: s.email },
327
- data: { name: s.name },
328
- template: 'birthday',
329
- idempotencyKey: `birthday-${s.id}-2024`,
330
- }));
331
-
332
524
  const batch = await notifications.sendBatch(payloads, {
333
- concurrency: 20, // max parallel sends (default: 10)
334
- onProgress: ({ completed, total }) => {
335
- console.log(`${completed}/${total}`);
336
- },
525
+ concurrency: 20,
526
+ onProgress: ({ completed, total }) => console.log(`${completed}/${total}`),
337
527
  });
338
528
 
339
529
  console.log(`Sent: ${batch.sent}, Failed: ${batch.failed}, Skipped: ${batch.skipped}`);
340
530
  ```
341
531
 
342
- Each notification goes through the full `send()` pipeline (lifecycle events, templates, preferences, retry). Errors in individual notifications are caught and reported — they never abort the batch.
343
-
344
- ### Concurrency Utility
345
-
346
- The underlying `pMap` concurrency pool is exported for reuse:
347
-
348
- ```typescript
349
- import { pMap } from '@classytic/notifications/utils';
350
-
351
- const results = await pMap(
352
- urls,
353
- async (url) => fetch(url).then(r => r.json()),
354
- { concurrency: 5 },
355
- );
356
- ```
357
-
358
532
  ## Retry + Backoff
359
533
 
360
534
  ```typescript
@@ -368,32 +542,20 @@ const notifications = new NotificationService({
368
542
  });
369
543
  ```
370
544
 
371
- Jitter (+-25%) is applied automatically to prevent thundering herd.
545
+ Jitter (+-25%) is applied automatically to prevent thundering herd. Per-channel overrides are supported.
372
546
 
373
547
  ## Lifecycle Events
374
548
 
375
549
  ```typescript
376
- notifications.on('before:send', (payload) => {
377
- console.log('Sending:', payload.event);
378
- });
379
-
380
- notifications.on('after:send', (result) => {
381
- console.log(`Sent ${result.sent}/${result.results.length}`);
382
- });
383
-
384
- notifications.on('send:success', (result) => { /* ... */ });
385
- notifications.on('send:failed', (result) => { /* ... */ });
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 */ });
386
554
  notifications.on('send:retry', ({ channel, attempt, error }) => { /* ... */ });
387
-
388
- // Remove listener
389
- notifications.off('send:failed', handler);
555
+ notifications.on('send:rate_limited', ({ channel, event }) => { /* ... */ });
556
+ notifications.on('send:queued', ({ jobId, payload }) => { /* ... */ });
390
557
  ```
391
558
 
392
- **Lifecycle contract:**
393
- - `before:send` is **fail-fast** — a throwing listener aborts the send and propagates the error. Use this for validation or rate limiting.
394
- - `after:send`, `send:success`, `send:failed` are **safe** — listener errors are caught and logged, never masking the dispatch result.
395
- - `send:retry` errors are caught and logged.
396
-
397
559
  ## Hook Factories
398
560
 
399
561
  Generate event handlers for any hook/event system:
@@ -406,47 +568,10 @@ const hooks = notifications.createHooks([
406
568
  getData: (user) => ({ name: user.name }),
407
569
  template: 'welcome',
408
570
  },
409
- {
410
- event: 'order.completed',
411
- getRecipient: (order) => ({ email: order.customer.email }),
412
- getData: (order) => ({ orderId: order.id, total: order.total }),
413
- template: 'order-confirmation',
414
- channels: ['email'],
415
- },
416
571
  ]);
417
572
 
418
573
  // With EventEmitter
419
574
  emitter.on('user.created', hooks['user.created'][0]);
420
-
421
- // With MongoKit
422
- repo.on('after:create', hooks['user.created'][0]);
423
- ```
424
-
425
- Hooks are fire-and-forget: errors are logged but never thrown to avoid breaking the caller's flow.
426
-
427
- ### Merging Hooks
428
-
429
- Combine hooks from multiple sources:
430
-
431
- ```typescript
432
- import { mergeHooks } from '@classytic/notifications/utils';
433
-
434
- const combined = mergeHooks(
435
- notifications.createHooks(userHookConfigs),
436
- notifications.createHooks(orderHookConfigs),
437
- );
438
- ```
439
-
440
- ## Channel Management
441
-
442
- ```typescript
443
- // Add/remove channels at runtime
444
- notifications.addChannel(new ConsoleChannel());
445
- notifications.removeChannel('console');
446
-
447
- // Inspect registered channels
448
- notifications.getChannel('email'); // Channel | undefined
449
- notifications.getChannelNames(); // ['email', 'webhook']
450
575
  ```
451
576
 
452
577
  ## API Reference
@@ -461,13 +586,23 @@ notifications.getChannelNames(); // ['email', 'webhook']
461
586
  | `removeChannel(name)` | Remove a channel by name |
462
587
  | `getChannel(name)` | Get a channel by name |
463
588
  | `getChannelNames()` | List all registered channel names |
589
+ | `getDeliveryLog()` | Get the delivery log instance |
464
590
  | `createHooks(configs)` | Create event-specific hook handlers |
465
591
  | `on(event, handler)` | Listen to lifecycle events |
466
592
  | `off(event, handler)` | Remove a lifecycle listener |
467
593
 
468
- ### `BaseChannel<TConfig>`
594
+ ### Pluggable Interfaces
469
595
 
470
- Abstract base class for channels. Provides `shouldHandle(event)` with wildcard support.
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) |
471
606
 
472
607
  ### Exports
473
608
 
@@ -476,13 +611,28 @@ Abstract base class for channels. Provides `shouldHandle(event)` with wildcard s
476
611
  import { NotificationService } from '@classytic/notifications';
477
612
 
478
613
  // Channels
479
- import { BaseChannel, EmailChannel, WebhookChannel, ConsoleChannel } from '@classytic/notifications/channels';
614
+ import {
615
+ BaseChannel, EmailChannel, WebhookChannel,
616
+ ConsoleChannel, SmsChannel, PushChannel,
617
+ } from '@classytic/notifications/channels';
480
618
 
481
619
  // Utilities
482
- import { mergeHooks, withRetry, resolveRetryConfig, calculateDelay, Emitter } from '@classytic/notifications/utils';
483
- import { NotificationError, ChannelError, ProviderNotInstalledError } from '@classytic/notifications/utils';
484
- import { isQuietHours, MemoryIdempotencyStore, pMap } from '@classytic/notifications/utils';
485
- import type { IdempotencyStore, PMapOptions, QuietHoursConfig } from '@classytic/notifications/utils';
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';
486
636
  ```
487
637
 
488
638
  ## License