@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/CHANGELOG.md +70 -0
- package/README.md +640 -280
- package/dist/channels/index.d.mts +2 -0
- package/dist/channels/index.mjs +3 -0
- package/dist/errors-FYJYmfvj.mjs +36 -0
- package/dist/index.d.mts +136 -0
- package/dist/index.mjs +458 -0
- package/dist/push.channel-4mRkzrEu.d.mts +55 -0
- package/dist/push.channel-D1FdTPUi.mjs +468 -0
- package/dist/status-webhook-BDaI1BMy.d.mts +268 -0
- package/dist/status-webhook-XY42DCj_.mjs +582 -0
- package/dist/types-D94B3VNX.d.mts +546 -0
- package/dist/utils/index.d.mts +3 -0
- package/dist/utils/index.mjs +4 -0
- package/package.json +75 -57
- package/notifications.d.ts +0 -269
- package/src/core/channel.js +0 -71
- package/src/core/dispatcher.js +0 -73
- package/src/core/factory.js +0 -92
- package/src/index.js +0 -36
- package/src/utils/merge-hooks.js +0 -45
package/README.md
CHANGED
|
@@ -1,280 +1,640 @@
|
|
|
1
|
-
# @classytic/notifications
|
|
2
|
-
|
|
3
|
-
> Multi-channel notification system for
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
## Features
|
|
8
|
-
|
|
9
|
-
-
|
|
10
|
-
-
|
|
11
|
-
-
|
|
12
|
-
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
}
|
|
72
|
-
},
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
```
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
)
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
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
|