@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.
@@ -0,0 +1,468 @@
1
+ import { r as ProviderNotInstalledError, t as ChannelError } from "./errors-FYJYmfvj.mjs";
2
+ import { createHmac } from "node:crypto";
3
+
4
+ //#region src/channels/BaseChannel.ts
5
+ var BaseChannel = class {
6
+ name;
7
+ config;
8
+ constructor(config) {
9
+ this.name = config.name ?? this.constructor.name;
10
+ this.config = config;
11
+ }
12
+ /** Check if this channel should handle a given event */
13
+ shouldHandle(event) {
14
+ if (this.config.enabled === false) return false;
15
+ const events = this.config.events;
16
+ if (!events || events.length === 0) return true;
17
+ return events.some((pattern) => {
18
+ if (pattern === event) return true;
19
+ if (pattern.endsWith(".*")) {
20
+ const prefix = pattern.slice(0, -2);
21
+ return event.startsWith(prefix + ".");
22
+ }
23
+ return false;
24
+ });
25
+ }
26
+ };
27
+
28
+ //#endregion
29
+ //#region src/channels/email.channel.ts
30
+ /**
31
+ * Email Channel (Nodemailer)
32
+ * @module @classytic/notifications
33
+ *
34
+ * Sends email notifications via Nodemailer.
35
+ * Supports any Nodemailer transport: SMTP, SES, Gmail, custom.
36
+ *
37
+ * Requires peer dependency: npm install nodemailer @types/nodemailer
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * import { EmailChannel } from '@classytic/notifications/channels';
42
+ *
43
+ * // Option 1: SMTP transport options
44
+ * const email = new EmailChannel({
45
+ * from: 'App <noreply@app.com>',
46
+ * transport: {
47
+ * host: 'smtp.gmail.com',
48
+ * port: 587,
49
+ * auth: { user: 'user@gmail.com', pass: 'app-password' },
50
+ * },
51
+ * });
52
+ *
53
+ * // Option 2: Gmail service shorthand
54
+ * const gmail = new EmailChannel({
55
+ * from: 'noreply@app.com',
56
+ * transport: { service: 'gmail', auth: { user: '...', pass: '...' } },
57
+ * });
58
+ *
59
+ * // Option 3: Pre-created transporter (SES, custom)
60
+ * import nodemailer from 'nodemailer';
61
+ * import aws from '@aws-sdk/client-ses';
62
+ * const ses = new aws.SES({ region: 'us-east-1' });
63
+ * const email = new EmailChannel({
64
+ * from: 'noreply@app.com',
65
+ * transporter: nodemailer.createTransport({ SES: { ses, aws } }),
66
+ * });
67
+ * ```
68
+ */
69
+ var EmailChannel = class EmailChannel extends BaseChannel {
70
+ transporter = null;
71
+ constructor(config) {
72
+ super({
73
+ name: "email",
74
+ ...config
75
+ });
76
+ }
77
+ /** Lazily initialize the Nodemailer transporter */
78
+ async getTransporter() {
79
+ if (this.transporter) return this.transporter;
80
+ if (this.config.transporter) {
81
+ this.transporter = this.config.transporter;
82
+ return this.transporter;
83
+ }
84
+ if (!this.config.transport) throw new ChannelError(this.name, "Either transport options or a transporter instance is required");
85
+ try {
86
+ this.transporter = (await import("nodemailer")).default.createTransport(this.config.transport);
87
+ return this.transporter;
88
+ } catch {
89
+ throw new ProviderNotInstalledError("nodemailer", "npm install nodemailer");
90
+ }
91
+ }
92
+ /** Fields that defaults must never override */
93
+ static PROTECTED_FIELDS = new Set([
94
+ "to",
95
+ "from",
96
+ "subject",
97
+ "html",
98
+ "text",
99
+ "cc",
100
+ "bcc",
101
+ "replyTo",
102
+ "attachments"
103
+ ]);
104
+ async send(payload) {
105
+ const { recipient, data } = payload;
106
+ if (!recipient.email) return {
107
+ status: "skipped",
108
+ channel: this.name,
109
+ error: "No recipient email"
110
+ };
111
+ const transporter = await this.getTransporter();
112
+ const safeDefaults = {};
113
+ if (this.config.defaults) {
114
+ for (const [key, value] of Object.entries(this.config.defaults)) if (!EmailChannel.PROTECTED_FIELDS.has(key)) safeDefaults[key] = value;
115
+ }
116
+ const mailOptions = {
117
+ ...safeDefaults,
118
+ from: data.from ?? this.config.from,
119
+ to: recipient.email,
120
+ subject: data.subject ?? ""
121
+ };
122
+ if (data.html) mailOptions.html = data.html;
123
+ if (data.text) mailOptions.text = data.text;
124
+ if (data.replyTo) mailOptions.replyTo = data.replyTo;
125
+ if (data.cc) mailOptions.cc = data.cc;
126
+ if (data.bcc) mailOptions.bcc = data.bcc;
127
+ if (data.attachments) mailOptions.attachments = data.attachments;
128
+ try {
129
+ const result = await transporter.sendMail(mailOptions);
130
+ return {
131
+ status: "sent",
132
+ channel: this.name,
133
+ metadata: { messageId: result.messageId }
134
+ };
135
+ } catch (err) {
136
+ const message = err instanceof Error ? err.message : String(err);
137
+ throw new ChannelError(this.name, message, err instanceof Error ? err : void 0);
138
+ }
139
+ }
140
+ /** Verify the SMTP connection (useful for health checks) */
141
+ async verify() {
142
+ const transporter = await this.getTransporter();
143
+ if (transporter.verify) return transporter.verify();
144
+ return true;
145
+ }
146
+ /** Close the transporter connection */
147
+ close() {
148
+ if (this.transporter?.close) this.transporter.close();
149
+ this.transporter = null;
150
+ }
151
+ };
152
+
153
+ //#endregion
154
+ //#region src/channels/webhook.channel.ts
155
+ /**
156
+ * Webhook Channel
157
+ * @module @classytic/notifications
158
+ *
159
+ * Sends notifications via HTTP POST/PUT to any URL.
160
+ * Supports HMAC-SHA256 payload signing for security.
161
+ * Zero dependencies - uses native fetch.
162
+ *
163
+ * @example
164
+ * ```typescript
165
+ * import { WebhookChannel } from '@classytic/notifications/channels';
166
+ *
167
+ * // Slack webhook
168
+ * const slack = new WebhookChannel({
169
+ * name: 'slack',
170
+ * url: 'https://hooks.slack.com/services/...',
171
+ * events: ['order.completed', 'user.created'],
172
+ * });
173
+ *
174
+ * // Signed webhook
175
+ * const hook = new WebhookChannel({
176
+ * url: 'https://api.partner.com/webhooks',
177
+ * secret: process.env.WEBHOOK_SECRET!,
178
+ * headers: { 'X-API-Key': process.env.PARTNER_KEY! },
179
+ * });
180
+ * ```
181
+ */
182
+ var WebhookChannel = class extends BaseChannel {
183
+ constructor(config) {
184
+ super({
185
+ name: "webhook",
186
+ ...config
187
+ });
188
+ }
189
+ async send(payload) {
190
+ const body = JSON.stringify({
191
+ event: payload.event,
192
+ recipient: payload.recipient,
193
+ data: payload.data,
194
+ metadata: payload.metadata,
195
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
196
+ });
197
+ const headers = {
198
+ "Content-Type": "application/json",
199
+ ...this.config.headers
200
+ };
201
+ if (this.config.secret) headers["X-Signature-256"] = `sha256=${createHmac("sha256", this.config.secret).update(body).digest("hex")}`;
202
+ try {
203
+ const response = await fetch(this.config.url, {
204
+ method: this.config.method ?? "POST",
205
+ headers,
206
+ body,
207
+ signal: AbortSignal.timeout(this.config.timeout ?? 1e4)
208
+ });
209
+ if (!response.ok) throw new ChannelError(this.name, `HTTP ${response.status}: ${response.statusText}`);
210
+ return {
211
+ status: "sent",
212
+ channel: this.name
213
+ };
214
+ } catch (err) {
215
+ if (err instanceof ChannelError) throw err;
216
+ const message = err instanceof Error ? err.message : String(err);
217
+ throw new ChannelError(this.name, message, err instanceof Error ? err : void 0);
218
+ }
219
+ }
220
+ };
221
+
222
+ //#endregion
223
+ //#region src/channels/console.channel.ts
224
+ /**
225
+ * Console Channel
226
+ * @module @classytic/notifications
227
+ *
228
+ * Logs notifications to the console. Useful for development and testing.
229
+ * Zero dependencies.
230
+ *
231
+ * @example
232
+ * ```typescript
233
+ * import { ConsoleChannel } from '@classytic/notifications/channels';
234
+ *
235
+ * const dev = new ConsoleChannel(); // logs all events
236
+ * const scoped = new ConsoleChannel({ events: ['user.*'] }); // only user events
237
+ * ```
238
+ */
239
+ var ConsoleChannel = class extends BaseChannel {
240
+ constructor(config = {}) {
241
+ super({
242
+ name: "console",
243
+ ...config
244
+ });
245
+ }
246
+ async send(payload) {
247
+ const output = {
248
+ event: payload.event,
249
+ recipient: payload.recipient,
250
+ data: payload.data,
251
+ template: payload.template,
252
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
253
+ };
254
+ console.log(`[notification] ${payload.event}`, JSON.stringify(output, null, 2));
255
+ return {
256
+ status: "sent",
257
+ channel: this.name
258
+ };
259
+ }
260
+ };
261
+
262
+ //#endregion
263
+ //#region src/channels/sms.channel.ts
264
+ /**
265
+ * SMS Channel
266
+ * @module @classytic/notifications
267
+ *
268
+ * Sends SMS notifications via any provider.
269
+ * Zero dependencies — bring your own SMS SDK.
270
+ *
271
+ * @example
272
+ * ```typescript
273
+ * import { SmsChannel } from '@classytic/notifications/channels';
274
+ *
275
+ * // Twilio (you manage the SDK)
276
+ * import twilio from 'twilio';
277
+ * const client = twilio(process.env.TWILIO_SID, process.env.TWILIO_TOKEN);
278
+ *
279
+ * const sms = new SmsChannel({
280
+ * from: '+15551234567',
281
+ * provider: {
282
+ * send: async ({ to, from, body }) => {
283
+ * const msg = await client.messages.create({ to, from, body });
284
+ * return { sid: msg.sid };
285
+ * },
286
+ * },
287
+ * });
288
+ *
289
+ * // AWS SNS
290
+ * import { SNSClient, PublishCommand } from '@aws-sdk/client-sns';
291
+ * const sns = new SNSClient({ region: 'us-east-1' });
292
+ *
293
+ * const snsSms = new SmsChannel({
294
+ * from: 'MyApp',
295
+ * provider: {
296
+ * send: async ({ to, body }) => {
297
+ * const res = await sns.send(new PublishCommand({
298
+ * PhoneNumber: to, Message: body,
299
+ * }));
300
+ * return { sid: res.MessageId ?? '' };
301
+ * },
302
+ * },
303
+ * });
304
+ *
305
+ * // Simple fetch-based (Vonage, MessageBird, etc.)
306
+ * const customSms = new SmsChannel({
307
+ * from: '+15551234567',
308
+ * provider: {
309
+ * send: async ({ to, from, body }) => {
310
+ * const res = await fetch('https://api.sms-provider.com/send', {
311
+ * method: 'POST',
312
+ * headers: { 'Content-Type': 'application/json', 'X-API-Key': '...' },
313
+ * body: JSON.stringify({ to, from, body }),
314
+ * });
315
+ * return { sid: await res.text() };
316
+ * },
317
+ * },
318
+ * });
319
+ * ```
320
+ */
321
+ var SmsChannel = class extends BaseChannel {
322
+ provider;
323
+ constructor(config) {
324
+ if (!config.provider) throw new ChannelError(config.name ?? "sms", "SmsChannel requires a provider. Pass any SMS SDK (Twilio, SNS, Vonage, etc.) via the provider option.");
325
+ super({
326
+ name: "sms",
327
+ ...config
328
+ });
329
+ this.provider = config.provider;
330
+ }
331
+ async send(payload) {
332
+ const { recipient, data } = payload;
333
+ if (!recipient.phone) return {
334
+ status: "skipped",
335
+ channel: this.name,
336
+ error: "No recipient phone number"
337
+ };
338
+ const body = data.text ?? data.message ?? data.subject ?? "";
339
+ if (!body) return {
340
+ status: "skipped",
341
+ channel: this.name,
342
+ error: "No message body (data.text, data.message, or data.subject)"
343
+ };
344
+ try {
345
+ const result = await this.provider.send({
346
+ to: recipient.phone,
347
+ from: data.from ?? this.config.from,
348
+ body
349
+ });
350
+ return {
351
+ status: "sent",
352
+ channel: this.name,
353
+ metadata: { sid: result.sid }
354
+ };
355
+ } catch (err) {
356
+ const message = err instanceof Error ? err.message : String(err);
357
+ throw new ChannelError(this.name, message, err instanceof Error ? err : void 0);
358
+ }
359
+ }
360
+ };
361
+
362
+ //#endregion
363
+ //#region src/channels/push.channel.ts
364
+ /**
365
+ * Push Notification Channel
366
+ * @module @classytic/notifications
367
+ *
368
+ * Sends push notifications via any provider: FCM, Expo, OneSignal, APNs, etc.
369
+ * Zero dependencies — bring your own push provider.
370
+ *
371
+ * @example
372
+ * ```typescript
373
+ * import { PushChannel } from '@classytic/notifications/channels';
374
+ *
375
+ * // FCM via Firebase Admin (you manage the SDK)
376
+ * import admin from 'firebase-admin';
377
+ * admin.initializeApp({ ... });
378
+ *
379
+ * const push = new PushChannel({
380
+ * provider: {
381
+ * send: async ({ token, title, body, data }) => {
382
+ * const result = await admin.messaging().send({
383
+ * token,
384
+ * notification: { title, body },
385
+ * data,
386
+ * });
387
+ * return { messageId: result };
388
+ * },
389
+ * },
390
+ * });
391
+ *
392
+ * // Expo Push
393
+ * import { Expo } from 'expo-server-sdk';
394
+ * const expo = new Expo();
395
+ *
396
+ * const expoPush = new PushChannel({
397
+ * name: 'expo-push',
398
+ * provider: {
399
+ * send: async ({ token, title, body, data }) => {
400
+ * const [receipt] = await expo.sendPushNotificationsAsync([
401
+ * { to: token, title, body, data },
402
+ * ]);
403
+ * return { messageId: receipt.id };
404
+ * },
405
+ * },
406
+ * });
407
+ *
408
+ * // Simple fetch-based (OneSignal, custom backend, etc.)
409
+ * const customPush = new PushChannel({
410
+ * provider: {
411
+ * send: async ({ token, title, body, data }) => {
412
+ * const res = await fetch('https://api.push-service.com/send', {
413
+ * method: 'POST',
414
+ * headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ...' },
415
+ * body: JSON.stringify({ token, title, body, data }),
416
+ * });
417
+ * return { messageId: await res.text() };
418
+ * },
419
+ * },
420
+ * });
421
+ * ```
422
+ */
423
+ var PushChannel = class extends BaseChannel {
424
+ provider;
425
+ constructor(config) {
426
+ if (!config.provider) throw new ChannelError(config.name ?? "push", "PushChannel requires a provider. Pass any push SDK (FCM, Expo, OneSignal, APNs) via the provider option.");
427
+ super({
428
+ name: "push",
429
+ ...config
430
+ });
431
+ this.provider = config.provider;
432
+ }
433
+ async send(payload) {
434
+ const { recipient, data } = payload;
435
+ if (!recipient.deviceToken) return {
436
+ status: "skipped",
437
+ channel: this.name,
438
+ error: "No recipient deviceToken"
439
+ };
440
+ const title = data.title ?? data.subject ?? "";
441
+ const body = data.body ?? data.text ?? data.message ?? "";
442
+ if (!title && !body) return {
443
+ status: "skipped",
444
+ channel: this.name,
445
+ error: "No title or body (data.title, data.body)"
446
+ };
447
+ try {
448
+ const result = await this.provider.send({
449
+ token: recipient.deviceToken,
450
+ title,
451
+ body,
452
+ data: data.pushData,
453
+ imageUrl: data.imageUrl
454
+ });
455
+ return {
456
+ status: "sent",
457
+ channel: this.name,
458
+ metadata: { messageId: result.messageId }
459
+ };
460
+ } catch (err) {
461
+ const message = err instanceof Error ? err.message : String(err);
462
+ throw new ChannelError(this.name, message, err instanceof Error ? err : void 0);
463
+ }
464
+ }
465
+ };
466
+
467
+ //#endregion
468
+ export { EmailChannel as a, WebhookChannel as i, SmsChannel as n, BaseChannel as o, ConsoleChannel as r, PushChannel as t };