@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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@classytic/notifications",
3
- "version": "1.2.0",
4
- "description": "Multi-channel notification system with pluggable providers, templates, and retry - zero required dependencies",
3
+ "version": "2.1.0",
4
+ "description": "Multi-channel notifications (Email, SMS, Push, Webhook) with rate limiting, delivery tracking, queue adapters, channel fallback, templates, retry — zero required dependencies",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "main": "./dist/index.mjs",
@@ -16,11 +16,22 @@
16
16
  "types": "./dist/channels/index.d.mts",
17
17
  "default": "./dist/channels/index.mjs"
18
18
  },
19
+ "./providers": {
20
+ "types": "./dist/providers/index.d.mts",
21
+ "default": "./dist/providers/index.mjs"
22
+ },
19
23
  "./utils": {
20
24
  "types": "./dist/utils/index.d.mts",
21
25
  "default": "./dist/utils/index.mjs"
22
26
  }
23
27
  },
28
+ "typesVersions": {
29
+ "*": {
30
+ "channels": ["./dist/channels/index.d.mts"],
31
+ "providers": ["./dist/providers/index.d.mts"],
32
+ "utils": ["./dist/utils/index.d.mts"]
33
+ }
34
+ },
24
35
  "files": [
25
36
  "dist",
26
37
  "README.md",
@@ -32,20 +43,20 @@
32
43
  "multi-channel",
33
44
  "email",
34
45
  "sms",
35
- "push",
46
+ "push-notifications",
36
47
  "webhook",
37
48
  "nodemailer",
38
49
  "smtp",
39
50
  "ses",
40
- "gmail",
41
- "event-driven",
51
+ "rate-limiting",
52
+ "delivery-tracking",
53
+ "queue",
54
+ "channel-fallback",
42
55
  "templates",
43
56
  "retry",
57
+ "idempotency",
44
58
  "pluggable",
45
59
  "framework-agnostic",
46
- "express",
47
- "fastify",
48
- "nestjs",
49
60
  "typescript",
50
61
  "zero-dependencies"
51
62
  ],
@@ -54,6 +65,9 @@
54
65
  "Sadman Chowdhury (https://github.com/siam923)"
55
66
  ],
56
67
  "license": "MIT",
68
+ "publishConfig": {
69
+ "access": "public"
70
+ },
57
71
  "repository": {
58
72
  "type": "git",
59
73
  "url": "git+https://github.com/classytic/notifications.git"
@@ -63,7 +77,7 @@
63
77
  },
64
78
  "homepage": "https://github.com/classytic/notifications#readme",
65
79
  "peerDependencies": {
66
- "nodemailer": "^6.0.0 || ^7.0.0 || ^8.0.0"
80
+ "nodemailer": ">=6"
67
81
  },
