@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/CHANGELOG.md +154 -37
- package/README.md +437 -201
- package/dist/channels/index.d.mts +2 -2
- package/dist/channels/index.mjs +2 -2
- package/dist/index.d.mts +39 -18
- package/dist/index.mjs +129 -28
- package/dist/providers/index.d.mts +136 -0
- package/dist/providers/index.mjs +280 -0
- package/dist/push.channel-OkjPEVTN.mjs +519 -0
- package/dist/push.channel-YtZrCCH1.d.mts +73 -0
- package/dist/status-webhook-Bb4UoinT.d.mts +268 -0
- package/dist/status-webhook-XY42DCj_.mjs +582 -0
- package/dist/types-BMs4UhKD.d.mts +572 -0
- package/dist/utils/index.d.mts +3 -3
- package/dist/utils/index.mjs +3 -3
- package/package.json +30 -13
- package/dist/concurrency-CV_XyiBQ.d.mts +0 -139
- package/dist/console.channel-BoWi_5nH.d.mts +0 -39
- package/dist/console.channel-CfA4b_Er.mjs +0 -246
- package/dist/merge-hooks-B4_uHR9x.mjs +0 -233
- package/dist/types-BnjZ7x2U.d.mts +0 -297
- /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-YtZrCCH1.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-OkjPEVTN.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-BMs4UhKD.mjs";
|
|
2
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-YtZrCCH1.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-Bb4UoinT.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/NotificationService.d.ts
|
|
6
6
|
declare class NotificationService {
|
|
@@ -12,6 +12,10 @@ declare class NotificationService {
|
|
|
12
12
|
private emitter;
|
|
13
13
|
private idempotencyStore?;
|
|
14
14
|
private idempotencyTtl;
|
|
15
|
+
private deliveryLog?;
|
|
16
|
+
private rateLimitStore?;
|
|
17
|
+
private queueAdapter?;
|
|
18
|
+
private queueFailureMode;
|
|
15
19
|
constructor(config?: NotificationServiceConfig);
|
|
16
20
|
/** Add a channel at runtime */
|
|
17
21
|
addChannel(channel: Channel): this;
|
|
@@ -21,27 +25,44 @@ declare class NotificationService {
|
|
|
21
25
|
getChannel(name: string): Channel | undefined;
|
|
22
26
|
/** List all registered channel names */
|
|
23
27
|
getChannelNames(): string[];
|
|
28
|
+
/** Get the delivery log instance (for querying history) */
|
|
29
|
+
getDeliveryLog(): DeliveryLog | undefined;
|
|
24
30
|
/**
|
|
25
|
-
* Send a notification to all matching channels
|
|
31
|
+
* Send a notification to all matching channels.
|
|
32
|
+
*
|
|
33
|
+
* When a queue adapter is configured, notifications are enqueued
|
|
34
|
+
* for crash-resilient delivery instead of sending immediately.
|
|
26
35
|
*
|
|
27
36
|
* Flow:
|
|
28
37
|
* 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.
|
|
38
|
+
* 2. If queue is configured, enqueue and return early
|
|
39
|
+
* 3. Resolve template (if provided)
|
|
40
|
+
* 4. Filter channels by event + target list
|
|
41
|
+
* 5. Apply user preference filtering
|
|
42
|
+
* 6. Check per-channel rate limits
|
|
43
|
+
* 7. Send to all channels in parallel (with retry)
|
|
44
|
+
* 8. Record to delivery log
|
|
45
|
+
* 9. Emit `after:send` / `send:success` / `send:failed`
|
|
41
46
|
*/
|
|
42
47
|
send(payload: NotificationPayload): Promise<DispatchResult>;
|
|
43
|
-
/**
|
|
48
|
+
/**
|
|
49
|
+
* Internal send pipeline (used by both direct sends and queue processor).
|
|
50
|
+
*
|
|
51
|
+
* Every code path — including skips for idempotency, quiet hours, and
|
|
52
|
+
* preferences — flows through finalize() so delivery logging and
|
|
53
|
+
* lifecycle events are always emitted.
|
|
54
|
+
*/
|
|
55
|
+
private sendDirect;
|
|
56
|
+
/**
|
|
57
|
+
* Single exit path for all send outcomes.
|
|
58
|
+
* Records to delivery log and emits lifecycle events regardless of
|
|
59
|
+
* whether the notification was sent, skipped, or failed.
|
|
60
|
+
*/
|
|
61
|
+
private finalize;
|
|
62
|
+
/** Send to a single channel with rate limiting and retry */
|
|
44
63
|
private sendToChannel;
|
|
64
|
+
/** Extract rate limit config from a channel */
|
|
65
|
+
private getChannelRateLimit;
|
|
45
66
|
/**
|
|
46
67
|
* Send multiple notifications with controlled concurrency.
|
|
47
68
|
*
|
|
@@ -113,4 +134,4 @@ declare class NotificationService {
|
|
|
113
134
|
off(event: ServiceEvent, handler: EventHandler): this;
|
|
114
135
|
}
|
|
115
136
|
//#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 };
|
|
137
|
+
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-OkjPEVTN.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,10 @@ var NotificationService = class {
|
|
|
58
66
|
emitter = new Emitter();
|
|
59
67
|
idempotencyStore;
|
|
60
68
|
idempotencyTtl;
|
|
69
|
+
deliveryLog;
|
|
70
|
+
rateLimitStore;
|
|
71
|
+
queueAdapter;
|
|
72
|
+
queueFailureMode;
|
|
61
73
|
constructor(config = {}) {
|
|
62
74
|
this.channels = config.channels ?? [];
|
|
63
75
|
this.templateResolver = config.templates;
|
|
@@ -66,12 +78,27 @@ var NotificationService = class {
|
|
|
66
78
|
this.logger = config.logger ?? SILENT_LOGGER;
|
|
67
79
|
if (config.idempotency) {
|
|
68
80
|
this.idempotencyStore = config.idempotency.store ?? new MemoryIdempotencyStore();
|
|
69
|
-
this.idempotencyTtl = config.idempotency.ttl ??
|
|
81
|
+
this.idempotencyTtl = config.idempotency.ttl ?? 864e5;
|
|
70
82
|
} else this.idempotencyTtl = IDEMPOTENCY_DEFAULT_TTL;
|
|
83
|
+
this.deliveryLog = config.deliveryLog;
|
|
84
|
+
if (config.rateLimitStore) this.rateLimitStore = config.rateLimitStore;
|
|
85
|
+
else if (this.channels.some((ch) => this.getChannelRateLimit(ch))) this.rateLimitStore = new MemoryRateLimitStore();
|
|
86
|
+
this.queueFailureMode = config.queueFailureMode ?? "throw-on-total-failure";
|
|
87
|
+
if (config.queue) {
|
|
88
|
+
this.queueAdapter = config.queue;
|
|
89
|
+
this.queueAdapter.process(async (payload) => {
|
|
90
|
+
const dispatch = await this.sendDirect(payload);
|
|
91
|
+
if (this.queueFailureMode === "throw-on-total-failure" && dispatch.sent === 0 && dispatch.failed > 0) {
|
|
92
|
+
const summary = dispatch.results.filter((r) => r.status === "failed").map((r) => `${r.channel}: ${r.error ?? "unknown error"}`).join("; ");
|
|
93
|
+
throw new NotificationError(`Queued dispatch for "${dispatch.event}" failed on every channel: ${summary || "no detail"}`, { code: "QUEUE_DISPATCH_FAILED" });
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
}
|
|
71
97
|
}
|
|
72
98
|
/** Add a channel at runtime */
|
|
73
99
|
addChannel(channel) {
|
|
74
100
|
this.channels.push(channel);
|
|
101
|
+
if (!this.rateLimitStore && this.getChannelRateLimit(channel)) this.rateLimitStore = new MemoryRateLimitStore();
|
|
75
102
|
return this;
|
|
76
103
|
}
|
|
77
104
|
/** Remove a channel by name */
|
|
@@ -87,38 +114,72 @@ var NotificationService = class {
|
|
|
87
114
|
getChannelNames() {
|
|
88
115
|
return this.channels.map((c) => c.name);
|
|
89
116
|
}
|
|
117
|
+
/** Get the delivery log instance (for querying history) */
|
|
118
|
+
getDeliveryLog() {
|
|
119
|
+
return this.deliveryLog;
|
|
120
|
+
}
|
|
90
121
|
/**
|
|
91
|
-
* Send a notification to all matching channels
|
|
122
|
+
* Send a notification to all matching channels.
|
|
123
|
+
*
|
|
124
|
+
* When a queue adapter is configured, notifications are enqueued
|
|
125
|
+
* for crash-resilient delivery instead of sending immediately.
|
|
92
126
|
*
|
|
93
127
|
* Flow:
|
|
94
128
|
* 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.
|
|
129
|
+
* 2. If queue is configured, enqueue and return early
|
|
130
|
+
* 3. Resolve template (if provided)
|
|
131
|
+
* 4. Filter channels by event + target list
|
|
132
|
+
* 5. Apply user preference filtering
|
|
133
|
+
* 6. Check per-channel rate limits
|
|
134
|
+
* 7. Send to all channels in parallel (with retry)
|
|
135
|
+
* 8. Record to delivery log
|
|
136
|
+
* 9. Emit `after:send` / `send:success` / `send:failed`
|
|
107
137
|
*/
|
|
108
138
|
async send(payload) {
|
|
139
|
+
if (this.queueAdapter) {
|
|
140
|
+
const enqueueOptions = payload.delay ? { delay: payload.delay } : void 0;
|
|
141
|
+
const jobId = await this.queueAdapter.enqueue(payload, enqueueOptions);
|
|
142
|
+
this.logger.debug?.(`Notification queued (job: ${jobId}${payload.delay ? `, delay: ${payload.delay}ms` : ""})`);
|
|
143
|
+
try {
|
|
144
|
+
await this.emitter.emit("send:queued", {
|
|
145
|
+
jobId,
|
|
146
|
+
payload
|
|
147
|
+
});
|
|
148
|
+
} catch {}
|
|
149
|
+
return {
|
|
150
|
+
event: payload.event,
|
|
151
|
+
results: [],
|
|
152
|
+
sent: 0,
|
|
153
|
+
failed: 0,
|
|
154
|
+
skipped: 0,
|
|
155
|
+
duration: 0,
|
|
156
|
+
queued: true
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
if (payload.delay) this.logger.warn("payload.delay requires a queue adapter — sending immediately");
|
|
160
|
+
return this.sendDirect(payload);
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Internal send pipeline (used by both direct sends and queue processor).
|
|
164
|
+
*
|
|
165
|
+
* Every code path — including skips for idempotency, quiet hours, and
|
|
166
|
+
* preferences — flows through finalize() so delivery logging and
|
|
167
|
+
* lifecycle events are always emitted.
|
|
168
|
+
*/
|
|
169
|
+
async sendDirect(payload) {
|
|
109
170
|
const start = Date.now();
|
|
110
171
|
await this.emitter.emit("before:send", payload);
|
|
111
172
|
if (payload.idempotencyKey && this.idempotencyStore) {
|
|
112
173
|
if (await this.idempotencyStore.has(payload.idempotencyKey)) {
|
|
113
174
|
this.logger.debug?.(`Duplicate notification skipped (key: ${payload.idempotencyKey})`);
|
|
114
|
-
return {
|
|
175
|
+
return this.finalize(payload, {
|
|
115
176
|
event: payload.event,
|
|
116
177
|
results: [],
|
|
117
178
|
sent: 0,
|
|
118
179
|
failed: 0,
|
|
119
180
|
skipped: 1,
|
|
120
181
|
duration: Date.now() - start
|
|
121
|
-
};
|
|
182
|
+
});
|
|
122
183
|
}
|
|
123
184
|
}
|
|
124
185
|
let enrichedPayload = payload;
|
|
@@ -145,36 +206,36 @@ var NotificationService = class {
|
|
|
145
206
|
if (prefs) {
|
|
146
207
|
if (prefs.quiet && isQuietHours(prefs.quiet)) {
|
|
147
208
|
this.logger.debug?.(`Notification skipped: quiet hours active for ${enrichedPayload.recipient.id}`);
|
|
148
|
-
return {
|
|
209
|
+
return this.finalize(payload, {
|
|
149
210
|
event: enrichedPayload.event,
|
|
150
211
|
results: [],
|
|
151
212
|
sent: 0,
|
|
152
213
|
failed: 0,
|
|
153
214
|
skipped: activeChannels.length,
|
|
154
215
|
duration: Date.now() - start
|
|
155
|
-
};
|
|
216
|
+
});
|
|
156
217
|
}
|
|
157
218
|
if (prefs.channels) activeChannels = activeChannels.filter((ch) => prefs.channels[ch.name] !== false);
|
|
158
|
-
if (prefs.events?.[enrichedPayload.event] === false) return {
|
|
219
|
+
if (prefs.events?.[enrichedPayload.event] === false) return this.finalize(payload, {
|
|
159
220
|
event: enrichedPayload.event,
|
|
160
221
|
results: [],
|
|
161
222
|
sent: 0,
|
|
162
223
|
failed: 0,
|
|
163
224
|
skipped: activeChannels.length,
|
|
164
225
|
duration: Date.now() - start
|
|
165
|
-
};
|
|
226
|
+
});
|
|
166
227
|
}
|
|
167
228
|
} catch (err) {
|
|
168
229
|
this.logger.warn("Preference resolution failed, sending to all channels", err);
|
|
169
230
|
}
|
|
170
|
-
if (!activeChannels.length) return {
|
|
231
|
+
if (!activeChannels.length) return this.finalize(payload, {
|
|
171
232
|
event: enrichedPayload.event,
|
|
172
233
|
results: [],
|
|
173
234
|
sent: 0,
|
|
174
235
|
failed: 0,
|
|
175
236
|
skipped: 0,
|
|
176
237
|
duration: Date.now() - start
|
|
177
|
-
};
|
|
238
|
+
});
|
|
178
239
|
const results = await Promise.all(activeChannels.map((channel) => this.sendToChannel(channel, enrichedPayload)));
|
|
179
240
|
const dispatch = {
|
|
180
241
|
event: enrichedPayload.event,
|
|
@@ -189,6 +250,19 @@ var NotificationService = class {
|
|
|
189
250
|
} catch (err) {
|
|
190
251
|
this.logger.warn(`Idempotency store error: ${err instanceof Error ? err.message : err}`);
|
|
191
252
|
}
|
|
253
|
+
return this.finalize(payload, dispatch);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Single exit path for all send outcomes.
|
|
257
|
+
* Records to delivery log and emits lifecycle events regardless of
|
|
258
|
+
* whether the notification was sent, skipped, or failed.
|
|
259
|
+
*/
|
|
260
|
+
async finalize(payload, dispatch) {
|
|
261
|
+
if (this.deliveryLog) try {
|
|
262
|
+
await this.deliveryLog.record(payload, dispatch);
|
|
263
|
+
} catch (err) {
|
|
264
|
+
this.logger.warn(`Delivery log error: ${err instanceof Error ? err.message : err}`);
|
|
265
|
+
}
|
|
192
266
|
try {
|
|
193
267
|
await this.emitter.emit("after:send", dispatch);
|
|
194
268
|
if (dispatch.failed > 0) await this.emitter.emit("send:failed", dispatch);
|
|
@@ -198,8 +272,31 @@ var NotificationService = class {
|
|
|
198
272
|
}
|
|
199
273
|
return dispatch;
|
|
200
274
|
}
|
|
201
|
-
/** Send to a single channel with retry */
|
|
275
|
+
/** Send to a single channel with rate limiting and retry */
|
|
202
276
|
async sendToChannel(channel, payload) {
|
|
277
|
+
if (typeof channel.canSend === "function") try {
|
|
278
|
+
const preflight = channel.canSend(payload);
|
|
279
|
+
if (preflight) return preflight;
|
|
280
|
+
} catch (err) {
|
|
281
|
+
this.logger.warn(`[${channel.name}] canSend() threw, falling through to send(): ${err instanceof Error ? err.message : err}`);
|
|
282
|
+
}
|
|
283
|
+
const rateLimit = this.getChannelRateLimit(channel);
|
|
284
|
+
if (rateLimit && this.rateLimitStore) {
|
|
285
|
+
if (!await this.rateLimitStore.consume(channel.name, rateLimit)) {
|
|
286
|
+
this.logger.warn(`[${channel.name}] Rate limited — skipping`);
|
|
287
|
+
this.emitter.emit("send:rate_limited", {
|
|
288
|
+
channel: channel.name,
|
|
289
|
+
event: payload.event
|
|
290
|
+
}).catch((err) => {
|
|
291
|
+
this.logger.error(`[${channel.name}] send:rate_limited listener error: ${err instanceof Error ? err.message : err}`);
|
|
292
|
+
});
|
|
293
|
+
return {
|
|
294
|
+
status: "skipped",
|
|
295
|
+
channel: channel.name,
|
|
296
|
+
error: "Rate limited"
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
}
|
|
203
300
|
const channelRetryRaw = channel.config?.retry;
|
|
204
301
|
const retryConfig = channelRetryRaw ? resolveRetryConfig(channelRetryRaw) : this.retryConfig;
|
|
205
302
|
const start = Date.now();
|
|
@@ -228,6 +325,10 @@ var NotificationService = class {
|
|
|
228
325
|
};
|
|
229
326
|
}
|
|
230
327
|
}
|
|
328
|
+
/** Extract rate limit config from a channel */
|
|
329
|
+
getChannelRateLimit(channel) {
|
|
330
|
+
return channel.config?.rateLimit;
|
|
331
|
+
}
|
|
231
332
|
/**
|
|
232
333
|
* Send multiple notifications with controlled concurrency.
|
|
233
334
|
*
|
|
@@ -366,4 +467,4 @@ var NotificationService = class {
|
|
|
366
467
|
};
|
|
367
468
|
|
|
368
469
|
//#endregion
|
|
369
|
-
export { BaseChannel, ChannelError, ConsoleChannel, EmailChannel, Emitter, IDEMPOTENCY_DEFAULT_TTL, MemoryIdempotencyStore, NotificationError, NotificationService, ProviderNotInstalledError, WebhookChannel, calculateDelay, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withRetry };
|
|
470
|
+
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 };
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { Transporter } from "nodemailer";
|
|
2
|
+
|
|
3
|
+
//#region src/providers/email/presets.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Email provider presets — Resend, Gmail, SendGrid, Mailgun, custom SMTP.
|
|
6
|
+
*
|
|
7
|
+
* Every provider that ships today exposes an SMTP gateway, so the table
|
|
8
|
+
* here captures the constants (host / port / secure / user-source /
|
|
9
|
+
* pass-source) and leaves the variable bits (api key, app password) to
|
|
10
|
+
* the credential's `data` blob. `buildEmailTransport` reads the preset,
|
|
11
|
+
* fills in the auth tuple, and builds a `nodemailer` transport.
|
|
12
|
+
*
|
|
13
|
+
* Adding a new SMTP-based provider is one entry below. Non-SMTP API
|
|
14
|
+
* providers (Postmark API, SES API) would branch in `buildEmailTransport`
|
|
15
|
+
* BEFORE the SMTP fallback — none are shipped yet.
|
|
16
|
+
*/
|
|
17
|
+
type EmailProviderName = 'resend' | 'gmail' | 'sendgrid' | 'mailgun' | 'ses' | 'smtp';
|
|
18
|
+
interface EmailPreset {
|
|
19
|
+
/** Display label for the credential card / dropdown. */
|
|
20
|
+
displayName: string;
|
|
21
|
+
/** One-line description shown next to the option. */
|
|
22
|
+
description: string;
|
|
23
|
+
/** SMTP host. `null` ⇒ user-supplied (custom SMTP). */
|
|
24
|
+
host: string | null;
|
|
25
|
+
/** SMTP port. */
|
|
26
|
+
port: number;
|
|
27
|
+
/** TLS — `true` = implicit TLS, `false` = STARTTLS. */
|
|
28
|
+
secure: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Where the SMTP `user` comes from:
|
|
31
|
+
* - `literal:<value>` — fixed for this provider (Resend → `resend`, SendGrid → `apikey`)
|
|
32
|
+
* - `user` — read `credential.data.user` (Gmail, Mailgun, custom SMTP)
|
|
33
|
+
*/
|
|
34
|
+
userSource: string;
|
|
35
|
+
/**
|
|
36
|
+
* Where the SMTP `pass` comes from:
|
|
37
|
+
* - `apiKey` — read `credential.data.apiKey` (Resend, SendGrid)
|
|
38
|
+
* - `password` — read `credential.data.password` (Gmail, Mailgun, SMTP)
|
|
39
|
+
*/
|
|
40
|
+
passSource: 'apiKey' | 'password';
|
|
41
|
+
/**
|
|
42
|
+
* Allow user-supplied `data.host` / `data.port` / `data.secure` to
|
|
43
|
+
* override the preset defaults. `true` for providers like SES where
|
|
44
|
+
* the region picks the host (`email-smtp.{region}.amazonaws.com`).
|
|
45
|
+
* `false` for fixed-host providers (Resend, Gmail, SendGrid, Mailgun)
|
|
46
|
+
* — prevents "changed host, kept the Resend key" footguns.
|
|
47
|
+
*/
|
|
48
|
+
allowHostOverride?: boolean;
|
|
49
|
+
/** Setup instructions surfaced in the Integrations UI. */
|
|
50
|
+
setupHint: string;
|
|
51
|
+
}
|
|
52
|
+
declare const EMAIL_PRESETS: Record<EmailProviderName, EmailPreset>;
|
|
53
|
+
/** Convenience dropdown options for the credential UI. */
|
|
54
|
+
declare const EMAIL_PROVIDER_OPTIONS: {
|
|
55
|
+
value: EmailProviderName;
|
|
56
|
+
label: string;
|
|
57
|
+
}[];
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region src/providers/email/transport.d.ts
|
|
60
|
+
/**
|
|
61
|
+
* Per-org credential blob — what the host stores (encrypted) and passes
|
|
62
|
+
* back into `buildEmailTransport()` at send time.
|
|
63
|
+
*
|
|
64
|
+
* Only the fields matching `provider` are read; the rest are ignored so
|
|
65
|
+
* a host can store the union shape (a single form with conditionally
|
|
66
|
+
* relevant fields) without leaking unused values into the auth tuple.
|
|
67
|
+
*/
|
|
68
|
+
interface EmailCredentialData {
|
|
69
|
+
provider: EmailProviderName;
|
|
70
|
+
fromEmail: string;
|
|
71
|
+
fromName?: string;
|
|
72
|
+
apiKey?: string;
|
|
73
|
+
user?: string;
|
|
74
|
+
password?: string;
|
|
75
|
+
host?: string;
|
|
76
|
+
port?: string | number;
|
|
77
|
+
secure?: string | boolean;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Build a `nodemailer` `Transporter` from the credential blob.
|
|
81
|
+
*
|
|
82
|
+
* @throws `Error` when required fields are missing for the chosen provider.
|
|
83
|
+
* @throws `Error` when `nodemailer` is not installed (optional peer).
|
|
84
|
+
*/
|
|
85
|
+
declare function buildEmailTransport(data: EmailCredentialData): Promise<Transporter>;
|
|
86
|
+
/**
|
|
87
|
+
* Compose the RFC-5322 `From` header value from the credential blob.
|
|
88
|
+
* Returns `"Display Name" <email@example.com>` when `fromName` is set,
|
|
89
|
+
* otherwise just `email@example.com`.
|
|
90
|
+
*/
|
|
91
|
+
declare function buildFromHeader(data: EmailCredentialData): string;
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/providers/email/schema.d.ts
|
|
94
|
+
/**
|
|
95
|
+
* Credential field schema for the email provider.
|
|
96
|
+
*
|
|
97
|
+
* Hosts that ship a dynamic credential form (driven by a provider's
|
|
98
|
+
* `getCredentialSchema()`-style method) read this to render the right
|
|
99
|
+
* fields. Returning the UNION of all provider-specific fields keeps the
|
|
100
|
+
* form generic — the UI hides irrelevant fields based on the chosen
|
|
101
|
+
* `provider`. Only relevant fields get saved into the encrypted blob.
|
|
102
|
+
*
|
|
103
|
+
* Shape is host-agnostic (no `@classytic/social` import). Hosts that
|
|
104
|
+
* use the social registry's `CredentialField` type can structurally cast.
|
|
105
|
+
*/
|
|
106
|
+
type EmailCredentialFieldType = 'text' | 'password' | 'url' | 'select' | 'textarea';
|
|
107
|
+
interface EmailCredentialField {
|
|
108
|
+
name: string;
|
|
109
|
+
displayName: string;
|
|
110
|
+
type: EmailCredentialFieldType;
|
|
111
|
+
required: boolean;
|
|
112
|
+
placeholder?: string;
|
|
113
|
+
description?: string;
|
|
114
|
+
options?: {
|
|
115
|
+
label: string;
|
|
116
|
+
value: string;
|
|
117
|
+
}[];
|
|
118
|
+
}
|
|
119
|
+
/** Union-of-fields schema — every field appears; the UI hides what's
|
|
120
|
+
* not relevant for the chosen `provider`. */
|
|
121
|
+
declare function getEmailCredentialSchema(): EmailCredentialField[];
|
|
122
|
+
//#endregion
|
|
123
|
+
//#region src/providers/email/test.d.ts
|
|
124
|
+
type EmailTestStatus = 'OK' | 'Error';
|
|
125
|
+
interface EmailTestResult {
|
|
126
|
+
status: EmailTestStatus;
|
|
127
|
+
message: string;
|
|
128
|
+
/** Set when status === 'OK'. */
|
|
129
|
+
data?: {
|
|
130
|
+
provider: EmailCredentialData['provider'];
|
|
131
|
+
fromEmail: string;
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
declare function testEmailCredential(data: EmailCredentialData): Promise<EmailTestResult>;
|
|
135
|
+
//#endregion
|
|
136
|
+
export { EMAIL_PRESETS, EMAIL_PROVIDER_OPTIONS, type EmailCredentialData, type EmailCredentialField, type EmailCredentialFieldType, type EmailPreset, type EmailProviderName, type EmailTestResult, type EmailTestStatus, buildEmailTransport, buildFromHeader, getEmailCredentialSchema, testEmailCredential };
|