@classytic/notifications 1.2.0 → 2.1.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,519 @@
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
+ /**
105
+ * Pre-flight check called by the service before consuming a rate-limit
106
+ * token. Returning a skip result here avoids burning quota on payloads
107
+ * that obviously can't deliver (e.g., a mixed-channel batch where the
108
+ * recipient has a phone but no email).
109
+ */
110
+ canSend(payload) {
111
+ if (!payload.recipient.email) return {
112
+ status: "skipped",
113
+ channel: this.name,
114
+ error: "No recipient email"
115
+ };
116
+ return null;
117
+ }
118
+ async send(payload) {
119
+ const { recipient, data } = payload;
120
+ if (!recipient.email) return {
121
+ status: "skipped",
122
+ channel: this.name,
123
+ error: "No recipient email"
124
+ };
125
+ const transporter = await this.getTransporter();
126
+ const safeDefaults = {};
127
+ if (this.config.defaults) {
128
+ for (const [key, value] of Object.entries(this.config.defaults)) if (!EmailChannel.PROTECTED_FIELDS.has(key)) safeDefaults[key] = value;
129
+ }
130
+ const mailOptions = {
131
+ ...safeDefaults,
132
+ from: data.from ?? this.config.from,
133
+ to: recipient.email,
134
+ subject: data.subject ?? ""
135
+ };
136
+ if (data.html) mailOptions.html = data.html;
137
+ if (data.text) mailOptions.text = data.text;
138
+ if (data.replyTo) mailOptions.replyTo = data.replyTo;
139
+ if (data.cc) mailOptions.cc = data.cc;
140
+ if (data.bcc) mailOptions.bcc = data.bcc;
141
+ if (data.attachments) mailOptions.attachments = data.attachments;
142
+ try {
143
+ const result = await transporter.sendMail(mailOptions);
144
+ return {
145
+ status: "sent",
146
+ channel: this.name,
147
+ metadata: { messageId: result.messageId }
148
+ };
149
+ } catch (err) {
150
+ const message = err instanceof Error ? err.message : String(err);
151
+ throw new ChannelError(this.name, message, err instanceof Error ? err : void 0);
152
+ }
153
+ }
154
+ /** Verify the SMTP connection (useful for health checks) */
155
+ async verify() {
156
+ const transporter = await this.getTransporter();
157
+ if (transporter.verify) return transporter.verify();
158
+ return true;
159
+ }
160
+ /** Close the transporter connection */
161
+ close() {
162
+ if (this.transporter?.close) this.transporter.close();
163
+ this.transporter = null;
164
+ }
165
+ };
166
+
167
+ //#endregion
168
+ //#region src/channels/webhook.channel.ts
169
+ /**
170
+ * Webhook Channel
171
+ * @module @classytic/notifications
172
+ *
173
+ * Sends notifications via HTTP POST/PUT to any URL.
174
+ * Supports HMAC-SHA256 payload signing for security.
175
+ * Zero dependencies - uses native fetch.
176
+ *
177
+ * @example
178
+ * ```typescript
179
+ * import { WebhookChannel } from '@classytic/notifications/channels';
180
+ *
181
+ * // Slack webhook
182
+ * const slack = new WebhookChannel({
183
+ * name: 'slack',
184
+ * url: 'https://hooks.slack.com/services/...',
185
+ * events: ['order.completed', 'user.created'],
186
+ * });
187
+ *
188
+ * // Signed webhook
189
+ * const hook = new WebhookChannel({
190
+ * url: 'https://api.partner.com/webhooks',
191
+ * secret: process.env.WEBHOOK_SECRET!,
192
+ * headers: { 'X-API-Key': process.env.PARTNER_KEY! },
193
+ * });
194
+ * ```
195
+ */
196
+ var WebhookChannel = class extends BaseChannel {
197
+ constructor(config) {
198
+ super({
199
+ name: "webhook",
200
+ ...config
201
+ });
202
+ }
203
+ async send(payload) {
204
+ const body = JSON.stringify({
205
+ event: payload.event,
206
+ recipient: payload.recipient,
207
+ data: payload.data,
208
+ metadata: payload.metadata,
209
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
210
+ });
211
+ const headers = {
212
+ "Content-Type": "application/json",
213
+ ...this.config.headers
214
+ };
215
+ if (this.config.secret) headers["X-Signature-256"] = `sha256=${createHmac("sha256", this.config.secret).update(body).digest("hex")}`;
216
+ try {
217
+ const response = await fetch(this.config.url, {
218
+ method: this.config.method ?? "POST",
219
+ headers,
220
+ body,
221
+ signal: AbortSignal.timeout(this.config.timeout ?? 1e4)
222
+ });
223
+ if (!response.ok) throw new ChannelError(this.name, `HTTP ${response.status}: ${response.statusText}`);
224
+ return {
225
+ status: "sent",
226
+ channel: this.name
227
+ };
228
+ } catch (err) {
229
+ if (err instanceof ChannelError) throw err;
230
+ const message = err instanceof Error ? err.message : String(err);
231
+ throw new ChannelError(this.name, message, err instanceof Error ? err : void 0);
232
+ }
233
+ }
234
+ };
235
+
236
+ //#endregion
237
+ //#region src/channels/console.channel.ts
238
+ /**
239
+ * Console Channel
240
+ * @module @classytic/notifications
241
+ *
242
+ * Logs notifications to the console. Useful for development and testing.
243
+ * Zero dependencies.
244
+ *
245
+ * @example
246
+ * ```typescript
247
+ * import { ConsoleChannel } from '@classytic/notifications/channels';
248
+ *
249
+ * const dev = new ConsoleChannel(); // logs all events
250
+ * const scoped = new ConsoleChannel({ events: ['user.*'] }); // only user events
251
+ * ```
252
+ */
253
+ var ConsoleChannel = class extends BaseChannel {
254
+ constructor(config = {}) {
255
+ super({
256
+ name: "console",
257
+ ...config
258
+ });
259
+ }
260
+ async send(payload) {
261
+ const output = {
262
+ event: payload.event,
263
+ recipient: payload.recipient,
264
+ data: payload.data,
265
+ template: payload.template,
266
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
267
+ };
268
+ console.log(`[notification] ${payload.event}`, JSON.stringify(output, null, 2));
269
+ return {
270
+ status: "sent",
271
+ channel: this.name
272
+ };
273
+ }
274
+ };
275
+
276
+ //#endregion
277
+ //#region src/channels/sms.channel.ts
278
+ /**
279
+ * SMS Channel
280
+ * @module @classytic/notifications
281
+ *
282
+ * Sends SMS notifications via any provider.
283
+ * Zero dependencies — bring your own SMS SDK.
284
+ *
285
+ * @example
286
+ * ```typescript
287
+ * import { SmsChannel } from '@classytic/notifications/channels';
288
+ *
289
+ * // Twilio (you manage the SDK)
290
+ * import twilio from 'twilio';
291
+ * const client = twilio(process.env.TWILIO_SID, process.env.TWILIO_TOKEN);
292
+ *
293
+ * const sms = new SmsChannel({
294
+ * from: '+15551234567',
295
+ * provider: {
296
+ * send: async ({ to, from, body }) => {
297
+ * const msg = await client.messages.create({ to, from, body });
298
+ * return { sid: msg.sid };
299
+ * },
300
+ * },
301
+ * });
302
+ *
303
+ * // AWS SNS
304
+ * import { SNSClient, PublishCommand } from '@aws-sdk/client-sns';
305
+ * const sns = new SNSClient({ region: 'us-east-1' });
306
+ *
307
+ * const snsSms = new SmsChannel({
308
+ * from: 'MyApp',
309
+ * provider: {
310
+ * send: async ({ to, body }) => {
311
+ * const res = await sns.send(new PublishCommand({
312
+ * PhoneNumber: to, Message: body,
313
+ * }));
314
+ * return { sid: res.MessageId ?? '' };
315
+ * },
316
+ * },
317
+ * });
318
+ *
319
+ * // Simple fetch-based (Vonage, MessageBird, etc.)
320
+ * const customSms = new SmsChannel({
321
+ * from: '+15551234567',
322
+ * provider: {
323
+ * send: async ({ to, from, body }) => {
324
+ * const res = await fetch('https://api.sms-provider.com/send', {
325
+ * method: 'POST',
326
+ * headers: { 'Content-Type': 'application/json', 'X-API-Key': '...' },
327
+ * body: JSON.stringify({ to, from, body }),
328
+ * });
329
+ * return { sid: await res.text() };
330
+ * },
331
+ * },
332
+ * });
333
+ * ```
334
+ */
335
+ var SmsChannel = class extends BaseChannel {
336
+ provider;
337
+ constructor(config) {
338
+ 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.");
339
+ super({
340
+ name: "sms",
341
+ ...config
342
+ });
343
+ this.provider = config.provider;
344
+ }
345
+ /**
346
+ * Pre-flight check called by the service before consuming a rate-limit
347
+ * token. Skip if the payload lacks a recipient phone OR a body — these
348
+ * skips are deterministic and shouldn't burn SMS quota.
349
+ */
350
+ canSend(payload) {
351
+ if (!payload.recipient.phone) return {
352
+ status: "skipped",
353
+ channel: this.name,
354
+ error: "No recipient phone number"
355
+ };
356
+ if (!(payload.data.text ?? payload.data.message ?? payload.data.subject ?? "")) return {
357
+ status: "skipped",
358
+ channel: this.name,
359
+ error: "No message body (data.text, data.message, or data.subject)"
360
+ };
361
+ return null;
362
+ }
363
+ async send(payload) {
364
+ const { recipient, data } = payload;
365
+ if (!recipient.phone) return {
366
+ status: "skipped",
367
+ channel: this.name,
368
+ error: "No recipient phone number"
369
+ };
370
+ const body = data.text ?? data.message ?? data.subject ?? "";
371
+ if (!body) return {
372
+ status: "skipped",
373
+ channel: this.name,
374
+ error: "No message body (data.text, data.message, or data.subject)"
375
+ };
376
+ try {
377
+ const result = await this.provider.send({
378
+ to: recipient.phone,
379
+ from: data.from ?? this.config.from,
380
+ body
381
+ });
382
+ return {
383
+ status: "sent",
384
+ channel: this.name,
385
+ metadata: { sid: result.sid }
386
+ };
387
+ } catch (err) {
388
+ const message = err instanceof Error ? err.message : String(err);
389
+ throw new ChannelError(this.name, message, err instanceof Error ? err : void 0);
390
+ }
391
+ }
392
+ };
393
+
394
+ //#endregion
395
+ //#region src/channels/push.channel.ts
396
+ /**
397
+ * Push Notification Channel
398
+ * @module @classytic/notifications
399
+ *
400
+ * Sends push notifications via any provider: FCM, Expo, OneSignal, APNs, etc.
401
+ * Zero dependencies — bring your own push provider.
402
+ *
403
+ * @example
404
+ * ```typescript
405
+ * import { PushChannel } from '@classytic/notifications/channels';
406
+ *
407
+ * // FCM via Firebase Admin (you manage the SDK)
408
+ * import admin from 'firebase-admin';
409
+ * admin.initializeApp({ ... });
410
+ *
411
+ * const push = new PushChannel({
412
+ * provider: {
413
+ * send: async ({ token, title, body, data }) => {
414
+ * const result = await admin.messaging().send({
415
+ * token,
416
+ * notification: { title, body },
417
+ * data,
418
+ * });
419
+ * return { messageId: result };
420
+ * },
421
+ * },
422
+ * });
423
+ *
424
+ * // Expo Push
425
+ * import { Expo } from 'expo-server-sdk';
426
+ * const expo = new Expo();
427
+ *
428
+ * const expoPush = new PushChannel({
429
+ * name: 'expo-push',
430
+ * provider: {
431
+ * send: async ({ token, title, body, data }) => {
432
+ * const [receipt] = await expo.sendPushNotificationsAsync([
433
+ * { to: token, title, body, data },
434
+ * ]);
435
+ * return { messageId: receipt.id };
436
+ * },
437
+ * },
438
+ * });
439
+ *
440
+ * // Simple fetch-based (OneSignal, custom backend, etc.)
441
+ * const customPush = new PushChannel({
442
+ * provider: {
443
+ * send: async ({ token, title, body, data }) => {
444
+ * const res = await fetch('https://api.push-service.com/send', {
445
+ * method: 'POST',
446
+ * headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ...' },
447
+ * body: JSON.stringify({ token, title, body, data }),
448
+ * });
449
+ * return { messageId: await res.text() };
450
+ * },
451
+ * },
452
+ * });
453
+ * ```
454
+ */
455
+ var PushChannel = class extends BaseChannel {
456
+ provider;
457
+ constructor(config) {
458
+ 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.");
459
+ super({
460
+ name: "push",
461
+ ...config
462
+ });
463
+ this.provider = config.provider;
464
+ }
465
+ /**
466
+ * Pre-flight check called by the service before consuming a rate-limit
467
+ * token. Skip when there's no device token or no displayable content.
468
+ */
469
+ canSend(payload) {
470
+ if (!payload.recipient.deviceToken) return {
471
+ status: "skipped",
472
+ channel: this.name,
473
+ error: "No recipient deviceToken"
474
+ };
475
+ const title = payload.data.title ?? payload.data.subject ?? "";
476
+ const body = payload.data.body ?? payload.data.text ?? payload.data.message ?? "";
477
+ if (!title && !body) return {
478
+ status: "skipped",
479
+ channel: this.name,
480
+ error: "No title or body (data.title, data.body)"
481
+ };
482
+ return null;
483
+ }
484
+ async send(payload) {
485
+ const { recipient, data } = payload;
486
+ if (!recipient.deviceToken) return {
487
+ status: "skipped",
488
+ channel: this.name,
489
+ error: "No recipient deviceToken"
490
+ };
491
+ const title = data.title ?? data.subject ?? "";
492
+ const body = data.body ?? data.text ?? data.message ?? "";
493
+ if (!title && !body) return {
494
+ status: "skipped",
495
+ channel: this.name,
496
+ error: "No title or body (data.title, data.body)"
497
+ };
498
+ try {
499
+ const result = await this.provider.send({
500
+ token: recipient.deviceToken,
501
+ title,
502
+ body,
503
+ data: data.pushData,
504
+ imageUrl: data.imageUrl
505
+ });
506
+ return {
507
+ status: "sent",
508
+ channel: this.name,
509
+ metadata: { messageId: result.messageId }
510
+ };
511
+ } catch (err) {
512
+ const message = err instanceof Error ? err.message : String(err);
513
+ throw new ChannelError(this.name, message, err instanceof Error ? err : void 0);
514
+ }
515
+ }
516
+ };
517
+
518
+ //#endregion
519
+ export { EmailChannel as a, WebhookChannel as i, SmsChannel as n, BaseChannel as o, ConsoleChannel as r, PushChannel as t };
@@ -0,0 +1,73 @@
1
+ import { E as SmsChannelConfig, a as ChannelConfig, c as EmailChannelConfig, h as NotificationPayload, i as Channel, j as WebhookChannelConfig, w as SendResult, y as PushChannelConfig } from "./types-BMs4UhKD.mjs";
2
+
3
+ //#region src/channels/BaseChannel.d.ts
4
+ declare abstract class BaseChannel<TConfig extends ChannelConfig = ChannelConfig> implements Channel {
5
+ readonly name: string;
6
+ protected config: TConfig;
7
+ constructor(config: TConfig);
8
+ /** Check if this channel should handle a given event */
9
+ shouldHandle(event: string): boolean;
10
+ /** Send notification - must be implemented by subclass */
11
+ abstract send(payload: NotificationPayload): Promise<SendResult>;
12
+ }
13
+ //#endregion
14
+ //#region src/channels/email.channel.d.ts
15
+ declare class EmailChannel extends BaseChannel<EmailChannelConfig> {
16
+ private transporter;
17
+ constructor(config: EmailChannelConfig);
18
+ /** Lazily initialize the Nodemailer transporter */
19
+ private getTransporter;
20
+ /** Fields that defaults must never override */
21
+ private static readonly PROTECTED_FIELDS;
22
+ /**
23
+ * Pre-flight check called by the service before consuming a rate-limit
24
+ * token. Returning a skip result here avoids burning quota on payloads
25
+ * that obviously can't deliver (e.g., a mixed-channel batch where the
26
+ * recipient has a phone but no email).
27
+ */
28
+ canSend(payload: NotificationPayload): SendResult | null;
29
+ send(payload: NotificationPayload): Promise<SendResult>;
30
+ /** Verify the SMTP connection (useful for health checks) */
31
+ verify(): Promise<boolean>;
32
+ /** Close the transporter connection */
33
+ close(): void;
34
+ }
35
+ //#endregion
36
+ //#region src/channels/webhook.channel.d.ts
37
+ declare class WebhookChannel extends BaseChannel<WebhookChannelConfig> {
38
+ constructor(config: WebhookChannelConfig);
39
+ send(payload: NotificationPayload): Promise<SendResult>;
40
+ }
41
+ //#endregion
42
+ //#region src/channels/console.channel.d.ts
43
+ declare class ConsoleChannel extends BaseChannel<ChannelConfig> {
44
+ constructor(config?: ChannelConfig);
45
+ send(payload: NotificationPayload): Promise<SendResult>;
46
+ }
47
+ //#endregion
48
+ //#region src/channels/sms.channel.d.ts
49
+ declare class SmsChannel extends BaseChannel<SmsChannelConfig> {
50
+ private provider;
51
+ constructor(config: SmsChannelConfig);
52
+ /**
53
+ * Pre-flight check called by the service before consuming a rate-limit
54
+ * token. Skip if the payload lacks a recipient phone OR a body — these
55
+ * skips are deterministic and shouldn't burn SMS quota.
56
+ */
57
+ canSend(payload: NotificationPayload): SendResult | null;
58
+ send(payload: NotificationPayload): Promise<SendResult>;
59
+ }
60
+ //#endregion
61
+ //#region src/channels/push.channel.d.ts
62
+ declare class PushChannel extends BaseChannel<PushChannelConfig> {
63
+ private provider;
64
+ constructor(config: PushChannelConfig);
65
+ /**
66
+ * Pre-flight check called by the service before consuming a rate-limit
67
+ * token. Skip when there's no device token or no displayable content.
68
+ */
69
+ canSend(payload: NotificationPayload): SendResult | null;
70
+ send(payload: NotificationPayload): Promise<SendResult>;
71
+ }
72
+ //#endregion
73
+ export { EmailChannel as a, WebhookChannel as i, SmsChannel as n, BaseChannel as o, ConsoleChannel as r, PushChannel as t };