68
82
  "peerDependenciesMeta": {
69
83
  "nodemailer": {
@@ -79,22 +93,25 @@
79
93
  "test": "vitest run",
80
94
  "test:watch": "vitest",
81
95
  "test:coverage": "vitest run --coverage",
96
+ "test:live": "vitest run --config vitest.live.config.ts",
82
97
  "typecheck": "tsc --noEmit",
83
- "prepublishOnly": "npm run build && npm run typecheck",
98
+ "prepublishOnly": "npm run build && npm run typecheck && npm test",
99
+ "push": "classytic-push",
84
100
  "publish:dry": "npm publish --dry-run --access public",
85
101
  "publish:npm": "npm publish --access public",
86
- "release": "npm run build && npm run typecheck && npm publish --access public",
102
+ "release": "npm run build && npm run typecheck && npm test && npm publish --access public",
87
103
  "release:patch": "npm version patch && npm run release",
88
104
  "release:minor": "npm version minor && npm run release",
89
105
  "release:major": "npm version major && npm run release"
90
106
  },
91
107
  "devDependencies": {
108
+ "@classytic/dev-tools": "^0.2.0",
92
109
  "@types/node": "^22.0.0",
93
110
  "@types/nodemailer": "^6.4.17",
94
111
  "@vitest/coverage-v8": "3.2.4",
95
112
  "nodemailer": "^6.10.1",
96
- "tsdown": "0.20.3",
113
+ "tsdown": "0.21.4",
97
114
  "typescript": "^5.7.0",
98
115
  "vitest": "^3.0.0"
99
116
  }
100
- }
117
+ }
@@ -1,139 +0,0 @@
1
- import { b as ResolvedRetryConfig, d as HookMap, u as HookHandler, x as RetryConfig } from "./types-BnjZ7x2U.mjs";
2
-
3
- //#region src/utils/merge-hooks.d.ts
4
- type HookInput = Record<string, HookHandler | HookHandler[]>;
5
- declare function mergeHooks(...hookConfigs: (HookInput | null | undefined)[]): HookMap;
6
- //#endregion
7
- //#region src/utils/retry.d.ts
8
- /** Resolve retry config with defaults */
9
- declare function resolveRetryConfig(config?: RetryConfig): ResolvedRetryConfig;
10
- /** Calculate delay for a given attempt */
11
- declare function calculateDelay(attempt: number, config: ResolvedRetryConfig): number;
12
- /**
13
- * Execute a function with retry and backoff
14
- *
15
- * @param fn - Async function to retry
16
- * @param config - Retry configuration
17
- * @param onRetry - Called before each retry attempt
18
- * @returns Result of fn
19
- * @throws Last error after all attempts exhausted
20
- */
21
- declare function withRetry<T>(fn: () => Promise<T>, config: ResolvedRetryConfig, onRetry?: (attempt: number, error: Error) => void): Promise<T>;
22
- //#endregion
23
- //#region src/utils/emitter.d.ts
24
- /**
25
- * Lightweight typed event emitter
26
- * @module @classytic/notifications
27
- *
28
- * Zero-dependency alternative to Node's EventEmitter.
29
- * Keeps the library portable across runtimes.
30
- */
31
- type Handler = (...args: unknown[]) => void | Promise<void>;
32
- declare class Emitter {
33
- private handlers;
34
- /** Register an event handler */
35
- on(event: string, handler: Handler): this;
36
- /** Remove an event handler */
37
- off(event: string, handler: Handler): this;
38
- /** Emit an event (runs handlers sequentially, awaits async) */
39
- emit(event: string, ...args: unknown[]): Promise<void>;
40
- /** Remove all handlers for an event (or all events) */
41
- removeAll(event?: string): this;
42
- }
43
- //#endregion
44
- //#region src/utils/errors.d.ts
45
- /**
46
- * Notification Errors
47
- * @module @classytic/notifications
48
- */
49
- declare class NotificationError extends Error {
50
- readonly code: string;
51
- readonly channel?: string;
52
- readonly cause?: Error;
53
- constructor(message: string, options?: {
54
- code?: string;
55
- channel?: string;
56
- cause?: Error;
57
- });
58
- }
59
- declare class ChannelError extends NotificationError {
60
- constructor(channel: string, message: string, cause?: Error);
61
- }
62
- declare class ProviderNotInstalledError extends NotificationError {
63
- constructor(provider: string, installCmd: string);
64
- }
65
- //#endregion
66
- //#region src/utils/quiet-hours.d.ts
67
- /**
68
- * Quiet hours utility
69
- * @module @classytic/notifications/utils
70
- *
71
- * Checks if the current time falls within a user's quiet hours window.
72
- * Uses Intl.DateTimeFormat for timezone conversion (zero dependencies, Node 18+).
73
- */
74
- /** Quiet hours configuration */
75
- interface QuietHoursConfig {
76
- /** Start time in HH:MM format (e.g. "22:00") */
77
- start?: string;
78
- /** End time in HH:MM format (e.g. "07:00") */
79
- end?: string;
80
- /** IANA timezone (e.g. "America/New_York"). Defaults to UTC */
81
- timezone?: string;
82
- }
83
- /**
84
- * Check if the current time falls within quiet hours.
85
- *
86
- * Supports overnight ranges (e.g. 22:00 - 07:00).
87
- * Returns false if start/end are missing or malformed.
88
- *
89
- * @param quiet - Quiet hours config with start, end, and optional timezone
90
- * @param now - Current date (defaults to new Date(), injectable for testing)
91
- */
92
- declare function isQuietHours(quiet: QuietHoursConfig, now?: Date): boolean;
93
- //#endregion
94
- //#region src/utils/concurrency.d.ts
95
- /**
96
- * Concurrency pool utility
97
- * @module @classytic/notifications/utils
98
- *
99
- * Process items in parallel with controlled concurrency.
100
- * Zero dependencies — uses a worker-pool pattern where N workers
101
- * pull from a shared queue, keeping the pipeline full at all times.
102
- *
103
- * Unlike chunk-based approaches (process N, wait, process N, wait),
104
- * the pool starts the next item as soon as any worker finishes,
105
- * eliminating idle time from slow outliers.
106
- *
107
- * @example
108
- * ```typescript
109
- * import { pMap } from '@classytic/notifications/utils';
110
- *
111
- * const results = await pMap(
112
- * urls,
113
- * async (url) => fetch(url).then(r => r.json()),
114
- * { concurrency: 5 },
115
- * );
116
- * ```
117
- */
118
- /** Options for pMap */
119
- interface PMapOptions {
120
- /** Max parallel operations (default: 10) */
121
- concurrency?: number;
122
- }
123
- /**
124
- * Map over items with controlled concurrency.
125
- *
126
- * Like `Promise.all(items.map(fn))` but with a max number of
127
- * parallel operations. Results are returned in input order.
128
- *
129
- * Uses a worker-pool pattern: N workers pull from a shared index,
130
- * so the pipeline stays full even when some items are slower.
131
- *
132
- * @param items - Array of items to process
133
- * @param fn - Async function to apply to each item
134
- * @param options - Concurrency options
135
- * @returns Array of results in the same order as input
136
- */
137
- declare function pMap<T, R>(items: T[], fn: (item: T, index: number) => Promise<R>, options?: PMapOptions): Promise<R[]>;
138
- //#endregion
139
- export { ChannelError as a, Emitter as c, withRetry as d, mergeHooks as f, isQuietHours as i, calculateDelay as l, pMap as n, NotificationError as o, QuietHoursConfig as r, ProviderNotInstalledError as s, PMapOptions as t, resolveRetryConfig as u };
@@ -1,39 +0,0 @@
1
- import { D as WebhookChannelConfig, S as SendResult, a as ChannelConfig, c as EmailChannelConfig, h as NotificationPayload, i as Channel } from "./types-BnjZ7x2U.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
- send(payload: NotificationPayload): Promise<SendResult>;
21
- /** Verify the SMTP connection (useful for health checks) */
22
- verify(): Promise<boolean>;
23
- /** Close the transporter connection */
24
- close(): void;
25
- }
26
- //#endregion
27
- //#region src/channels/webhook.channel.d.ts
28
- declare class WebhookChannel extends BaseChannel<WebhookChannelConfig> {
29
- constructor(config: WebhookChannelConfig);
30
- send(payload: NotificationPayload): Promise<SendResult>;
31
- }
32
- //#endregion
33
- //#region src/channels/console.channel.d.ts
34
- declare class ConsoleChannel extends BaseChannel<ChannelConfig> {
35
- constructor(config?: ChannelConfig);
36
- send(payload: NotificationPayload): Promise<SendResult>;
37
- }
38
- //#endregion
39
- export { BaseChannel as i, WebhookChannel as n, EmailChannel as r, ConsoleChannel as t };
@@ -1,246 +0,0 @@
1
- import { r as ProviderNotInstalledError, t as ChannelError } from "./errors-DAIVZx_Q.mjs";
2
-
3
- //#region src/channels/BaseChannel.ts
4
- var BaseChannel = class {
5
- name;
6
- config;
7
- constructor(config) {
8
- this.name = config.name ?? this.constructor.name;
9
- this.config = config;
10
- }
11
- /** Check if this channel should handle a given event */
12
- shouldHandle(event) {
13
- if (this.config.enabled === false) return false;
14
- const events = this.config.events;
15
- if (!events || events.length === 0) return true;
16
- return events.some((pattern) => {
17
- if (pattern === event) return true;
18
- if (pattern.endsWith(".*")) {
19
- const prefix = pattern.slice(0, -2);
20
- return event.startsWith(prefix + ".");
21
- }
22
- return false;
23
- });
24
- }
25
- };
26
-
27
- //#endregion
28
- //#region src/channels/email.channel.ts
29
- /**
30
- * Email Channel (Nodemailer)
31
- * @module @classytic/notifications
32
- *
33
- * Sends email notifications via Nodemailer.
34
- * Supports any Nodemailer transport: SMTP, SES, Gmail, custom.
35
- *
36
- * Requires peer dependency: npm install nodemailer @types/nodemailer
37
- *
38
- * @example
39
- * ```typescript
40
- * import { EmailChannel } from '@classytic/notifications/channels';
41
- *
42
- * // Option 1: SMTP transport options
43
- * const email = new EmailChannel({
44
- * from: 'App <noreply@app.com>',
45
- * transport: {
46
- * host: 'smtp.gmail.com',
47
- * port: 587,
48
- * auth: { user: 'user@gmail.com', pass: 'app-password' },
49
- * },
50
- * });
51
- *
52
- * // Option 2: Gmail service shorthand
53
- * const gmail = new EmailChannel({
54
- * from: 'noreply@app.com',
55
- * transport: { service: 'gmail', auth: { user: '...', pass: '...' } },
56
- * });
57
- *
58
- * // Option 3: Pre-created transporter (SES, custom)
59
- * import nodemailer from 'nodemailer';
60
- * import aws from '@aws-sdk/client-ses';
61
- * const ses = new aws.SES({ region: 'us-east-1' });
62
- * const email = new EmailChannel({
63
- * from: 'noreply@app.com',
64
- * transporter: nodemailer.createTransport({ SES: { ses, aws } }),
65
- * });
66
- * ```
67
- */
68
- var EmailChannel = class extends BaseChannel {
69
- transporter = null;
70
- constructor(config) {
71
- super({
72
- name: "email",
73
- ...config
74
- });
75
- }
76
- /** Lazily initialize the Nodemailer transporter */
77
- async getTransporter() {
78
- if (this.transporter) return this.transporter;
79
- if (this.config.transporter) {
80
- this.transporter = this.config.transporter;
81
- return this.transporter;
82
- }
83
- if (!this.config.transport) throw new ChannelError(this.name, "Either transport options or a transporter instance is required");
84
- try {
85
- this.transporter = (await import("nodemailer")).default.createTransport(this.config.transport);
86
- return this.transporter;
87
- } catch {
88
- throw new ProviderNotInstalledError("nodemailer", "npm install nodemailer");
89
- }
90
- }
91
- async send(payload) {
92
- const { recipient, data } = payload;
93
- if (!recipient.email) return {
94
- status: "skipped",
95
- channel: this.name,
96
- error: "No recipient email"
97
- };
98
- const transporter = await this.getTransporter();
99
- const mailOptions = {
100
- from: data.from ?? this.config.from,
101
- to: recipient.email,
102
- subject: data.subject ?? "",
103
- ...this.config.defaults
104
- };
105
- if (data.html) mailOptions.html = data.html;
106
- if (data.text) mailOptions.text = data.text;
107
- if (data.replyTo) mailOptions.replyTo = data.replyTo;
108
- if (data.cc) mailOptions.cc = data.cc;
109
- if (data.bcc) mailOptions.bcc = data.bcc;
110
- if (data.attachments) mailOptions.attachments = data.attachments;
111
- try {
112
- const result = await transporter.sendMail(mailOptions);
113
- return {
114
- status: "sent",
115
- channel: this.name,
116
- metadata: { messageId: result.messageId }
117
- };
118
- } catch (err) {
119
- const message = err instanceof Error ? err.message : String(err);
120
- throw new ChannelError(this.name, message, err instanceof Error ? err : void 0);
121
- }
122
- }
123
- /** Verify the SMTP connection (useful for health checks) */
124
- async verify() {
125
- const transporter = await this.getTransporter();
126
- if (transporter.verify) return transporter.verify();
127
- return true;
128
- }
129
- /** Close the transporter connection */
130
- close() {
131
- if (this.transporter?.close) this.transporter.close();
132
- this.transporter = null;
133
- }
134
- };
135
-
136
- //#endregion
137
- //#region src/channels/webhook.channel.ts
138
- /**
139
- * Webhook Channel
140
- * @module @classytic/notifications
141
- *
142
- * Sends notifications via HTTP POST/PUT to any URL.
143
- * Supports HMAC-SHA256 payload signing for security.
144
- * Zero dependencies - uses native fetch.
145
- *
146
- * @example
147
- * ```typescript
148
- * import { WebhookChannel } from '@classytic/notifications/channels';
149
- *
150
- * // Slack webhook
151
- * const slack = new WebhookChannel({
152
- * name: 'slack',
153
- * url: 'https://hooks.slack.com/services/...',
154
- * events: ['order.completed', 'user.created'],
155
- * });
156
- *
157
- * // Signed webhook
158
- * const hook = new WebhookChannel({
159
- * url: 'https://api.partner.com/webhooks',
160
- * secret: process.env.WEBHOOK_SECRET!,
161
- * headers: { 'X-API-Key': process.env.PARTNER_KEY! },
162
- * });
163
- * ```
164
- */
165
- var WebhookChannel = class extends BaseChannel {
166
- constructor(config) {
167
- super({
168
- name: "webhook",
169
- ...config
170
- });
171
- }
172
- async send(payload) {
173
- const body = JSON.stringify({
174
- event: payload.event,
175
- recipient: payload.recipient,
176
- data: payload.data,
177
- metadata: payload.metadata,
178
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
179
- });
180
- const headers = {
181
- "Content-Type": "application/json",
182
- ...this.config.headers
183
- };
184
- if (this.config.secret) headers["X-Signature-256"] = `sha256=${(await import("node:crypto")).createHmac("sha256", this.config.secret).update(body).digest("hex")}`;
185
- try {
186
- const response = await fetch(this.config.url, {
187
- method: this.config.method ?? "POST",
188
- headers,
189
- body,
190
- signal: AbortSignal.timeout(this.config.timeout ?? 1e4)
191
- });
192
- if (!response.ok) throw new ChannelError(this.name, `HTTP ${response.status}: ${response.statusText}`);
193
- return {
194
- status: "sent",
195
- channel: this.name
196
- };
197
- } catch (err) {
198
- if (err instanceof ChannelError) throw err;
199
- const message = err instanceof Error ? err.message : String(err);
200
- throw new ChannelError(this.name, message, err instanceof Error ? err : void 0);
201
- }
202
- }
203
- };
204
-
205
- //#endregion
206
- //#region src/channels/console.channel.ts
207
- /**
208
- * Console Channel
209
- * @module @classytic/notifications
210
- *
211
- * Logs notifications to the console. Useful for development and testing.
212
- * Zero dependencies.
213
- *
214
- * @example
215
- * ```typescript
216
- * import { ConsoleChannel } from '@classytic/notifications/channels';
217
- *
218
- * const dev = new ConsoleChannel(); // logs all events
219
- * const scoped = new ConsoleChannel({ events: ['user.*'] }); // only user events
220
- * ```
221
- */
222
- var ConsoleChannel = class extends BaseChannel {
223
- constructor(config = {}) {
224
- super({
225
- name: "console",
226
- ...config
227
- });
228
- }
229
- async send(payload) {
230
- const output = {
231
- event: payload.event,
232
- recipient: payload.recipient,
233
- data: payload.data,
234
- template: payload.template,
235
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
236
- };
237
- console.log(`[notification] ${payload.event}`, JSON.stringify(output, null, 2));
238
- return {
239
- status: "sent",
240
- channel: this.name
241
- };
242
- }
243
- };
244
-
245
- //#endregion
246
- export { BaseChannel as i, WebhookChannel as n, EmailChannel as r, ConsoleChannel as t };