@classytic/notifications 1.2.0 → 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 -37
- package/README.md +351 -201
- package/dist/channels/index.d.mts +2 -2
- package/dist/channels/index.mjs +2 -2
- package/dist/index.d.mts +38 -18
- package/dist/index.mjs +117 -28
- package/dist/{console.channel-BoWi_5nH.d.mts → push.channel-4mRkzrEu.d.mts} +18 -2
- package/dist/{console.channel-CfA4b_Er.mjs → push.channel-D1FdTPUi.mjs} +228 -6
- package/dist/status-webhook-BDaI1BMy.d.mts +268 -0
- package/dist/status-webhook-XY42DCj_.mjs +582 -0
- package/dist/{types-BnjZ7x2U.d.mts → types-D94B3VNX.d.mts} +251 -2
- package/dist/utils/index.d.mts +3 -3
- package/dist/utils/index.mjs +3 -3
- package/package.json +11 -11
- package/dist/concurrency-CV_XyiBQ.d.mts +0 -139
- package/dist/merge-hooks-B4_uHR9x.mjs +0 -233
- /package/dist/{errors-DAIVZx_Q.mjs → errors-FYJYmfvj.mjs} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as
|
|
2
|
-
export { BaseChannel, ConsoleChannel, EmailChannel, WebhookChannel };
|
|
1
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-4mRkzrEu.mjs";
|
|
2
|
+
export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, WebhookChannel };
|
package/dist/channels/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { i as
|
|
1
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-D1FdTPUi.mjs";
|
|
2
2
|
|
|
3
|
-
export { BaseChannel, ConsoleChannel, EmailChannel, WebhookChannel };
|
|
3
|
+
export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, WebhookChannel };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { i as
|
|
3
|
-
import { a as
|
|
1
|
+
import { A as TemplateResult, B as DeliveryLogQuery, C as RetryConfig, D as SmsProvider, E as SmsChannelConfig, F as QueueJob, G as MemoryRateLimitStore, H as IDEMPOTENCY_DEFAULT_TTL, I as QueueJobStatus, K as RateLimitConfig, L as QueueProcessor, M as MemoryQueue, N as QueueAdapter, O as SmtpTransportOptions, P as QueueEnqueueOptions, R as DeliveryLog, S as ResolvedRetryConfig, T as ServiceEvent, U as IdempotencyStore, V as MemoryDeliveryLog, W as MemoryIdempotencyStore, _ as NotificationServiceConfig, a as ChannelConfig, b as PushProvider, c as EmailChannelConfig, d as HookMap, f as Logger, g as NotificationPreferences, h as NotificationPayload, i as Channel, j as WebhookChannelConfig, k as TemplateResolver, l as EventHandler, m as NotificationHookConfig, n as BatchProgress, o as DispatchResult, p as NodemailerTransporter, q as RateLimitStore, r as BatchResult, s as EmailAttachment, t as BatchOptions, u as HookHandler, v as PreferenceResolver, w as SendResult, x as Recipient, y as PushChannelConfig, z as DeliveryLogEntry } from "./types-D94B3VNX.mjs";
|
|
2
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-4mRkzrEu.mjs";
|
|
3
|
+
import { S as mergeHooks, _ as ProviderNotInstalledError, a as createStatusHandler, b as resolveRetryConfig, c as TemplateDefinition, d as PMapOptions, f as pMap, g as NotificationError, h as ChannelError, i as StatusUpdate, l as TemplateMap, m as isQuietHours, n as StatusHandler, o as FallbackOptions, p as QuietHoursConfig, r as StatusHandlerConfig, s as withFallback, t as DeliveryStatus, u as createSimpleResolver, v as Emitter, x as withRetry, y as calculateDelay } from "./status-webhook-BDaI1BMy.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/NotificationService.d.ts
|
|
6
6
|
declare class NotificationService {
|
|
@@ -12,6 +12,9 @@ declare class NotificationService {
|
|
|
12
12
|
private emitter;
|
|
13
13
|
private idempotencyStore?;
|
|
14
14
|
private idempotencyTtl;
|
|
15
|
+
private deliveryLog?;
|
|
16
|
+
private rateLimitStore?;
|
|
17
|
+
private queueAdapter?;
|
|
15
18
|
constructor(config?: NotificationServiceConfig);
|
|
16
19
|
/** Add a channel at runtime */
|
|
17
20
|
addChannel(channel: Channel): this;
|
|
@@ -21,27 +24,44 @@ declare class NotificationService {
|
|
|
21
24
|
getChannel(name: string): Channel | undefined;
|
|
22
25
|
/** List all registered channel names */
|
|
23
26
|
getChannelNames(): string[];
|
|
27
|
+
/** Get the delivery log instance (for querying history) */
|
|
28
|
+
getDeliveryLog(): DeliveryLog | undefined;
|
|
24
29
|
/**
|
|
25
|
-
* Send a notification to all matching channels
|
|
30
|
+
* Send a notification to all matching channels.
|
|
31
|
+
*
|
|
32
|
+
* When a queue adapter is configured, notifications are enqueued
|
|
33
|
+
* for crash-resilient delivery instead of sending immediately.
|
|
26
34
|
*
|
|
27
35
|
* Flow:
|
|
28
36
|
* 1. Emit `before:send` (awaited — listeners can block or throw to abort)
|
|
29
|
-
* 2.
|
|
30
|
-
* 3.
|
|
31
|
-
* 4.
|
|
32
|
-
* 5.
|
|
33
|
-
* 6.
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
* propagates the error to the caller. Use this for validation or rate limiting.
|
|
38
|
-
* - `after:send`, `send:success`, `send:failed` are awaited but **safe** — listener errors
|
|
39
|
-
* are caught and logged, never masking the dispatch result.
|
|
40
|
-
* - `send:retry` is emitted inside the retry callback — listener errors are caught + logged.
|
|
37
|
+
* 2. If queue is configured, enqueue and return early
|
|
38
|
+
* 3. Resolve template (if provided)
|
|
39
|
+
* 4. Filter channels by event + target list
|
|
40
|
+
* 5. Apply user preference filtering
|
|
41
|
+
* 6. Check per-channel rate limits
|
|
42
|
+
* 7. Send to all channels in parallel (with retry)
|
|
43
|
+
* 8. Record to delivery log
|
|
44
|
+
* 9. Emit `after:send` / `send:success` / `send:failed`
|
|
41
45
|
*/
|
|
42
46
|
send(payload: NotificationPayload): Promise<DispatchResult>;
|
|
43
|
-
/**
|
|
47
|
+
/**
|
|
48
|
+
* Internal send pipeline (used by both direct sends and queue processor).
|
|
49
|
+
*
|
|
50
|
+
* Every code path — including skips for idempotency, quiet hours, and
|
|
51
|
+
* preferences — flows through finalize() so delivery logging and
|
|
52
|
+
* lifecycle events are always emitted.
|
|
53
|
+
*/
|
|
54
|
+
private sendDirect;
|
|
55
|
+
/**
|
|
56
|
+
* Single exit path for all send outcomes.
|
|
57
|
+
* Records to delivery log and emits lifecycle events regardless of
|
|
58
|
+
* whether the notification was sent, skipped, or failed.
|
|
59
|
+
*/
|
|
60
|
+
private finalize;
|
|
61
|
+
/** Send to a single channel with rate limiting and retry */
|
|
44
62
|
private sendToChannel;
|
|
63
|
+
/** Extract rate limit config from a channel */
|
|
64
|
+
private getChannelRateLimit;
|
|
45
65
|
/**
|
|
46
66
|
* Send multiple notifications with controlled concurrency.
|
|
47
67
|
*
|
|
@@ -113,4 +133,4 @@ declare class NotificationService {
|
|
|
113
133
|
off(event: ServiceEvent, handler: EventHandler): this;
|
|
114
134
|
}
|
|
115
135
|
//#endregion
|
|
116
|
-
export { BaseChannel, type BatchOptions, type BatchProgress, type BatchResult, type Channel, type ChannelConfig, ChannelError, ConsoleChannel, type DispatchResult, type EmailAttachment, EmailChannel, type EmailChannelConfig, Emitter, type EventHandler, type HookHandler, type HookMap, IDEMPOTENCY_DEFAULT_TTL, type IdempotencyStore, type Logger, MemoryIdempotencyStore, type NodemailerTransporter, NotificationError, type NotificationHookConfig, type NotificationPayload, type NotificationPreferences, NotificationService, type NotificationServiceConfig, type PMapOptions, type PreferenceResolver, ProviderNotInstalledError, type QuietHoursConfig, type Recipient, type ResolvedRetryConfig, type RetryConfig, type SendResult, type ServiceEvent, type SmtpTransportOptions, type TemplateResolver, type TemplateResult, WebhookChannel, type WebhookChannelConfig, calculateDelay, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withRetry };
|
|
136
|
+
export { BaseChannel, type BatchOptions, type BatchProgress, type BatchResult, type Channel, type ChannelConfig, ChannelError, ConsoleChannel, type DeliveryLog, type DeliveryLogEntry, type DeliveryLogQuery, type DeliveryStatus, type DispatchResult, type EmailAttachment, EmailChannel, type EmailChannelConfig, Emitter, type EventHandler, type FallbackOptions, type HookHandler, type HookMap, IDEMPOTENCY_DEFAULT_TTL, type IdempotencyStore, type Logger, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, type NodemailerTransporter, NotificationError, type NotificationHookConfig, type NotificationPayload, type NotificationPreferences, NotificationService, type NotificationServiceConfig, type PMapOptions, type PreferenceResolver, ProviderNotInstalledError, PushChannel, type PushChannelConfig, type PushProvider, type QueueAdapter, type QueueEnqueueOptions, type QueueJob, type QueueJobStatus, type QueueProcessor, type QuietHoursConfig, type RateLimitConfig, type RateLimitStore, type Recipient, type ResolvedRetryConfig, type RetryConfig, type SendResult, type ServiceEvent, SmsChannel, type SmsChannelConfig, type SmsProvider, type SmtpTransportOptions, type StatusHandler, type StatusHandlerConfig, type StatusUpdate, type TemplateDefinition, type TemplateMap, type TemplateResolver, type TemplateResult, WebhookChannel, type WebhookChannelConfig, calculateDelay, createSimpleResolver, createStatusHandler, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import { n as NotificationError, r as ProviderNotInstalledError, t as ChannelError } from "./errors-
|
|
3
|
-
import { i as
|
|
1
|
+
import { a as MemoryDeliveryLog, c as MemoryRateLimitStore, d as isQuietHours, f as calculateDelay, h as Emitter, i as MemoryQueue, l as IDEMPOTENCY_DEFAULT_TTL, m as withRetry, n as withFallback, o as mergeHooks, p as resolveRetryConfig, r as createSimpleResolver, s as pMap, t as createStatusHandler, u as MemoryIdempotencyStore } from "./status-webhook-XY42DCj_.mjs";
|
|
2
|
+
import { n as NotificationError, r as ProviderNotInstalledError, t as ChannelError } from "./errors-FYJYmfvj.mjs";
|
|
3
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-D1FdTPUi.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/NotificationService.ts
|
|
6
6
|
/**
|
|
@@ -11,14 +11,21 @@ import { i as BaseChannel, n as WebhookChannel, r as EmailChannel, t as ConsoleC
|
|
|
11
11
|
* Routes notifications to channels, resolves templates,
|
|
12
12
|
* applies user preferences, retries on failure, and emits lifecycle events.
|
|
13
13
|
*
|
|
14
|
+
* v2 additions: rate limiting, delivery log, queue adapter, BCC batching.
|
|
15
|
+
*
|
|
14
16
|
* @example
|
|
15
17
|
* ```typescript
|
|
16
18
|
* import { NotificationService } from '@classytic/notifications';
|
|
17
19
|
* import { EmailChannel, ConsoleChannel } from '@classytic/notifications/channels';
|
|
20
|
+
* import { MemoryDeliveryLog } from '@classytic/notifications/utils';
|
|
18
21
|
*
|
|
19
22
|
* const notifications = new NotificationService({
|
|
20
23
|
* channels: [
|
|
21
|
-
* new EmailChannel({
|
|
24
|
+
* new EmailChannel({
|
|
25
|
+
* from: 'noreply@app.com',
|
|
26
|
+
* transport: { service: 'gmail', auth: { user, pass } },
|
|
27
|
+
* rateLimit: { maxPerWindow: 500, windowMs: 86_400_000 }, // Gmail 500/day
|
|
28
|
+
* }),
|
|
22
29
|
* new ConsoleChannel(),
|
|
23
30
|
* ],
|
|
24
31
|
* templates: async (id, data) => {
|
|
@@ -26,6 +33,7 @@ import { i as BaseChannel, n as WebhookChannel, r as EmailChannel, t as ConsoleC
|
|
|
26
33
|
* return templates[id] ?? { subject: id, text: JSON.stringify(data) };
|
|
27
34
|
* },
|
|
28
35
|
* retry: { maxAttempts: 3, backoff: 'exponential' },
|
|
36
|
+
* deliveryLog: new MemoryDeliveryLog(),
|
|
29
37
|
* });
|
|
30
38
|
*
|
|
31
39
|
* // Send a notification
|
|
@@ -58,6 +66,9 @@ var NotificationService = class {
|
|
|
58
66
|
emitter = new Emitter();
|
|
59
67
|
idempotencyStore;
|
|
60
68
|
idempotencyTtl;
|
|
69
|
+
deliveryLog;
|
|
70
|
+
rateLimitStore;
|
|
71
|
+
queueAdapter;
|
|
61
72
|
constructor(config = {}) {
|
|
62
73
|
this.channels = config.channels ?? [];
|
|
63
74
|
this.templateResolver = config.templates;
|
|
@@ -66,12 +77,22 @@ var NotificationService = class {
|
|
|
66
77
|
this.logger = config.logger ?? SILENT_LOGGER;
|
|
67
78
|
if (config.idempotency) {
|
|
68
79
|
this.idempotencyStore = config.idempotency.store ?? new MemoryIdempotencyStore();
|
|
69
|
-
this.idempotencyTtl = config.idempotency.ttl ??
|
|
80
|
+
this.idempotencyTtl = config.idempotency.ttl ?? 864e5;
|
|
70
81
|
} else this.idempotencyTtl = IDEMPOTENCY_DEFAULT_TTL;
|
|
82
|
+
this.deliveryLog = config.deliveryLog;
|
|
83
|
+
if (config.rateLimitStore) this.rateLimitStore = config.rateLimitStore;
|
|
84
|
+
else if (this.channels.some((ch) => this.getChannelRateLimit(ch))) this.rateLimitStore = new MemoryRateLimitStore();
|
|
85
|
+
if (config.queue) {
|
|
86
|
+
this.queueAdapter = config.queue;
|
|
87
|
+
this.queueAdapter.process(async (payload) => {
|
|
88
|
+
await this.sendDirect(payload);
|
|
89
|
+
});
|
|
90
|
+
}
|
|
71
91
|
}
|
|
72
92
|
/** Add a channel at runtime */
|
|
73
93
|
addChannel(channel) {
|
|
74
94
|
this.channels.push(channel);
|
|
95
|
+
if (!this.rateLimitStore && this.getChannelRateLimit(channel)) this.rateLimitStore = new MemoryRateLimitStore();
|
|
75
96
|
return this;
|
|
76
97
|
}
|
|
77
98
|
/** Remove a channel by name */
|
|
@@ -87,38 +108,72 @@ var NotificationService = class {
|
|
|
87
108
|
getChannelNames() {
|
|
88
109
|
return this.channels.map((c) => c.name);
|
|
89
110
|
}
|
|
111
|
+
/** Get the delivery log instance (for querying history) */
|
|
112
|
+
getDeliveryLog() {
|
|
113
|
+
return this.deliveryLog;
|
|
114
|
+
}
|
|
90
115
|
/**
|
|
91
|
-
* Send a notification to all matching channels
|
|
116
|
+
* Send a notification to all matching channels.
|
|
117
|
+
*
|
|
118
|
+
* When a queue adapter is configured, notifications are enqueued
|
|
119
|
+
* for crash-resilient delivery instead of sending immediately.
|
|
92
120
|
*
|
|
93
121
|
* Flow:
|
|
94
122
|
* 1. Emit `before:send` (awaited — listeners can block or throw to abort)
|
|
95
|
-
* 2.
|
|
96
|
-
* 3.
|
|
97
|
-
* 4.
|
|
98
|
-
* 5.
|
|
99
|
-
* 6.
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
* propagates the error to the caller. Use this for validation or rate limiting.
|
|
104
|
-
* - `after:send`, `send:success`, `send:failed` are awaited but **safe** — listener errors
|
|
105
|
-
* are caught and logged, never masking the dispatch result.
|
|
106
|
-
* - `send:retry` is emitted inside the retry callback — listener errors are caught + logged.
|
|
123
|
+
* 2. If queue is configured, enqueue and return early
|
|
124
|
+
* 3. Resolve template (if provided)
|
|
125
|
+
* 4. Filter channels by event + target list
|
|
126
|
+
* 5. Apply user preference filtering
|
|
127
|
+
* 6. Check per-channel rate limits
|
|
128
|
+
* 7. Send to all channels in parallel (with retry)
|
|
129
|
+
* 8. Record to delivery log
|
|
130
|
+
* 9. Emit `after:send` / `send:success` / `send:failed`
|
|
107
131
|
*/
|
|
108
132
|
async send(payload) {
|
|
133
|
+
if (this.queueAdapter) {
|
|
134
|
+
const enqueueOptions = payload.delay ? { delay: payload.delay } : void 0;
|
|
135
|
+
const jobId = await this.queueAdapter.enqueue(payload, enqueueOptions);
|
|
136
|
+
this.logger.debug?.(`Notification queued (job: ${jobId}${payload.delay ? `, delay: ${payload.delay}ms` : ""})`);
|
|
137
|
+
try {
|
|
138
|
+
await this.emitter.emit("send:queued", {
|
|
139
|
+
jobId,
|
|
140
|
+
payload
|
|
141
|
+
});
|
|
142
|
+
} catch {}
|
|
143
|
+
return {
|
|
144
|
+
event: payload.event,
|
|
145
|
+
results: [],
|
|
146
|
+
sent: 0,
|
|
147
|
+
failed: 0,
|
|
148
|
+
skipped: 0,
|
|
149
|
+
duration: 0,
|
|
150
|
+
queued: true
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
if (payload.delay) this.logger.warn("payload.delay requires a queue adapter — sending immediately");
|
|
154
|
+
return this.sendDirect(payload);
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Internal send pipeline (used by both direct sends and queue processor).
|
|
158
|
+
*
|
|
159
|
+
* Every code path — including skips for idempotency, quiet hours, and
|
|
160
|
+
* preferences — flows through finalize() so delivery logging and
|
|
161
|
+
* lifecycle events are always emitted.
|
|
162
|
+
*/
|
|
163
|
+
async sendDirect(payload) {
|
|
109
164
|
const start = Date.now();
|
|
110
165
|
await this.emitter.emit("before:send", payload);
|
|
111
166
|
if (payload.idempotencyKey && this.idempotencyStore) {
|
|
112
167
|
if (await this.idempotencyStore.has(payload.idempotencyKey)) {
|
|
113
168
|
this.logger.debug?.(`Duplicate notification skipped (key: ${payload.idempotencyKey})`);
|
|
114
|
-
return {
|
|
169
|
+
return this.finalize(payload, {
|
|
115
170
|
event: payload.event,
|
|
116
171
|
results: [],
|
|
117
172
|
sent: 0,
|
|
118
173
|
failed: 0,
|
|
119
174
|
skipped: 1,
|
|
120
175
|
duration: Date.now() - start
|
|
121
|
-
};
|
|
176
|
+
});
|
|
122
177
|
}
|
|
123
178
|
}
|
|
124
179
|
let enrichedPayload = payload;
|
|
@@ -145,36 +200,36 @@ var NotificationService = class {
|
|
|
145
200
|
if (prefs) {
|
|
146
201
|
if (prefs.quiet && isQuietHours(prefs.quiet)) {
|
|
147
202
|
this.logger.debug?.(`Notification skipped: quiet hours active for ${enrichedPayload.recipient.id}`);
|
|
148
|
-
return {
|
|
203
|
+
return this.finalize(payload, {
|
|
149
204
|
event: enrichedPayload.event,
|
|
150
205
|
results: [],
|
|
151
206
|
sent: 0,
|
|
152
207
|
failed: 0,
|
|
153
208
|
skipped: activeChannels.length,
|
|
154
209
|
duration: Date.now() - start
|
|
155
|
-
};
|
|
210
|
+
});
|
|
156
211
|
}
|
|
157
212
|
if (prefs.channels) activeChannels = activeChannels.filter((ch) => prefs.channels[ch.name] !== false);
|
|
158
|
-
if (prefs.events?.[enrichedPayload.event] === false) return {
|
|
213
|
+
if (prefs.events?.[enrichedPayload.event] === false) return this.finalize(payload, {
|
|
159
214
|
event: enrichedPayload.event,
|
|
160
215
|
results: [],
|
|
161
216
|
sent: 0,
|
|
162
217
|
failed: 0,
|
|
163
218
|
skipped: activeChannels.length,
|
|
164
219
|
duration: Date.now() - start
|
|
165
|
-
};
|
|
220
|
+
});
|
|
166
221
|
}
|
|
167
222
|
} catch (err) {
|
|
168
223
|
this.logger.warn("Preference resolution failed, sending to all channels", err);
|
|
169
224
|
}
|
|
170
|
-
if (!activeChannels.length) return {
|
|
225
|
+
if (!activeChannels.length) return this.finalize(payload, {
|
|
171
226
|
event: enrichedPayload.event,
|
|
172
227
|
results: [],
|
|
173
228
|
sent: 0,
|
|
174
229
|
failed: 0,
|
|
175
230
|
skipped: 0,
|
|
176
231
|
duration: Date.now() - start
|
|
177
|
-
};
|
|
232
|
+
});
|
|
178
233
|
const results = await Promise.all(activeChannels.map((channel) => this.sendToChannel(channel, enrichedPayload)));
|
|
179
234
|
const dispatch = {
|
|
180
235
|
event: enrichedPayload.event,
|
|
@@ -189,6 +244,19 @@ var NotificationService = class {
|
|
|
189
244
|
} catch (err) {
|
|
190
245
|
this.logger.warn(`Idempotency store error: ${err instanceof Error ? err.message : err}`);
|
|
191
246
|
}
|
|
247
|
+
return this.finalize(payload, dispatch);
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Single exit path for all send outcomes.
|
|
251
|
+
* Records to delivery log and emits lifecycle events regardless of
|
|
252
|
+
* whether the notification was sent, skipped, or failed.
|
|
253
|
+
*/
|
|
254
|
+
async finalize(payload, dispatch) {
|
|
255
|
+
if (this.deliveryLog) try {
|
|
256
|
+
await this.deliveryLog.record(payload, dispatch);
|
|
257
|
+
} catch (err) {
|
|
258
|
+
this.logger.warn(`Delivery log error: ${err instanceof Error ? err.message : err}`);
|
|
259
|
+
}
|
|
192
260
|
try {
|
|
193
261
|
await this.emitter.emit("after:send", dispatch);
|
|
194
262
|
if (dispatch.failed > 0) await this.emitter.emit("send:failed", dispatch);
|
|
@@ -198,8 +266,25 @@ var NotificationService = class {
|
|
|
198
266
|
}
|
|
199
267
|
return dispatch;
|
|
200
268
|
}
|
|
201
|
-
/** Send to a single channel with retry */
|
|
269
|
+
/** Send to a single channel with rate limiting and retry */
|
|
202
270
|
async sendToChannel(channel, payload) {
|
|
271
|
+
const rateLimit = this.getChannelRateLimit(channel);
|
|
272
|
+
if (rateLimit && this.rateLimitStore) {
|
|
273
|
+
if (!await this.rateLimitStore.consume(channel.name, rateLimit)) {
|
|
274
|
+
this.logger.warn(`[${channel.name}] Rate limited — skipping`);
|
|
275
|
+
this.emitter.emit("send:rate_limited", {
|
|
276
|
+
channel: channel.name,
|
|
277
|
+
event: payload.event
|
|
278
|
+
}).catch((err) => {
|
|
279
|
+
this.logger.error(`[${channel.name}] send:rate_limited listener error: ${err instanceof Error ? err.message : err}`);
|
|
280
|
+
});
|
|
281
|
+
return {
|
|
282
|
+
status: "skipped",
|
|
283
|
+
channel: channel.name,
|
|
284
|
+
error: "Rate limited"
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
}
|
|
203
288
|
const channelRetryRaw = channel.config?.retry;
|
|
204
289
|
const retryConfig = channelRetryRaw ? resolveRetryConfig(channelRetryRaw) : this.retryConfig;
|
|
205
290
|
const start = Date.now();
|
|
@@ -228,6 +313,10 @@ var NotificationService = class {
|
|
|
228
313
|
};
|
|
229
314
|
}
|
|
230
315
|
}
|
|
316
|
+
/** Extract rate limit config from a channel */
|
|
317
|
+
getChannelRateLimit(channel) {
|
|
318
|
+
return channel.config?.rateLimit;
|
|
319
|
+
}
|
|
231
320
|
/**
|
|
232
321
|
* Send multiple notifications with controlled concurrency.
|
|
233
322
|
*
|
|
@@ -366,4 +455,4 @@ var NotificationService = class {
|
|
|
366
455
|
};
|
|
367
456
|
|
|
368
457
|
//#endregion
|
|
369
|
-
export { BaseChannel, ChannelError, ConsoleChannel, EmailChannel, Emitter, IDEMPOTENCY_DEFAULT_TTL, MemoryIdempotencyStore, NotificationError, NotificationService, ProviderNotInstalledError, WebhookChannel, calculateDelay, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withRetry };
|
|
458
|
+
export { BaseChannel, ChannelError, ConsoleChannel, EmailChannel, Emitter, IDEMPOTENCY_DEFAULT_TTL, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, NotificationService, ProviderNotInstalledError, PushChannel, SmsChannel, WebhookChannel, calculateDelay, createSimpleResolver, createStatusHandler, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
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-D94B3VNX.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/channels/BaseChannel.d.ts
|
|
4
4
|
declare abstract class BaseChannel<TConfig extends ChannelConfig = ChannelConfig> implements Channel {
|
|
@@ -17,6 +17,8 @@ declare class EmailChannel extends BaseChannel<EmailChannelConfig> {
|
|
|
17
17
|
constructor(config: EmailChannelConfig);
|
|
18
18
|
/** Lazily initialize the Nodemailer transporter */
|
|
19
19
|
private getTransporter;
|
|
20
|
+
/** Fields that defaults must never override */
|
|
21
|
+
private static readonly PROTECTED_FIELDS;
|
|
20
22
|
send(payload: NotificationPayload): Promise<SendResult>;
|
|
21
23
|
/** Verify the SMTP connection (useful for health checks) */
|
|
22
24
|
verify(): Promise<boolean>;
|
|
@@ -36,4 +38,18 @@ declare class ConsoleChannel extends BaseChannel<ChannelConfig> {
|
|
|
36
38
|
send(payload: NotificationPayload): Promise<SendResult>;
|
|
37
39
|
}
|
|
38
40
|
//#endregion
|
|
39
|
-
|
|
41
|
+
//#region src/channels/sms.channel.d.ts
|
|
42
|
+
declare class SmsChannel extends BaseChannel<SmsChannelConfig> {
|
|
43
|
+
private provider;
|
|
44
|
+
constructor(config: SmsChannelConfig);
|
|
45
|
+
send(payload: NotificationPayload): Promise<SendResult>;
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
//#region src/channels/push.channel.d.ts
|
|
49
|
+
declare class PushChannel extends BaseChannel<PushChannelConfig> {
|
|
50
|
+
private provider;
|
|
51
|
+
constructor(config: PushChannelConfig);
|
|
52
|
+
send(payload: NotificationPayload): Promise<SendResult>;
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
export { EmailChannel as a, WebhookChannel as i, SmsChannel as n, BaseChannel as o, ConsoleChannel as r, PushChannel as t };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { r as ProviderNotInstalledError, t as ChannelError } from "./errors-
|
|
1
|
+
import { r as ProviderNotInstalledError, t as ChannelError } from "./errors-FYJYmfvj.mjs";
|
|
2
|
+
import { createHmac } from "node:crypto";
|
|
2
3
|
|
|
3
4
|
//#region src/channels/BaseChannel.ts
|
|
4
5
|
var BaseChannel = class {
|
|
@@ -65,7 +66,7 @@ var BaseChannel = class {
|
|
|
65
66
|
* });
|
|
66
67
|
* ```
|
|
67
68
|
*/
|
|
68
|
-
var EmailChannel = class extends BaseChannel {
|
|
69
|
+
var EmailChannel = class EmailChannel extends BaseChannel {
|
|
69
70
|
transporter = null;
|
|
70
71
|
constructor(config) {
|
|
71
72
|
super({
|
|
@@ -88,6 +89,18 @@ var EmailChannel = class extends BaseChannel {
|
|
|
88
89
|
throw new ProviderNotInstalledError("nodemailer", "npm install nodemailer");
|
|
89
90
|
}
|
|
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
|
+
]);
|
|
91
104
|
async send(payload) {
|
|
92
105
|
const { recipient, data } = payload;
|
|
93
106
|
if (!recipient.email) return {
|
|
@@ -96,11 +109,15 @@ var EmailChannel = class extends BaseChannel {
|
|
|
96
109
|
error: "No recipient email"
|
|
97
110
|
};
|
|
98
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
|
+
}
|
|
99
116
|
const mailOptions = {
|
|
117
|
+
...safeDefaults,
|
|
100
118
|
from: data.from ?? this.config.from,
|
|
101
119
|
to: recipient.email,
|
|
102
|
-
subject: data.subject ?? ""
|
|
103
|
-
...this.config.defaults
|
|
120
|
+
subject: data.subject ?? ""
|
|
104
121
|
};
|
|
105
122
|
if (data.html) mailOptions.html = data.html;
|
|
106
123
|
if (data.text) mailOptions.text = data.text;
|
|
@@ -181,7 +198,7 @@ var WebhookChannel = class extends BaseChannel {
|
|
|
181
198
|
"Content-Type": "application/json",
|
|
182
199
|
...this.config.headers
|
|
183
200
|
};
|
|
184
|
-
if (this.config.secret) headers["X-Signature-256"] = `sha256=${
|
|
201
|
+
if (this.config.secret) headers["X-Signature-256"] = `sha256=${createHmac("sha256", this.config.secret).update(body).digest("hex")}`;
|
|
185
202
|
try {
|
|
186
203
|
const response = await fetch(this.config.url, {
|
|
187
204
|
method: this.config.method ?? "POST",
|
|
@@ -243,4 +260,209 @@ var ConsoleChannel = class extends BaseChannel {
|
|
|
243
260
|
};
|
|
244
261
|
|
|
245
262
|
//#endregion
|
|
246
|
-
|
|
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 };
|