@classytic/notifications 0.0.1
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/LICENSE +22 -0
- package/README.md +280 -0
- package/notifications.d.ts +269 -0
- package/package.json +82 -0
- package/src/core/channel.js +71 -0
- package/src/core/dispatcher.js +73 -0
- package/src/core/factory.js +92 -0
- package/src/index.js +36 -0
- package/src/utils/merge-hooks.js +45 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Classytic
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
package/README.md
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
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
|
+
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type definitions for @classytic/notifications
|
|
3
|
+
* Multi-channel notification system for event-driven applications
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
// ============ CORE TYPES ============
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Notification recipient information
|
|
10
|
+
*/
|
|
11
|
+
export interface NotificationRecipient {
|
|
12
|
+
/** Recipient ID */
|
|
13
|
+
id?: string | any;
|
|
14
|
+
/** Recipient email address */
|
|
15
|
+
email?: string;
|
|
16
|
+
/** Recipient phone number */
|
|
17
|
+
phone?: string;
|
|
18
|
+
/** Recipient name */
|
|
19
|
+
name?: string;
|
|
20
|
+
/** Additional recipient data */
|
|
21
|
+
[key: string]: any;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Notification data passed to channels
|
|
26
|
+
*/
|
|
27
|
+
export interface NotificationData {
|
|
28
|
+
/** Subject/title of notification */
|
|
29
|
+
subject?: string;
|
|
30
|
+
/** Message body */
|
|
31
|
+
message?: string;
|
|
32
|
+
/** Template ID or name */
|
|
33
|
+
template?: string;
|
|
34
|
+
/** Template variables */
|
|
35
|
+
templateData?: Record<string, any>;
|
|
36
|
+
/** Additional custom data */
|
|
37
|
+
[key: string]: any;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Notification object sent to channels
|
|
42
|
+
*/
|
|
43
|
+
export interface Notification {
|
|
44
|
+
/** Event name that triggered the notification */
|
|
45
|
+
event: string;
|
|
46
|
+
/** Recipient information */
|
|
47
|
+
recipient: NotificationRecipient;
|
|
48
|
+
/** Notification data */
|
|
49
|
+
data: NotificationData;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Notification send result
|
|
54
|
+
*/
|
|
55
|
+
export interface NotificationResult {
|
|
56
|
+
/** Send status */
|
|
57
|
+
status: 'sent' | 'skipped' | 'failed';
|
|
58
|
+
/** Channel name */
|
|
59
|
+
channel?: string;
|
|
60
|
+
/** Error message if failed */
|
|
61
|
+
error?: string;
|
|
62
|
+
/** Additional result data */
|
|
63
|
+
[key: string]: any;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Channel capabilities
|
|
68
|
+
*/
|
|
69
|
+
export interface ChannelCapabilities {
|
|
70
|
+
/** Supports batch sending */
|
|
71
|
+
supportsBatch: boolean;
|
|
72
|
+
/** Supports scheduled sending */
|
|
73
|
+
supportsScheduling: boolean;
|
|
74
|
+
/** Supports file attachments */
|
|
75
|
+
supportsAttachments: boolean;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ============ NOTIFICATION CHANNEL ============
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Notification channel configuration
|
|
82
|
+
*/
|
|
83
|
+
export interface NotificationChannelConfig {
|
|
84
|
+
/** Channel name */
|
|
85
|
+
name?: string;
|
|
86
|
+
/** Enable/disable channel */
|
|
87
|
+
enabled?: boolean;
|
|
88
|
+
/** Events this channel should handle (empty = all events) */
|
|
89
|
+
events?: string[];
|
|
90
|
+
/** Additional configuration */
|
|
91
|
+
[key: string]: any;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Notification Channel Base Class
|
|
96
|
+
* Abstract base class for all notification channels
|
|
97
|
+
*/
|
|
98
|
+
export class NotificationChannel {
|
|
99
|
+
/** Channel configuration */
|
|
100
|
+
config: NotificationChannelConfig;
|
|
101
|
+
/** Whether channel is enabled */
|
|
102
|
+
enabled: boolean;
|
|
103
|
+
/** Channel name */
|
|
104
|
+
name: string;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Create notification channel
|
|
108
|
+
* @param config Channel configuration
|
|
109
|
+
*/
|
|
110
|
+
constructor(config?: NotificationChannelConfig);
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Send notification (must be implemented by subclass)
|
|
114
|
+
* @param notification Notification to send
|
|
115
|
+
* @returns Send result
|
|
116
|
+
*/
|
|
117
|
+
send(notification: Notification): Promise<NotificationResult>;
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Get events this channel handles
|
|
121
|
+
* @returns Event names (empty array = handle all events)
|
|
122
|
+
*/
|
|
123
|
+
getSupportedEvents(): string[];
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Check if this channel should handle this event
|
|
127
|
+
* @param event Event name
|
|
128
|
+
* @returns True if channel should handle event
|
|
129
|
+
*/
|
|
130
|
+
shouldHandle(event: string): boolean;
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Get channel capabilities
|
|
134
|
+
* @returns Channel capabilities
|
|
135
|
+
*/
|
|
136
|
+
getCapabilities(): ChannelCapabilities;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ============ DISPATCHER ============
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Recipient resolver function
|
|
143
|
+
* Extracts recipient information from event data
|
|
144
|
+
*/
|
|
145
|
+
export type RecipientResolver = (eventData: any) => Promise<NotificationRecipient | null> | NotificationRecipient | null;
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Data extractor function
|
|
149
|
+
* Extracts notification data from event data
|
|
150
|
+
*/
|
|
151
|
+
export type DataExtractor = (eventData: any) => NotificationData;
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Dispatch result
|
|
155
|
+
*/
|
|
156
|
+
export interface DispatchResult {
|
|
157
|
+
/** Number of channels that successfully sent */
|
|
158
|
+
sent: number;
|
|
159
|
+
/** Number of channels that failed */
|
|
160
|
+
failed?: number;
|
|
161
|
+
/** Total channels attempted */
|
|
162
|
+
total?: number;
|
|
163
|
+
/** List of channel names */
|
|
164
|
+
channels?: string[];
|
|
165
|
+
/** Whether sending was skipped */
|
|
166
|
+
skipped?: boolean;
|
|
167
|
+
/** Reason for skip */
|
|
168
|
+
reason?: string;
|
|
169
|
+
/** Error message */
|
|
170
|
+
error?: string;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Notification dispatcher function
|
|
175
|
+
*/
|
|
176
|
+
export type Dispatcher = (
|
|
177
|
+
event: string,
|
|
178
|
+
eventData: any,
|
|
179
|
+
recipientResolver: RecipientResolver,
|
|
180
|
+
dataExtractor: DataExtractor
|
|
181
|
+
) => Promise<DispatchResult>;
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Create notification dispatcher
|
|
185
|
+
* Routes notifications to appropriate channels
|
|
186
|
+
* @param channels Registered notification channels
|
|
187
|
+
* @returns Dispatcher function
|
|
188
|
+
*/
|
|
189
|
+
export function createDispatcher(channels?: NotificationChannel[]): Dispatcher;
|
|
190
|
+
|
|
191
|
+
// ============ FACTORY ============
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Notification handler configuration
|
|
195
|
+
*/
|
|
196
|
+
export interface NotificationHandlerConfig {
|
|
197
|
+
/** Event name this handler responds to */
|
|
198
|
+
event: string;
|
|
199
|
+
/** Notification channels to use */
|
|
200
|
+
channels?: NotificationChannel[];
|
|
201
|
+
/** Function to extract recipient from event data */
|
|
202
|
+
getRecipient: RecipientResolver;
|
|
203
|
+
/** Function to extract template data from event data */
|
|
204
|
+
getTemplateData: DataExtractor;
|
|
205
|
+
/** Enable/disable this notification handler */
|
|
206
|
+
enabled?: boolean;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Notification handler function
|
|
211
|
+
*/
|
|
212
|
+
export type NotificationHandler = (eventData: any) => Promise<void>;
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Create notification handler for an event
|
|
216
|
+
* @param config Handler configuration
|
|
217
|
+
* @returns Async handler function
|
|
218
|
+
*/
|
|
219
|
+
export function createNotificationHandler(config: NotificationHandlerConfig): NotificationHandler;
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Map of event names to handler arrays
|
|
223
|
+
*/
|
|
224
|
+
export type NotificationHandlers = Record<string, NotificationHandler[]>;
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Create multiple notification handlers
|
|
228
|
+
* @param configs Array of handler configurations
|
|
229
|
+
* @param channels Registered notification channels
|
|
230
|
+
* @returns Map of event → handler arrays
|
|
231
|
+
*/
|
|
232
|
+
export function createNotificationHandlers(
|
|
233
|
+
configs: NotificationHandlerConfig[],
|
|
234
|
+
channels?: NotificationChannel[]
|
|
235
|
+
): NotificationHandlers;
|
|
236
|
+
|
|
237
|
+
// ============ UTILITIES ============
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Hook configuration object
|
|
241
|
+
* Maps event names to handler functions or arrays of handlers
|
|
242
|
+
*/
|
|
243
|
+
export type HookConfig = Record<string, NotificationHandler | NotificationHandler[]>;
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Merge multiple hook configurations
|
|
247
|
+
* Each event can have multiple handlers from different sources
|
|
248
|
+
* @param hookConfigs Hook configuration objects to merge
|
|
249
|
+
* @returns Merged hooks with all handlers combined
|
|
250
|
+
*
|
|
251
|
+
* @example
|
|
252
|
+
* const hooks = mergeHooks(
|
|
253
|
+
* { 'user.created': [handler1] },
|
|
254
|
+
* { 'user.created': [handler2], 'user.deleted': [handler3] }
|
|
255
|
+
* );
|
|
256
|
+
* // Result: { 'user.created': [handler1, handler2], 'user.deleted': [handler3] }
|
|
257
|
+
*/
|
|
258
|
+
export function mergeHooks(...hookConfigs: HookConfig[]): Record<string, NotificationHandler[]>;
|
|
259
|
+
|
|
260
|
+
// ============ DEFAULT EXPORT ============
|
|
261
|
+
|
|
262
|
+
declare const _default: {
|
|
263
|
+
NotificationChannel: typeof NotificationChannel;
|
|
264
|
+
createDispatcher: typeof createDispatcher;
|
|
265
|
+
createNotificationHandlers: typeof createNotificationHandlers;
|
|
266
|
+
mergeHooks: typeof mergeHooks;
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
export default _default;
|
package/package.json
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@classytic/notifications",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Multi-channel notification system for event-driven applications. Framework-agnostic with pluggable channels.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"types": "./notifications.d.ts",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"notifications",
|
|
10
|
+
"multi-channel",
|
|
11
|
+
"email",
|
|
12
|
+
"push",
|
|
13
|
+
"sms",
|
|
14
|
+
"in-app",
|
|
15
|
+
"event-driven",
|
|
16
|
+
"hooks",
|
|
17
|
+
"alerts",
|
|
18
|
+
"messaging",
|
|
19
|
+
"dispatcher",
|
|
20
|
+
"channels",
|
|
21
|
+
"pluggable",
|
|
22
|
+
"framework-agnostic",
|
|
23
|
+
"express",
|
|
24
|
+
"fastify",
|
|
25
|
+
"nestjs"
|
|
26
|
+
],
|
|
27
|
+
"author": "Classytic",
|
|
28
|
+
"license": "MIT",
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/classytic/notifications.git"
|
|
32
|
+
},
|
|
33
|
+
"bugs": {
|
|
34
|
+
"url": "https://github.com/classytic/notifications/issues"
|
|
35
|
+
},
|
|
36
|
+
"homepage": "https://github.com/classytic/notifications#readme",
|
|
37
|
+
"scripts": {
|
|
38
|
+
"test": "node --test tests/*.test.js",
|
|
39
|
+
"test:watch": "node --test --watch tests/*.test.js",
|
|
40
|
+
"prepublishOnly": "npm test && npm pack --dry-run",
|
|
41
|
+
"version:patch": "npm version patch",
|
|
42
|
+
"version:minor": "npm version minor",
|
|
43
|
+
"version:major": "npm version major",
|
|
44
|
+
"publish:npm": "npm publish --access public",
|
|
45
|
+
"release:patch": "npm run version:patch && npm run publish:npm",
|
|
46
|
+
"release:minor": "npm run version:minor && npm run publish:npm",
|
|
47
|
+
"release:major": "npm run version:major && npm run publish:npm"
|
|
48
|
+
},
|
|
49
|
+
"engines": {
|
|
50
|
+
"node": ">=18.0.0"
|
|
51
|
+
},
|
|
52
|
+
"exports": {
|
|
53
|
+
".": {
|
|
54
|
+
"types": "./notifications.d.ts",
|
|
55
|
+
"import": "./src/index.js"
|
|
56
|
+
},
|
|
57
|
+
"./core/channel": {
|
|
58
|
+
"import": "./src/core/channel.js"
|
|
59
|
+
},
|
|
60
|
+
"./core/dispatcher": {
|
|
61
|
+
"import": "./src/core/dispatcher.js"
|
|
62
|
+
},
|
|
63
|
+
"./core/factory": {
|
|
64
|
+
"import": "./src/core/factory.js"
|
|
65
|
+
},
|
|
66
|
+
"./utils/merge-hooks": {
|
|
67
|
+
"import": "./src/utils/merge-hooks.js"
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
"files": [
|
|
71
|
+
"src/**/*.js",
|
|
72
|
+
"!src/**/*.test.js",
|
|
73
|
+
"!src/**/*.spec.js",
|
|
74
|
+
"!src/**/__tests__/**",
|
|
75
|
+
"notifications.d.ts",
|
|
76
|
+
"README.md",
|
|
77
|
+
"LICENSE"
|
|
78
|
+
],
|
|
79
|
+
"peerDependencies": {},
|
|
80
|
+
"dependencies": {}
|
|
81
|
+
}
|
|
82
|
+
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Notification Channel Base Class
|
|
3
|
+
* @classytic/notifications
|
|
4
|
+
*
|
|
5
|
+
* Abstract base class for all notification channels
|
|
6
|
+
* Inspired by: AWS SNS, Twilio Notify, Firebase Cloud Messaging
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export class NotificationChannel {
|
|
10
|
+
constructor(config = {}) {
|
|
11
|
+
this.config = config;
|
|
12
|
+
this.enabled = config.enabled !== false;
|
|
13
|
+
this.name = config.name || this.constructor.name;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Send notification
|
|
18
|
+
* Must be implemented by subclass
|
|
19
|
+
*
|
|
20
|
+
* @param {Object} notification
|
|
21
|
+
* @param {string} notification.event - Event name
|
|
22
|
+
* @param {Object} notification.recipient - Recipient info
|
|
23
|
+
* @param {Object} notification.data - Notification data
|
|
24
|
+
* @returns {Promise<Object>} { status: 'sent' | 'skipped' | 'failed', ... }
|
|
25
|
+
*/
|
|
26
|
+
async send(notification) {
|
|
27
|
+
throw new Error(`${this.name}.send() must be implemented`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Get events this channel handles
|
|
32
|
+
* Return empty array to handle all events
|
|
33
|
+
*
|
|
34
|
+
* @returns {Array<string>} Event names
|
|
35
|
+
*/
|
|
36
|
+
getSupportedEvents() {
|
|
37
|
+
return this.config.events || [];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Check if this channel should handle this event
|
|
42
|
+
*
|
|
43
|
+
* @param {string} event - Event name
|
|
44
|
+
* @returns {boolean}
|
|
45
|
+
*/
|
|
46
|
+
shouldHandle(event) {
|
|
47
|
+
if (!this.enabled) return false;
|
|
48
|
+
|
|
49
|
+
const supported = this.getSupportedEvents();
|
|
50
|
+
|
|
51
|
+
// Empty array = handle all events
|
|
52
|
+
if (supported.length === 0) return true;
|
|
53
|
+
|
|
54
|
+
return supported.includes(event);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Get channel capabilities
|
|
59
|
+
* @returns {Object} Capabilities
|
|
60
|
+
*/
|
|
61
|
+
getCapabilities() {
|
|
62
|
+
return {
|
|
63
|
+
supportsBatch: false,
|
|
64
|
+
supportsScheduling: false,
|
|
65
|
+
supportsAttachments: false,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export default NotificationChannel;
|
|
71
|
+
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Notification Dispatcher
|
|
3
|
+
* @classytic/notifications
|
|
4
|
+
*
|
|
5
|
+
* Routes notifications to appropriate channels
|
|
6
|
+
* Pattern: Mediator + Chain of Responsibility
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Create notification dispatcher
|
|
11
|
+
*
|
|
12
|
+
* @param {Array<NotificationChannel>} channels - Registered channels
|
|
13
|
+
* @returns {Function} Async dispatcher function
|
|
14
|
+
*/
|
|
15
|
+
export function createDispatcher(channels = []) {
|
|
16
|
+
if (!Array.isArray(channels)) {
|
|
17
|
+
throw new Error('Channels must be an array');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
return async function dispatch(event, eventData, recipientResolver, dataExtractor) {
|
|
21
|
+
if (!channels.length) return { sent: 0, channels: [] };
|
|
22
|
+
|
|
23
|
+
try {
|
|
24
|
+
// 1. Resolve recipient
|
|
25
|
+
const recipient = await recipientResolver(eventData);
|
|
26
|
+
if (!recipient) {
|
|
27
|
+
return { sent: 0, skipped: true, reason: 'no_recipient' };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// 2. Extract notification data
|
|
31
|
+
const data = dataExtractor(eventData);
|
|
32
|
+
|
|
33
|
+
// 3. Filter channels that should handle this event
|
|
34
|
+
const activeChannels = channels.filter(channel => channel.shouldHandle(event));
|
|
35
|
+
|
|
36
|
+
if (!activeChannels.length) {
|
|
37
|
+
return { sent: 0, skipped: true, reason: 'no_active_channels' };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// 4. Send to all active channels (parallel)
|
|
41
|
+
const results = await Promise.allSettled(
|
|
42
|
+
activeChannels.map(channel =>
|
|
43
|
+
channel.send({
|
|
44
|
+
event,
|
|
45
|
+
recipient,
|
|
46
|
+
data,
|
|
47
|
+
}).catch(error => ({
|
|
48
|
+
status: 'failed',
|
|
49
|
+
channel: channel.name,
|
|
50
|
+
error: error.message,
|
|
51
|
+
}))
|
|
52
|
+
)
|
|
53
|
+
);
|
|
54
|
+
|
|
55
|
+
// 5. Collect results
|
|
56
|
+
const sent = results.filter(r => r.status === 'fulfilled' && r.value?.status === 'sent').length;
|
|
57
|
+
const failed = results.filter(r => r.status === 'rejected' || r.value?.status === 'failed').length;
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
sent,
|
|
61
|
+
failed,
|
|
62
|
+
total: activeChannels.length,
|
|
63
|
+
channels: activeChannels.map(c => c.name),
|
|
64
|
+
};
|
|
65
|
+
} catch (error) {
|
|
66
|
+
console.error(`[Dispatcher] Failed for ${event}:`, error.message);
|
|
67
|
+
return { sent: 0, failed: 1, error: error.message };
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export default createDispatcher;
|
|
73
|
+
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Notification Factory
|
|
3
|
+
* @classytic/notifications
|
|
4
|
+
*
|
|
5
|
+
* Creates notification handlers from configurations
|
|
6
|
+
* Pattern: Factory + Builder
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { createDispatcher } from './dispatcher.js';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Create notification handler for an event
|
|
13
|
+
*
|
|
14
|
+
* @param {Object} config
|
|
15
|
+
* @param {string} config.event - Event name
|
|
16
|
+
* @param {Array<NotificationChannel>} config.channels - Notification channels
|
|
17
|
+
* @param {Function} config.getRecipient - Extract recipient from event data
|
|
18
|
+
* @param {Function} config.getTemplateData - Extract data for templates
|
|
19
|
+
* @param {boolean} config.enabled - Enable/disable this notification
|
|
20
|
+
* @returns {Function} Async handler function
|
|
21
|
+
*/
|
|
22
|
+
export function createNotificationHandler(config) {
|
|
23
|
+
const {
|
|
24
|
+
event,
|
|
25
|
+
channels = [],
|
|
26
|
+
getRecipient,
|
|
27
|
+
getTemplateData,
|
|
28
|
+
enabled = true,
|
|
29
|
+
} = config;
|
|
30
|
+
|
|
31
|
+
if (!event) {
|
|
32
|
+
throw new Error('Event name is required');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (!getRecipient || typeof getRecipient !== 'function') {
|
|
36
|
+
throw new Error('getRecipient function is required');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (!getTemplateData || typeof getTemplateData !== 'function') {
|
|
40
|
+
throw new Error('getTemplateData function is required');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const dispatcher = createDispatcher(channels);
|
|
44
|
+
|
|
45
|
+
return async (eventData) => {
|
|
46
|
+
if (!enabled) return;
|
|
47
|
+
|
|
48
|
+
try {
|
|
49
|
+
await dispatcher(event, eventData, getRecipient, getTemplateData);
|
|
50
|
+
} catch (error) {
|
|
51
|
+
// Fire-and-forget: log but don't throw
|
|
52
|
+
console.error(`[Notification] ${event} failed:`, error.message);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Create multiple notification handlers
|
|
59
|
+
*
|
|
60
|
+
* @param {Array} configs - Notification configurations
|
|
61
|
+
* @param {Array<NotificationChannel>} channels - Registered channels
|
|
62
|
+
* @returns {Object} Map of event → [handlers]
|
|
63
|
+
*/
|
|
64
|
+
export function createNotificationHandlers(configs, channels = []) {
|
|
65
|
+
if (!Array.isArray(configs)) {
|
|
66
|
+
throw new Error('Configs must be an array');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const handlers = {};
|
|
70
|
+
|
|
71
|
+
configs.forEach(config => {
|
|
72
|
+
if (!config.event) {
|
|
73
|
+
throw new Error('Each config must have an event property');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (!handlers[config.event]) {
|
|
77
|
+
handlers[config.event] = [];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const handler = createNotificationHandler({
|
|
81
|
+
...config,
|
|
82
|
+
channels,
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
handlers[config.event].push(handler);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
return handlers;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export default { createNotificationHandler, createNotificationHandlers };
|
|
92
|
+
|
package/src/index.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @classytic/notifications
|
|
3
|
+
* Multi-Channel Notification System
|
|
4
|
+
*
|
|
5
|
+
* Framework-agnostic notification system with pluggable channels
|
|
6
|
+
* Works with any event system (hooks, EventEmitter, custom)
|
|
7
|
+
*
|
|
8
|
+
* @version 1.0.0
|
|
9
|
+
* @author Classytic
|
|
10
|
+
* @license MIT
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
// ============ CORE ============
|
|
14
|
+
export { NotificationChannel } from './core/channel.js';
|
|
15
|
+
export { createDispatcher } from './core/dispatcher.js';
|
|
16
|
+
export {
|
|
17
|
+
createNotificationHandler,
|
|
18
|
+
createNotificationHandlers
|
|
19
|
+
} from './core/factory.js';
|
|
20
|
+
|
|
21
|
+
// ============ UTILITIES ============
|
|
22
|
+
export { mergeHooks } from './utils/merge-hooks.js';
|
|
23
|
+
|
|
24
|
+
// ============ DEFAULT EXPORT ============
|
|
25
|
+
import { NotificationChannel as _NotificationChannel } from './core/channel.js';
|
|
26
|
+
import { createDispatcher as _createDispatcher } from './core/dispatcher.js';
|
|
27
|
+
import { createNotificationHandlers as _createNotificationHandlers } from './core/factory.js';
|
|
28
|
+
import { mergeHooks as _mergeHooks } from './utils/merge-hooks.js';
|
|
29
|
+
|
|
30
|
+
export default {
|
|
31
|
+
NotificationChannel: _NotificationChannel,
|
|
32
|
+
createDispatcher: _createDispatcher,
|
|
33
|
+
createNotificationHandlers: _createNotificationHandlers,
|
|
34
|
+
mergeHooks: _mergeHooks,
|
|
35
|
+
};
|
|
36
|
+
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hook Merging Utility
|
|
3
|
+
* @classytic/notifications
|
|
4
|
+
*
|
|
5
|
+
* Merges multiple hook configurations into single object
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Merge multiple hook configurations
|
|
10
|
+
* Each event can have multiple handlers from different sources
|
|
11
|
+
*
|
|
12
|
+
* @param {...Object} hookConfigs - Hook configuration objects
|
|
13
|
+
* @returns {Object} Merged hooks
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* const hooks = mergeHooks(
|
|
17
|
+
* { 'user.created': [handler1] },
|
|
18
|
+
* { 'user.created': [handler2], 'user.deleted': [handler3] }
|
|
19
|
+
* );
|
|
20
|
+
* // Result: { 'user.created': [handler1, handler2], 'user.deleted': [handler3] }
|
|
21
|
+
*/
|
|
22
|
+
export function mergeHooks(...hookConfigs) {
|
|
23
|
+
const merged = {};
|
|
24
|
+
|
|
25
|
+
hookConfigs.forEach(config => {
|
|
26
|
+
if (!config || typeof config !== 'object') {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
Object.entries(config).forEach(([event, handlers]) => {
|
|
31
|
+
if (!merged[event]) {
|
|
32
|
+
merged[event] = [];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Ensure handlers is an array
|
|
36
|
+
const handlerArray = Array.isArray(handlers) ? handlers : [handlers];
|
|
37
|
+
merged[event].push(...handlerArray);
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
return merged;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export default mergeHooks;
|
|
45
|
+
|