@classytic/notifications 0.0.1 → 1.2.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 +37 -0
- package/README.md +490 -280
- package/dist/channels/index.d.mts +2 -0
- package/dist/channels/index.mjs +3 -0
- package/dist/concurrency-CV_XyiBQ.d.mts +139 -0
- package/dist/console.channel-BoWi_5nH.d.mts +39 -0
- package/dist/console.channel-CfA4b_Er.mjs +246 -0
- package/dist/errors-DAIVZx_Q.mjs +36 -0
- package/dist/index.d.mts +116 -0
- package/dist/index.mjs +369 -0
- package/dist/merge-hooks-B4_uHR9x.mjs +233 -0
- package/dist/types-BnjZ7x2U.d.mts +297 -0
- package/dist/utils/index.d.mts +3 -0
- package/dist/utils/index.mjs +4 -0
- package/package.json +73 -55
- package/notifications.d.ts +0 -269
- package/src/core/channel.js +0 -71
- package/src/core/dispatcher.js +0 -73
- package/src/core/factory.js +0 -92
- package/src/index.js +0 -36
- package/src/utils/merge-hooks.js +0 -45
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
import { a as isQuietHours, c as withRetry, i as MemoryIdempotencyStore, l as Emitter, n as pMap, o as calculateDelay, r as IDEMPOTENCY_DEFAULT_TTL, s as resolveRetryConfig, t as mergeHooks } from "./merge-hooks-B4_uHR9x.mjs";
|
|
2
|
+
import { n as NotificationError, r as ProviderNotInstalledError, t as ChannelError } from "./errors-DAIVZx_Q.mjs";
|
|
3
|
+
import { i as BaseChannel, n as WebhookChannel, r as EmailChannel, t as ConsoleChannel } from "./console.channel-CfA4b_Er.mjs";
|
|
4
|
+
|
|
5
|
+
//#region src/NotificationService.ts
|
|
6
|
+
/**
|
|
7
|
+
* Notification Service
|
|
8
|
+
* @module @classytic/notifications
|
|
9
|
+
*
|
|
10
|
+
* Central orchestrator for multi-channel notifications.
|
|
11
|
+
* Routes notifications to channels, resolves templates,
|
|
12
|
+
* applies user preferences, retries on failure, and emits lifecycle events.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```typescript
|
|
16
|
+
* import { NotificationService } from '@classytic/notifications';
|
|
17
|
+
* import { EmailChannel, ConsoleChannel } from '@classytic/notifications/channels';
|
|
18
|
+
*
|
|
19
|
+
* const notifications = new NotificationService({
|
|
20
|
+
* channels: [
|
|
21
|
+
* new EmailChannel({ from: 'noreply@app.com', transport: { service: 'gmail', auth: { user, pass } } }),
|
|
22
|
+
* new ConsoleChannel(),
|
|
23
|
+
* ],
|
|
24
|
+
* templates: async (id, data) => {
|
|
25
|
+
* const templates = { welcome: { subject: `Welcome ${data.name}!`, html: `<p>Hi ${data.name}</p>` } };
|
|
26
|
+
* return templates[id] ?? { subject: id, text: JSON.stringify(data) };
|
|
27
|
+
* },
|
|
28
|
+
* retry: { maxAttempts: 3, backoff: 'exponential' },
|
|
29
|
+
* });
|
|
30
|
+
*
|
|
31
|
+
* // Send a notification
|
|
32
|
+
* const result = await notifications.send({
|
|
33
|
+
* event: 'user.created',
|
|
34
|
+
* recipient: { email: 'user@example.com', name: 'John' },
|
|
35
|
+
* data: { name: 'John' },
|
|
36
|
+
* template: 'welcome',
|
|
37
|
+
* });
|
|
38
|
+
*
|
|
39
|
+
* // Listen to lifecycle events
|
|
40
|
+
* notifications.on('send:failed', ({ channel, error }) => {
|
|
41
|
+
* alertOps(`Notification channel ${channel} failed: ${error}`);
|
|
42
|
+
* });
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
/** Silent logger (no output) */
|
|
46
|
+
const SILENT_LOGGER = {
|
|
47
|
+
info() {},
|
|
48
|
+
warn() {},
|
|
49
|
+
error() {},
|
|
50
|
+
debug() {}
|
|
51
|
+
};
|
|
52
|
+
var NotificationService = class {
|
|
53
|
+
channels = [];
|
|
54
|
+
templateResolver;
|
|
55
|
+
preferenceResolver;
|
|
56
|
+
retryConfig;
|
|
57
|
+
logger;
|
|
58
|
+
emitter = new Emitter();
|
|
59
|
+
idempotencyStore;
|
|
60
|
+
idempotencyTtl;
|
|
61
|
+
constructor(config = {}) {
|
|
62
|
+
this.channels = config.channels ?? [];
|
|
63
|
+
this.templateResolver = config.templates;
|
|
64
|
+
this.preferenceResolver = config.preferences;
|
|
65
|
+
this.retryConfig = resolveRetryConfig(config.retry);
|
|
66
|
+
this.logger = config.logger ?? SILENT_LOGGER;
|
|
67
|
+
if (config.idempotency) {
|
|
68
|
+
this.idempotencyStore = config.idempotency.store ?? new MemoryIdempotencyStore();
|
|
69
|
+
this.idempotencyTtl = config.idempotency.ttl ?? IDEMPOTENCY_DEFAULT_TTL;
|
|
70
|
+
} else this.idempotencyTtl = IDEMPOTENCY_DEFAULT_TTL;
|
|
71
|
+
}
|
|
72
|
+
/** Add a channel at runtime */
|
|
73
|
+
addChannel(channel) {
|
|
74
|
+
this.channels.push(channel);
|
|
75
|
+
return this;
|
|
76
|
+
}
|
|
77
|
+
/** Remove a channel by name */
|
|
78
|
+
removeChannel(name) {
|
|
79
|
+
this.channels = this.channels.filter((c) => c.name !== name);
|
|
80
|
+
return this;
|
|
81
|
+
}
|
|
82
|
+
/** Get a registered channel by name */
|
|
83
|
+
getChannel(name) {
|
|
84
|
+
return this.channels.find((c) => c.name === name);
|
|
85
|
+
}
|
|
86
|
+
/** List all registered channel names */
|
|
87
|
+
getChannelNames() {
|
|
88
|
+
return this.channels.map((c) => c.name);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Send a notification to all matching channels
|
|
92
|
+
*
|
|
93
|
+
* Flow:
|
|
94
|
+
* 1. Emit `before:send` (awaited — listeners can block or throw to abort)
|
|
95
|
+
* 2. Resolve template (if provided)
|
|
96
|
+
* 3. Filter channels by event + target list
|
|
97
|
+
* 4. Apply user preference filtering
|
|
98
|
+
* 5. Send to all channels in parallel (with retry)
|
|
99
|
+
* 6. Emit `after:send` / `send:success` / `send:failed` (awaited — listeners run sequentially)
|
|
100
|
+
*
|
|
101
|
+
* **Lifecycle contract:**
|
|
102
|
+
* - `before:send` is awaited and **fail-fast** — a throwing listener aborts the send and
|
|
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.
|
|
107
|
+
*/
|
|
108
|
+
async send(payload) {
|
|
109
|
+
const start = Date.now();
|
|
110
|
+
await this.emitter.emit("before:send", payload);
|
|
111
|
+
if (payload.idempotencyKey && this.idempotencyStore) {
|
|
112
|
+
if (await this.idempotencyStore.has(payload.idempotencyKey)) {
|
|
113
|
+
this.logger.debug?.(`Duplicate notification skipped (key: ${payload.idempotencyKey})`);
|
|
114
|
+
return {
|
|
115
|
+
event: payload.event,
|
|
116
|
+
results: [],
|
|
117
|
+
sent: 0,
|
|
118
|
+
failed: 0,
|
|
119
|
+
skipped: 1,
|
|
120
|
+
duration: Date.now() - start
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
let enrichedPayload = payload;
|
|
125
|
+
if (payload.template && this.templateResolver) try {
|
|
126
|
+
const rendered = await this.templateResolver(payload.template, payload.data);
|
|
127
|
+
enrichedPayload = {
|
|
128
|
+
...payload,
|
|
129
|
+
data: {
|
|
130
|
+
...payload.data,
|
|
131
|
+
...rendered
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
} catch (err) {
|
|
135
|
+
this.logger.error(`Template resolution failed for "${payload.template}"`, err);
|
|
136
|
+
throw new NotificationError(`Template "${payload.template}" failed: ${err instanceof Error ? err.message : err}`, { code: "TEMPLATE_ERROR" });
|
|
137
|
+
}
|
|
138
|
+
let activeChannels = this.channels.filter((ch) => ch.shouldHandle(payload.event));
|
|
139
|
+
if (payload.channels?.length) {
|
|
140
|
+
const targetSet = new Set(payload.channels);
|
|
141
|
+
activeChannels = activeChannels.filter((ch) => targetSet.has(ch.name));
|
|
142
|
+
}
|
|
143
|
+
if (enrichedPayload.recipient.id && this.preferenceResolver) try {
|
|
144
|
+
const prefs = await this.preferenceResolver(enrichedPayload.recipient.id, enrichedPayload.event);
|
|
145
|
+
if (prefs) {
|
|
146
|
+
if (prefs.quiet && isQuietHours(prefs.quiet)) {
|
|
147
|
+
this.logger.debug?.(`Notification skipped: quiet hours active for ${enrichedPayload.recipient.id}`);
|
|
148
|
+
return {
|
|
149
|
+
event: enrichedPayload.event,
|
|
150
|
+
results: [],
|
|
151
|
+
sent: 0,
|
|
152
|
+
failed: 0,
|
|
153
|
+
skipped: activeChannels.length,
|
|
154
|
+
duration: Date.now() - start
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
if (prefs.channels) activeChannels = activeChannels.filter((ch) => prefs.channels[ch.name] !== false);
|
|
158
|
+
if (prefs.events?.[enrichedPayload.event] === false) return {
|
|
159
|
+
event: enrichedPayload.event,
|
|
160
|
+
results: [],
|
|
161
|
+
sent: 0,
|
|
162
|
+
failed: 0,
|
|
163
|
+
skipped: activeChannels.length,
|
|
164
|
+
duration: Date.now() - start
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
} catch (err) {
|
|
168
|
+
this.logger.warn("Preference resolution failed, sending to all channels", err);
|
|
169
|
+
}
|
|
170
|
+
if (!activeChannels.length) return {
|
|
171
|
+
event: enrichedPayload.event,
|
|
172
|
+
results: [],
|
|
173
|
+
sent: 0,
|
|
174
|
+
failed: 0,
|
|
175
|
+
skipped: 0,
|
|
176
|
+
duration: Date.now() - start
|
|
177
|
+
};
|
|
178
|
+
const results = await Promise.all(activeChannels.map((channel) => this.sendToChannel(channel, enrichedPayload)));
|
|
179
|
+
const dispatch = {
|
|
180
|
+
event: enrichedPayload.event,
|
|
181
|
+
results,
|
|
182
|
+
sent: results.filter((r) => r.status === "sent").length,
|
|
183
|
+
failed: results.filter((r) => r.status === "failed").length,
|
|
184
|
+
skipped: results.filter((r) => r.status === "skipped").length,
|
|
185
|
+
duration: Date.now() - start
|
|
186
|
+
};
|
|
187
|
+
if (payload.idempotencyKey && this.idempotencyStore && dispatch.sent > 0) try {
|
|
188
|
+
await this.idempotencyStore.set(payload.idempotencyKey, this.idempotencyTtl);
|
|
189
|
+
} catch (err) {
|
|
190
|
+
this.logger.warn(`Idempotency store error: ${err instanceof Error ? err.message : err}`);
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
await this.emitter.emit("after:send", dispatch);
|
|
194
|
+
if (dispatch.failed > 0) await this.emitter.emit("send:failed", dispatch);
|
|
195
|
+
if (dispatch.sent > 0) await this.emitter.emit("send:success", dispatch);
|
|
196
|
+
} catch (err) {
|
|
197
|
+
this.logger.error(`Lifecycle listener error: ${err instanceof Error ? err.message : err}`);
|
|
198
|
+
}
|
|
199
|
+
return dispatch;
|
|
200
|
+
}
|
|
201
|
+
/** Send to a single channel with retry */
|
|
202
|
+
async sendToChannel(channel, payload) {
|
|
203
|
+
const channelRetryRaw = channel.config?.retry;
|
|
204
|
+
const retryConfig = channelRetryRaw ? resolveRetryConfig(channelRetryRaw) : this.retryConfig;
|
|
205
|
+
const start = Date.now();
|
|
206
|
+
try {
|
|
207
|
+
return {
|
|
208
|
+
...await withRetry(() => channel.send(payload), retryConfig, (attempt, error) => {
|
|
209
|
+
this.logger.warn(`[${channel.name}] Retry ${attempt}/${retryConfig.maxAttempts}: ${error.message}`);
|
|
210
|
+
this.emitter.emit("send:retry", {
|
|
211
|
+
channel: channel.name,
|
|
212
|
+
attempt,
|
|
213
|
+
error: error.message
|
|
214
|
+
}).catch((emitErr) => {
|
|
215
|
+
this.logger.error(`[${channel.name}] send:retry listener error: ${emitErr instanceof Error ? emitErr.message : emitErr}`);
|
|
216
|
+
});
|
|
217
|
+
}),
|
|
218
|
+
duration: Date.now() - start
|
|
219
|
+
};
|
|
220
|
+
} catch (err) {
|
|
221
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
222
|
+
this.logger.error(`[${channel.name}] Failed: ${message}`);
|
|
223
|
+
return {
|
|
224
|
+
status: "failed",
|
|
225
|
+
channel: channel.name,
|
|
226
|
+
error: message,
|
|
227
|
+
duration: Date.now() - start
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Send multiple notifications with controlled concurrency.
|
|
233
|
+
*
|
|
234
|
+
* Uses a worker-pool pattern: N workers pull from a shared queue,
|
|
235
|
+
* keeping the pipeline full at all times. Unlike chunk-and-wait,
|
|
236
|
+
* there's no idle time from slow outliers.
|
|
237
|
+
*
|
|
238
|
+
* Each notification goes through the full `send()` pipeline
|
|
239
|
+
* (lifecycle events, templates, preferences, retry). Errors in
|
|
240
|
+
* individual notifications are caught and reported — they never
|
|
241
|
+
* abort the batch.
|
|
242
|
+
*
|
|
243
|
+
* @example
|
|
244
|
+
* ```typescript
|
|
245
|
+
* const payloads = students.map(s => ({
|
|
246
|
+
* event: 'birthday',
|
|
247
|
+
* recipient: { id: s.id, email: s.email },
|
|
248
|
+
* data: { name: s.name },
|
|
249
|
+
* template: 'birthday',
|
|
250
|
+
* idempotencyKey: `birthday-${s.id}-2024`,
|
|
251
|
+
* }));
|
|
252
|
+
*
|
|
253
|
+
* const batch = await notifications.sendBatch(payloads, {
|
|
254
|
+
* concurrency: 20,
|
|
255
|
+
* onProgress: ({ completed, total }) => {
|
|
256
|
+
* console.log(`${completed}/${total}`);
|
|
257
|
+
* },
|
|
258
|
+
* });
|
|
259
|
+
*
|
|
260
|
+
* console.log(`Sent: ${batch.sent}, Failed: ${batch.failed}`);
|
|
261
|
+
* ```
|
|
262
|
+
*/
|
|
263
|
+
async sendBatch(payloads, options = {}) {
|
|
264
|
+
const { concurrency = 10, onProgress } = options;
|
|
265
|
+
const start = Date.now();
|
|
266
|
+
let completed = 0;
|
|
267
|
+
const results = await pMap(payloads, async (payload) => {
|
|
268
|
+
let result;
|
|
269
|
+
try {
|
|
270
|
+
result = await this.send(payload);
|
|
271
|
+
} catch (err) {
|
|
272
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
273
|
+
this.logger.error(`[batch] Notification failed for event "${payload.event}": ${message}`);
|
|
274
|
+
result = {
|
|
275
|
+
event: payload.event,
|
|
276
|
+
results: [],
|
|
277
|
+
sent: 0,
|
|
278
|
+
failed: 1,
|
|
279
|
+
skipped: 0,
|
|
280
|
+
duration: 0
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
completed++;
|
|
284
|
+
onProgress?.({
|
|
285
|
+
completed,
|
|
286
|
+
total: payloads.length,
|
|
287
|
+
result
|
|
288
|
+
});
|
|
289
|
+
return result;
|
|
290
|
+
}, { concurrency });
|
|
291
|
+
return {
|
|
292
|
+
total: payloads.length,
|
|
293
|
+
sent: results.reduce((sum, r) => sum + r.sent, 0),
|
|
294
|
+
failed: results.reduce((sum, r) => sum + r.failed, 0),
|
|
295
|
+
skipped: results.reduce((sum, r) => sum + r.skipped, 0),
|
|
296
|
+
duration: Date.now() - start,
|
|
297
|
+
results
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Create event-specific hook handlers
|
|
302
|
+
*
|
|
303
|
+
* Returns a map of event name -> handler functions that can be plugged
|
|
304
|
+
* into any event system (EventEmitter, MongoKit hooks, custom).
|
|
305
|
+
*
|
|
306
|
+
* @example
|
|
307
|
+
* ```typescript
|
|
308
|
+
* const hooks = notifications.createHooks([
|
|
309
|
+
* {
|
|
310
|
+
* event: 'user.created',
|
|
311
|
+
* getRecipient: (user) => ({ email: user.email, name: user.name }),
|
|
312
|
+
* getData: (user) => ({ name: user.name }),
|
|
313
|
+
* template: 'welcome',
|
|
314
|
+
* },
|
|
315
|
+
* {
|
|
316
|
+
* event: 'order.completed',
|
|
317
|
+
* getRecipient: (order) => ({ email: order.customer.email }),
|
|
318
|
+
* getData: (order) => ({ orderId: order.id, total: order.total }),
|
|
319
|
+
* template: 'order-confirmation',
|
|
320
|
+
* channels: ['email'], // only email for this event
|
|
321
|
+
* },
|
|
322
|
+
* ]);
|
|
323
|
+
*
|
|
324
|
+
* // Plug into EventEmitter
|
|
325
|
+
* emitter.on('user.created', hooks['user.created'][0]);
|
|
326
|
+
*
|
|
327
|
+
* // Plug into MongoKit
|
|
328
|
+
* repo.on('after:create', hooks['user.created'][0]);
|
|
329
|
+
* ```
|
|
330
|
+
*/
|
|
331
|
+
createHooks(configs) {
|
|
332
|
+
const hooks = {};
|
|
333
|
+
for (const config of configs) {
|
|
334
|
+
if (config.enabled === false) continue;
|
|
335
|
+
const handler = async (eventData) => {
|
|
336
|
+
try {
|
|
337
|
+
const recipient = await config.getRecipient(eventData);
|
|
338
|
+
if (!recipient) return void 0;
|
|
339
|
+
return await this.send({
|
|
340
|
+
event: config.event,
|
|
341
|
+
recipient,
|
|
342
|
+
data: config.getData(eventData),
|
|
343
|
+
template: config.template,
|
|
344
|
+
channels: config.channels
|
|
345
|
+
});
|
|
346
|
+
} catch (err) {
|
|
347
|
+
this.logger.error(`[hook:${config.event}] ${err instanceof Error ? err.message : err}`);
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
if (!hooks[config.event]) hooks[config.event] = [];
|
|
352
|
+
hooks[config.event].push(handler);
|
|
353
|
+
}
|
|
354
|
+
return hooks;
|
|
355
|
+
}
|
|
356
|
+
/** Listen to service lifecycle events */
|
|
357
|
+
on(event, handler) {
|
|
358
|
+
this.emitter.on(event, handler);
|
|
359
|
+
return this;
|
|
360
|
+
}
|
|
361
|
+
/** Remove an event listener */
|
|
362
|
+
off(event, handler) {
|
|
363
|
+
this.emitter.off(event, handler);
|
|
364
|
+
return this;
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
//#endregion
|
|
369
|
+
export { BaseChannel, ChannelError, ConsoleChannel, EmailChannel, Emitter, IDEMPOTENCY_DEFAULT_TTL, MemoryIdempotencyStore, NotificationError, NotificationService, ProviderNotInstalledError, WebhookChannel, calculateDelay, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withRetry };
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
//#region src/utils/emitter.ts
|
|
2
|
+
var Emitter = class {
|
|
3
|
+
handlers = /* @__PURE__ */ new Map();
|
|
4
|
+
/** Register an event handler */
|
|
5
|
+
on(event, handler) {
|
|
6
|
+
const list = this.handlers.get(event) ?? [];
|
|
7
|
+
list.push(handler);
|
|
8
|
+
this.handlers.set(event, list);
|
|
9
|
+
return this;
|
|
10
|
+
}
|
|
11
|
+
/** Remove an event handler */
|
|
12
|
+
off(event, handler) {
|
|
13
|
+
const list = this.handlers.get(event);
|
|
14
|
+
if (list) this.handlers.set(event, list.filter((h) => h !== handler));
|
|
15
|
+
return this;
|
|
16
|
+
}
|
|
17
|
+
/** Emit an event (runs handlers sequentially, awaits async) */
|
|
18
|
+
async emit(event, ...args) {
|
|
19
|
+
const list = this.handlers.get(event);
|
|
20
|
+
if (!list) return;
|
|
21
|
+
for (const handler of list) await handler(...args);
|
|
22
|
+
}
|
|
23
|
+
/** Remove all handlers for an event (or all events) */
|
|
24
|
+
removeAll(event) {
|
|
25
|
+
if (event) this.handlers.delete(event);
|
|
26
|
+
else this.handlers.clear();
|
|
27
|
+
return this;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/utils/retry.ts
|
|
33
|
+
/** Resolve retry config with defaults */
|
|
34
|
+
function resolveRetryConfig(config) {
|
|
35
|
+
return {
|
|
36
|
+
maxAttempts: config?.maxAttempts ?? 1,
|
|
37
|
+
backoff: config?.backoff ?? "exponential",
|
|
38
|
+
initialDelay: config?.initialDelay ?? 500,
|
|
39
|
+
maxDelay: config?.maxDelay ?? 3e4
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/** Calculate delay for a given attempt */
|
|
43
|
+
function calculateDelay(attempt, config) {
|
|
44
|
+
let delay;
|
|
45
|
+
switch (config.backoff) {
|
|
46
|
+
case "exponential":
|
|
47
|
+
delay = config.initialDelay * Math.pow(2, attempt - 1);
|
|
48
|
+
break;
|
|
49
|
+
case "linear":
|
|
50
|
+
delay = config.initialDelay * attempt;
|
|
51
|
+
break;
|
|
52
|
+
default: delay = config.initialDelay;
|
|
53
|
+
}
|
|
54
|
+
const jitter = delay * .25 * (Math.random() * 2 - 1);
|
|
55
|
+
delay = Math.min(delay + jitter, config.maxDelay);
|
|
56
|
+
return Math.max(0, Math.round(delay));
|
|
57
|
+
}
|
|
58
|
+
/** Sleep for a given duration */
|
|
59
|
+
function sleep(ms) {
|
|
60
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Execute a function with retry and backoff
|
|
64
|
+
*
|
|
65
|
+
* @param fn - Async function to retry
|
|
66
|
+
* @param config - Retry configuration
|
|
67
|
+
* @param onRetry - Called before each retry attempt
|
|
68
|
+
* @returns Result of fn
|
|
69
|
+
* @throws Last error after all attempts exhausted
|
|
70
|
+
*/
|
|
71
|
+
async function withRetry(fn, config, onRetry) {
|
|
72
|
+
let lastError;
|
|
73
|
+
for (let attempt = 1; attempt <= config.maxAttempts; attempt++) try {
|
|
74
|
+
return await fn();
|
|
75
|
+
} catch (err) {
|
|
76
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
77
|
+
if (attempt === config.maxAttempts) break;
|
|
78
|
+
const delay = calculateDelay(attempt, config);
|
|
79
|
+
onRetry?.(attempt, lastError);
|
|
80
|
+
await sleep(delay);
|
|
81
|
+
}
|
|
82
|
+
throw lastError;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
//#endregion
|
|
86
|
+
//#region src/utils/quiet-hours.ts
|
|
87
|
+
/**
|
|
88
|
+
* Check if the current time falls within quiet hours.
|
|
89
|
+
*
|
|
90
|
+
* Supports overnight ranges (e.g. 22:00 - 07:00).
|
|
91
|
+
* Returns false if start/end are missing or malformed.
|
|
92
|
+
*
|
|
93
|
+
* @param quiet - Quiet hours config with start, end, and optional timezone
|
|
94
|
+
* @param now - Current date (defaults to new Date(), injectable for testing)
|
|
95
|
+
*/
|
|
96
|
+
function isQuietHours(quiet, now = /* @__PURE__ */ new Date()) {
|
|
97
|
+
if (!quiet.start || !quiet.end) return false;
|
|
98
|
+
const startMinutes = parseTimeToMinutes(quiet.start);
|
|
99
|
+
const endMinutes = parseTimeToMinutes(quiet.end);
|
|
100
|
+
if (startMinutes === -1 || endMinutes === -1) return false;
|
|
101
|
+
const currentMinutes = getCurrentMinutes(now, quiet.timezone);
|
|
102
|
+
if (startMinutes <= endMinutes) return currentMinutes >= startMinutes && currentMinutes < endMinutes;
|
|
103
|
+
return currentMinutes >= startMinutes || currentMinutes < endMinutes;
|
|
104
|
+
}
|
|
105
|
+
/** Parse "HH:MM" to minutes since midnight. Returns -1 on invalid input. */
|
|
106
|
+
function parseTimeToMinutes(time) {
|
|
107
|
+
const match = time.match(/^(\d{1,2}):(\d{2})$/);
|
|
108
|
+
if (!match) return -1;
|
|
109
|
+
const hours = parseInt(match[1], 10);
|
|
110
|
+
const minutes = parseInt(match[2], 10);
|
|
111
|
+
if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return -1;
|
|
112
|
+
return hours * 60 + minutes;
|
|
113
|
+
}
|
|
114
|
+
/** Get current minutes-since-midnight in the given timezone (or UTC). */
|
|
115
|
+
function getCurrentMinutes(now, timezone) {
|
|
116
|
+
if (!timezone) return now.getUTCHours() * 60 + now.getUTCMinutes();
|
|
117
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
118
|
+
timeZone: timezone,
|
|
119
|
+
hour: "numeric",
|
|
120
|
+
minute: "numeric",
|
|
121
|
+
hour12: false
|
|
122
|
+
}).formatToParts(now);
|
|
123
|
+
const hour = parseInt(parts.find((p) => p.type === "hour")?.value ?? "0", 10);
|
|
124
|
+
const minute = parseInt(parts.find((p) => p.type === "minute")?.value ?? "0", 10);
|
|
125
|
+
return hour * 60 + minute;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
//#endregion
|
|
129
|
+
//#region src/utils/idempotency.ts
|
|
130
|
+
/**
|
|
131
|
+
* Idempotency / deduplication utilities
|
|
132
|
+
* @module @classytic/notifications/utils
|
|
133
|
+
*
|
|
134
|
+
* Prevents duplicate notification delivery using idempotency keys.
|
|
135
|
+
* Ships with an in-memory store; implement IdempotencyStore for
|
|
136
|
+
* Redis, database, or other distributed backends.
|
|
137
|
+
*/
|
|
138
|
+
/** Default TTL: 24 hours */
|
|
139
|
+
const DEFAULT_TTL = 1440 * 60 * 1e3;
|
|
140
|
+
/**
|
|
141
|
+
* In-memory idempotency store with TTL-based expiry.
|
|
142
|
+
*
|
|
143
|
+
* Suitable for single-process apps. For distributed systems,
|
|
144
|
+
* implement `IdempotencyStore` with Redis or your database.
|
|
145
|
+
*
|
|
146
|
+
* Expired entries are lazily cleaned up every `cleanupInterval` writes.
|
|
147
|
+
*/
|
|
148
|
+
var MemoryIdempotencyStore = class {
|
|
149
|
+
store = /* @__PURE__ */ new Map();
|
|
150
|
+
cleanupCounter = 0;
|
|
151
|
+
cleanupInterval;
|
|
152
|
+
constructor(options) {
|
|
153
|
+
this.cleanupInterval = options?.cleanupInterval ?? 100;
|
|
154
|
+
}
|
|
155
|
+
has(key) {
|
|
156
|
+
const expiry = this.store.get(key);
|
|
157
|
+
if (expiry === void 0) return false;
|
|
158
|
+
if (Date.now() > expiry) {
|
|
159
|
+
this.store.delete(key);
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
set(key, ttlMs) {
|
|
165
|
+
this.store.set(key, Date.now() + ttlMs);
|
|
166
|
+
this.maybeCleanup();
|
|
167
|
+
}
|
|
168
|
+
/** Number of entries (including possibly expired) */
|
|
169
|
+
get size() {
|
|
170
|
+
return this.store.size;
|
|
171
|
+
}
|
|
172
|
+
/** Remove all entries */
|
|
173
|
+
clear() {
|
|
174
|
+
this.store.clear();
|
|
175
|
+
}
|
|
176
|
+
maybeCleanup() {
|
|
177
|
+
if (++this.cleanupCounter < this.cleanupInterval) return;
|
|
178
|
+
this.cleanupCounter = 0;
|
|
179
|
+
const now = Date.now();
|
|
180
|
+
for (const [key, expiry] of this.store) if (now > expiry) this.store.delete(key);
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
/** Default TTL for idempotency keys (24 hours) */
|
|
184
|
+
const IDEMPOTENCY_DEFAULT_TTL = DEFAULT_TTL;
|
|
185
|
+
|
|
186
|
+
//#endregion
|
|
187
|
+
//#region src/utils/concurrency.ts
|
|
188
|
+
/**
|
|
189
|
+
* Map over items with controlled concurrency.
|
|
190
|
+
*
|
|
191
|
+
* Like `Promise.all(items.map(fn))` but with a max number of
|
|
192
|
+
* parallel operations. Results are returned in input order.
|
|
193
|
+
*
|
|
194
|
+
* Uses a worker-pool pattern: N workers pull from a shared index,
|
|
195
|
+
* so the pipeline stays full even when some items are slower.
|
|
196
|
+
*
|
|
197
|
+
* @param items - Array of items to process
|
|
198
|
+
* @param fn - Async function to apply to each item
|
|
199
|
+
* @param options - Concurrency options
|
|
200
|
+
* @returns Array of results in the same order as input
|
|
201
|
+
*/
|
|
202
|
+
async function pMap(items, fn, options = {}) {
|
|
203
|
+
const { concurrency = 10 } = options;
|
|
204
|
+
if (items.length === 0) return [];
|
|
205
|
+
const results = new Array(items.length);
|
|
206
|
+
let nextIndex = 0;
|
|
207
|
+
async function worker() {
|
|
208
|
+
while (nextIndex < items.length) {
|
|
209
|
+
const i = nextIndex++;
|
|
210
|
+
results[i] = await fn(items[i], i);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, () => worker()));
|
|
214
|
+
return results;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
//#endregion
|
|
218
|
+
//#region src/utils/merge-hooks.ts
|
|
219
|
+
function mergeHooks(...hookConfigs) {
|
|
220
|
+
const merged = {};
|
|
221
|
+
for (const config of hookConfigs) {
|
|
222
|
+
if (!config || typeof config !== "object") continue;
|
|
223
|
+
for (const [event, handlers] of Object.entries(config)) {
|
|
224
|
+
if (!merged[event]) merged[event] = [];
|
|
225
|
+
const handlerArray = Array.isArray(handlers) ? handlers : [handlers];
|
|
226
|
+
merged[event].push(...handlerArray);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return merged;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
//#endregion
|
|
233
|
+
export { isQuietHours as a, withRetry as c, MemoryIdempotencyStore as i, Emitter as l, pMap as n, calculateDelay as o, IDEMPOTENCY_DEFAULT_TTL as r, resolveRetryConfig as s, mergeHooks as t };
|