@classytic/notifications 0.0.1 → 1.2.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,490 @@
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, and user preferences. Zero required dependencies — bring your own providers.
6
+
7
+ ## Features
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.)
12
+ - **Retry + Backoff** — Exponential, linear, or fixed backoff with jitter. Per-channel overrides
13
+ - **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
+ - **Idempotency** — Built-in deduplication with pluggable stores (memory, Redis, DB)
16
+ - **Lifecycle Events** — `before:send`, `after:send`, `send:success`, `send:failed`, `send:retry`
17
+ - **Hook Factories** — Generate event handlers for EventEmitter, MongoKit, or any hook system
18
+ - **Webhook Signing** — HMAC-SHA256 payload signing out of the box
19
+ - **TypeScript** — Full type definitions, ESM-only
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ npm install @classytic/notifications
25
+ ```
26
+
27
+ **For EmailChannel** (optional — only if you use email):
28
+
29
+ ```bash
30
+ npm install nodemailer
31
+ ```
32
+
33
+ ## Quick Start
34
+
35
+ ```typescript
36
+ import { NotificationService } from '@classytic/notifications';
37
+ import { EmailChannel, WebhookChannel, ConsoleChannel } from '@classytic/notifications/channels';
38
+
39
+ const notifications = new NotificationService({
40
+ channels: [
41
+ new EmailChannel({
42
+ from: 'App <noreply@app.com>',
43
+ transport: { host: 'smtp.gmail.com', port: 587, auth: { user, pass } },
44
+ }),
45
+ new WebhookChannel({
46
+ url: 'https://hooks.slack.com/services/...',
47
+ events: ['order.*'],
48
+ }),
49
+ new ConsoleChannel(), // dev/testing
50
+ ],
51
+ templates: async (id, data) => ({
52
+ subject: `Notification: ${id}`,
53
+ html: `<p>${JSON.stringify(data)}</p>`,
54
+ }),
55
+ retry: { maxAttempts: 3, backoff: 'exponential' },
56
+ });
57
+
58
+ await notifications.send({
59
+ event: 'user.created',
60
+ recipient: { email: 'user@example.com', name: 'John' },
61
+ data: { name: 'John' },
62
+ template: 'welcome',
63
+ });
64
+ ```
65
+
66
+ ## Channels
67
+
68
+ ### Built-in Channels
69
+
70
+ #### EmailChannel (Nodemailer)
71
+
72
+ Requires: `npm install nodemailer`
73
+
74
+ ```typescript
75
+ import { EmailChannel } from '@classytic/notifications/channels';
76
+
77
+ // SMTP
78
+ const email = new EmailChannel({
79
+ from: 'App <noreply@app.com>',
80
+ transport: { host: 'smtp.gmail.com', port: 587, auth: { user, pass } },
81
+ });
82
+
83
+ // Gmail shorthand
84
+ const gmail = new EmailChannel({
85
+ from: 'noreply@app.com',
86
+ transport: { service: 'gmail', auth: { user, pass } },
87
+ });
88
+
89
+ // Pre-created transporter (SES, custom)
90
+ import nodemailer from 'nodemailer';
91
+ const email = new EmailChannel({
92
+ from: 'noreply@app.com',
93
+ transporter: nodemailer.createTransport({ /* SES config */ }),
94
+ });
95
+ ```
96
+
97
+ #### WebhookChannel
98
+
99
+ Zero dependencies — uses native `fetch`.
100
+
101
+ ```typescript
102
+ import { WebhookChannel } from '@classytic/notifications/channels';
103
+
104
+ const slack = new WebhookChannel({
105
+ url: 'https://hooks.slack.com/services/...',
106
+ events: ['order.completed', 'user.created'],
107
+ });
108
+
109
+ // With HMAC-SHA256 signing
110
+ const signed = new WebhookChannel({
111
+ url: 'https://api.partner.com/webhooks',
112
+ secret: process.env.WEBHOOK_SECRET!,
113
+ headers: { 'X-API-Key': process.env.PARTNER_KEY! },
114
+ timeout: 5000,
115
+ });
116
+ ```
117
+
118
+ #### ConsoleChannel
119
+
120
+ Logs to console. Useful for development and testing.
121
+
122
+ ```typescript
123
+ import { ConsoleChannel } from '@classytic/notifications/channels';
124
+
125
+ const dev = new ConsoleChannel();
126
+ const scoped = new ConsoleChannel({ events: ['user.*'] });
127
+ ```
128
+
129
+ ### Custom Channels
130
+
131
+ Extend `BaseChannel` or implement the `Channel` interface directly:
132
+
133
+ ```typescript
134
+ import { BaseChannel } from '@classytic/notifications/channels';
135
+ import type { NotificationPayload, SendResult, ChannelConfig } from '@classytic/notifications';
136
+
137
+ interface SlackConfig extends ChannelConfig {
138
+ webhookUrl: string;
139
+ }
140
+
141
+ class SlackChannel extends BaseChannel<SlackConfig> {
142
+ constructor(config: SlackConfig) {
143
+ super({ name: 'slack', ...config });
144
+ }
145
+
146
+ async send(payload: NotificationPayload): Promise<SendResult> {
147
+ const res = await fetch(this.config.webhookUrl, {
148
+ method: 'POST',
149
+ headers: { 'Content-Type': 'application/json' },
150
+ body: JSON.stringify({ text: String(payload.data.message) }),
151
+ });
152
+ if (!res.ok) return { status: 'failed', channel: this.name, error: res.statusText };
153
+ return { status: 'sent', channel: this.name };
154
+ }
155
+ }
156
+ ```
157
+
158
+ ### Event Filtering
159
+
160
+ Channels only receive events matching their `events` whitelist. Supports wildcards:
161
+
162
+ ```typescript
163
+ new WebhookChannel({
164
+ url: '...',
165
+ events: ['order.*'], // matches order.created, order.completed, etc.
166
+ });
167
+
168
+ new ConsoleChannel({
169
+ events: [], // empty = all events (default)
170
+ });
171
+ ```
172
+
173
+ ### Per-Channel Retry Override
174
+
175
+ Channels can override the global retry config, including disabling retry:
176
+
177
+ ```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
+ ],
191
+ });
192
+ ```
193
+
194
+ ## Templates
195
+
196
+ Plug any template engine via a resolver function:
197
+
198
+ ```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) };
208
+ },
209
+ });
210
+
211
+ await notifications.send({
212
+ event: 'user.created',
213
+ recipient: { email: 'user@example.com' },
214
+ data: { name: 'John' },
215
+ template: 'welcome', // resolved before sending
216
+ });
217
+ ```
218
+
219
+ Template values are merged into `payload.data`, with template values taking precedence.
220
+
221
+ ## User Preferences
222
+
223
+ Filter channels per-user with a preference resolver:
224
+
225
+ ```typescript
226
+ const notifications = new NotificationService({
227
+ preferences: async (recipientId, event) => {
228
+ const prefs = await db.getUserPrefs(recipientId);
229
+ return {
230
+ channels: { email: true, sms: false }, // opt-out of SMS
231
+ events: { 'marketing.promo': false }, // opt-out of promos
232
+ quiet: { // quiet hours
233
+ start: '22:00',
234
+ end: '07:00',
235
+ timezone: 'America/New_York',
236
+ },
237
+ };
238
+ },
239
+ });
240
+ ```
241
+
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
+ ## Idempotency / Deduplication
265
+
266
+ Prevent duplicate notifications by providing an `idempotencyKey` on the payload. The key is only recorded after at least one channel succeeds.
267
+
268
+ ```typescript
269
+ 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
279
+ });
280
+
281
+ // Second send with same key → skipped (sent: 0, skipped: 1)
282
+ await notifications.send({
283
+ event: 'order.completed',
284
+ recipient: { email: 'user@example.com' },
285
+ data: { orderId: '123' },
286
+ idempotencyKey: 'order-completed-123',
287
+ });
288
+ ```
289
+
290
+ ### Custom Store + TTL
291
+
292
+ ```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
+ import type { IdempotencyStore } from '@classytic/notifications/utils';
304
+
305
+ class RedisIdempotencyStore implements IdempotencyStore {
306
+ async has(key: string): Promise<boolean> {
307
+ return !!(await redis.exists(`idemp:${key}`));
308
+ }
309
+ async set(key: string, ttlMs: number): Promise<void> {
310
+ await redis.set(`idemp:${key}`, '1', 'PX', ttlMs);
311
+ }
312
+ }
313
+
314
+ const notifications = new NotificationService({
315
+ idempotency: { store: new RedisIdempotencyStore() },
316
+ });
317
+ ```
318
+
319
+ ## Batch Sending
320
+
321
+ Send thousands of notifications with controlled concurrency using a worker-pool pattern:
322
+
323
+ ```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
+ const batch = await notifications.sendBatch(payloads, {
333
+ concurrency: 20, // max parallel sends (default: 10)
334
+ onProgress: ({ completed, total }) => {
335
+ console.log(`${completed}/${total}`);
336
+ },
337
+ });
338
+
339
+ console.log(`Sent: ${batch.sent}, Failed: ${batch.failed}, Skipped: ${batch.skipped}`);
340
+ ```
341
+
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
+ ## Retry + Backoff
359
+
360
+ ```typescript
361
+ const notifications = new NotificationService({
362
+ retry: {
363
+ maxAttempts: 3, // default: 1 (no retry)
364
+ backoff: 'exponential', // 'exponential' | 'linear' | 'fixed'
365
+ initialDelay: 500, // ms, default: 500
366
+ maxDelay: 30_000, // ms, default: 30000
367
+ },
368
+ });
369
+ ```
370
+
371
+ Jitter (+-25%) is applied automatically to prevent thundering herd.
372
+
373
+ ## Lifecycle Events
374
+
375
+ ```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) => { /* ... */ });
386
+ notifications.on('send:retry', ({ channel, attempt, error }) => { /* ... */ });
387
+
388
+ // Remove listener
389
+ notifications.off('send:failed', handler);
390
+ ```
391
+
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
+ ## Hook Factories
398
+
399
+ Generate event handlers for any hook/event system:
400
+
401
+ ```typescript
402
+ const hooks = notifications.createHooks([
403
+ {
404
+ event: 'user.created',
405
+ getRecipient: (user) => ({ email: user.email, name: user.name }),
406
+ getData: (user) => ({ name: user.name }),
407
+ template: 'welcome',
408
+ },
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
+ ]);
417
+
418
+ // With EventEmitter
419
+ 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
+ ```
451
+
452
+ ## API Reference
453
+
454
+ ### `NotificationService`
455
+
456
+ | Method | Description |
457
+ |--------|-------------|
458
+ | `send(payload)` | Send notification to all matching channels |
459
+ | `sendBatch(payloads, options?)` | Send multiple notifications with concurrency control |
460
+ | `addChannel(channel)` | Register a channel at runtime |
461
+ | `removeChannel(name)` | Remove a channel by name |
462
+ | `getChannel(name)` | Get a channel by name |
463
+ | `getChannelNames()` | List all registered channel names |
464
+ | `createHooks(configs)` | Create event-specific hook handlers |
465
+ | `on(event, handler)` | Listen to lifecycle events |
466
+ | `off(event, handler)` | Remove a lifecycle listener |
467
+
468
+ ### `BaseChannel<TConfig>`
469
+
470
+ Abstract base class for channels. Provides `shouldHandle(event)` with wildcard support.
471
+
472
+ ### Exports
473
+
474
+ ```typescript
475
+ // Core
476
+ import { NotificationService } from '@classytic/notifications';
477
+
478
+ // Channels
479
+ import { BaseChannel, EmailChannel, WebhookChannel, ConsoleChannel } from '@classytic/notifications/channels';
480
+
481
+ // 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';
486
+ ```
487
+
488
+ ## License
489
+
490
+ MIT