@classytic/notifications 2.0.0 → 2.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 +94 -0
- package/README.md +86 -0
- package/dist/channels/index.d.mts +1 -1
- package/dist/channels/index.mjs +1 -1
- package/dist/index.d.mts +58 -4
- package/dist/index.mjs +82 -9
- package/dist/providers/index.d.mts +136 -0
- package/dist/providers/index.mjs +280 -0
- package/dist/{push.channel-4mRkzrEu.d.mts → push.channel-CeUVeVfB.d.mts} +23 -1
- package/dist/{push.channel-D1FdTPUi.mjs → push.channel-DI6BNBZ4.mjs} +76 -3
- package/dist/{status-webhook-XY42DCj_.mjs → status-webhook-C69Vrc2v.mjs} +191 -31
- package/dist/{status-webhook-BDaI1BMy.d.mts → status-webhook-DxCdp0c_.d.mts} +73 -3
- package/dist/{types-D94B3VNX.d.mts → types-QIV0Th2F.d.mts} +145 -9
- package/dist/utils/index.d.mts +3 -3
- package/dist/utils/index.mjs +3 -3
- package/package.json +26 -9
- /package/dist/{errors-FYJYmfvj.mjs → errors-BxRjct-E.mjs} +0 -0
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
|
|
1
3
|
//#region src/utils/emitter.ts
|
|
2
4
|
var Emitter = class {
|
|
3
5
|
handlers = /* @__PURE__ */ new Map();
|
|
@@ -90,6 +92,12 @@ async function withRetry(fn, config, onRetry) {
|
|
|
90
92
|
* Supports overnight ranges (e.g. 22:00 - 07:00).
|
|
91
93
|
* Returns false if start/end are missing or malformed.
|
|
92
94
|
*
|
|
95
|
+
* Note: an invalid `timezone` (not a recognised IANA zone) causes
|
|
96
|
+
* `Intl.DateTimeFormat` to throw a `RangeError` — this function does not
|
|
97
|
+
* catch it. `NotificationService` calls this inside its preference try/catch
|
|
98
|
+
* and fails open (sends anyway) on such errors; standalone callers should
|
|
99
|
+
* validate the timezone or wrap the call themselves.
|
|
100
|
+
*
|
|
93
101
|
* @param quiet - Quiet hours config with start, end, and optional timezone
|
|
94
102
|
* @param now - Current date (defaults to new Date(), injectable for testing)
|
|
95
103
|
*/
|
|
@@ -134,6 +142,15 @@ function getCurrentMinutes(now, timezone) {
|
|
|
134
142
|
* Prevents duplicate notification delivery using idempotency keys.
|
|
135
143
|
* Ships with an in-memory store; implement IdempotencyStore for
|
|
136
144
|
* Redis, database, or other distributed backends.
|
|
145
|
+
*
|
|
146
|
+
* ## Distributed systems note
|
|
147
|
+
*
|
|
148
|
+
* `MemoryIdempotencyStore` is not suitable for multi-process deployments.
|
|
149
|
+
* The `has()` + `set()` pair is not atomic — two concurrent processes can
|
|
150
|
+
* both call `has()`, both see `false`, and both deliver the notification.
|
|
151
|
+
* For distributed safety, implement `IdempotencyStore` backed by a store
|
|
152
|
+
* that supports atomic `SET key value NX PX ttl` semantics (Redis, Postgres
|
|
153
|
+
* advisory locks, etc.). The interface is intentionally async to allow this.
|
|
137
154
|
*/
|
|
138
155
|
/** Default TTL: 24 hours */
|
|
139
156
|
const DEFAULT_TTL = 1440 * 60 * 1e3;
|
|
@@ -143,14 +160,23 @@ const DEFAULT_TTL = 1440 * 60 * 1e3;
|
|
|
143
160
|
* Suitable for single-process apps. For distributed systems,
|
|
144
161
|
* implement `IdempotencyStore` with Redis or your database.
|
|
145
162
|
*
|
|
146
|
-
*
|
|
163
|
+
* Cleanup strategy:
|
|
164
|
+
* - **Write-triggered**: every `cleanupInterval` writes a full pass
|
|
165
|
+
* removes expired keys (prevents unbounded growth under high write load).
|
|
166
|
+
* - **Time-triggered**: a background `setInterval` runs every
|
|
167
|
+
* `cleanupIntervalMs` so sparse-traffic apps don't accumulate stale keys
|
|
168
|
+
* indefinitely. Pass `cleanupIntervalMs: 0` to disable the timer
|
|
169
|
+
* (e.g. in tests that use fake timers).
|
|
147
170
|
*/
|
|
148
171
|
var MemoryIdempotencyStore = class {
|
|
149
172
|
store = /* @__PURE__ */ new Map();
|
|
150
|
-
|
|
151
|
-
|
|
173
|
+
writeCounter = 0;
|
|
174
|
+
writeCleanupThreshold;
|
|
175
|
+
timer;
|
|
152
176
|
constructor(options) {
|
|
153
|
-
this.
|
|
177
|
+
this.writeCleanupThreshold = options?.cleanupInterval ?? 100;
|
|
178
|
+
const intervalMs = options?.cleanupIntervalMs ?? 300 * 1e3;
|
|
179
|
+
this.timer = intervalMs > 0 ? setInterval(() => this.cleanup(), intervalMs).unref?.() ?? setInterval(() => this.cleanup(), intervalMs) : null;
|
|
154
180
|
}
|
|
155
181
|
has(key) {
|
|
156
182
|
const expiry = this.store.get(key);
|
|
@@ -163,21 +189,31 @@ var MemoryIdempotencyStore = class {
|
|
|
163
189
|
}
|
|
164
190
|
set(key, ttlMs) {
|
|
165
191
|
this.store.set(key, Date.now() + ttlMs);
|
|
166
|
-
this.
|
|
192
|
+
if (++this.writeCounter >= this.writeCleanupThreshold) {
|
|
193
|
+
this.writeCounter = 0;
|
|
194
|
+
this.cleanup();
|
|
195
|
+
}
|
|
167
196
|
}
|
|
168
|
-
/**
|
|
197
|
+
/** Remove all expired entries. Safe to call at any time. */
|
|
198
|
+
cleanup() {
|
|
199
|
+
const now = Date.now();
|
|
200
|
+
for (const [key, expiry] of this.store) if (now > expiry) this.store.delete(key);
|
|
201
|
+
}
|
|
202
|
+
/** Number of entries (including possibly expired). */
|
|
169
203
|
get size() {
|
|
170
204
|
return this.store.size;
|
|
171
205
|
}
|
|
172
|
-
/** Remove all entries */
|
|
206
|
+
/** Remove all entries and stop the background timer. */
|
|
173
207
|
clear() {
|
|
174
208
|
this.store.clear();
|
|
209
|
+
if (this.timer) clearInterval(this.timer);
|
|
175
210
|
}
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
211
|
+
/**
|
|
212
|
+
* Stop the background cleanup timer without clearing entries.
|
|
213
|
+
* Call in tests / shutdown hooks to avoid open-handle warnings.
|
|
214
|
+
*/
|
|
215
|
+
destroy() {
|
|
216
|
+
if (this.timer) clearInterval(this.timer);
|
|
181
217
|
}
|
|
182
218
|
};
|
|
183
219
|
/** Default TTL for idempotency keys (24 hours) */
|
|
@@ -268,9 +304,32 @@ function mergeHooks(...hookConfigs) {
|
|
|
268
304
|
|
|
269
305
|
//#endregion
|
|
270
306
|
//#region src/utils/delivery-log.ts
|
|
271
|
-
/**
|
|
307
|
+
/**
|
|
308
|
+
* Delivery Log / Audit Trail
|
|
309
|
+
* @module @classytic/notifications/utils
|
|
310
|
+
*
|
|
311
|
+
* Tracks what was sent to whom, when, and via which channel.
|
|
312
|
+
* Ships with an in-memory store; implement DeliveryLog for
|
|
313
|
+
* database-backed persistence.
|
|
314
|
+
*
|
|
315
|
+
* @example
|
|
316
|
+
* ```typescript
|
|
317
|
+
* import { NotificationService } from '@classytic/notifications';
|
|
318
|
+
* import { MemoryDeliveryLog } from '@classytic/notifications/utils';
|
|
319
|
+
*
|
|
320
|
+
* const log = new MemoryDeliveryLog();
|
|
321
|
+
* const service = new NotificationService({
|
|
322
|
+
* channels: [...],
|
|
323
|
+
* deliveryLog: log,
|
|
324
|
+
* });
|
|
325
|
+
*
|
|
326
|
+
* // Query delivery history
|
|
327
|
+
* const entries = log.query({ recipientId: 'u1', event: 'user.created' });
|
|
328
|
+
* ```
|
|
329
|
+
*/
|
|
330
|
+
/** Generate a collision-free log entry ID (Node 18+ `crypto.randomUUID`). */
|
|
272
331
|
function generateId$1() {
|
|
273
|
-
return
|
|
332
|
+
return randomUUID();
|
|
274
333
|
}
|
|
275
334
|
/**
|
|
276
335
|
* In-memory delivery log with query support.
|
|
@@ -332,15 +391,45 @@ var MemoryDeliveryLog = class {
|
|
|
332
391
|
resolveStatus(dispatch) {
|
|
333
392
|
if (dispatch.sent > 0 && dispatch.failed === 0) return "delivered";
|
|
334
393
|
if (dispatch.sent > 0 && dispatch.failed > 0) return "partial";
|
|
394
|
+
if (dispatch.failed === 0 && dispatch.skipped > 0) return "skipped";
|
|
335
395
|
return "failed";
|
|
336
396
|
}
|
|
337
397
|
};
|
|
338
398
|
|
|
339
399
|
//#endregion
|
|
340
400
|
//#region src/utils/queue.ts
|
|
341
|
-
/**
|
|
401
|
+
/**
|
|
402
|
+
* Queue Adapter
|
|
403
|
+
* @module @classytic/notifications/utils
|
|
404
|
+
*
|
|
405
|
+
* Optional queue layer for crash-resilient notification delivery.
|
|
406
|
+
* Without a queue, notifications are fire-and-forget (lost on crash).
|
|
407
|
+
*
|
|
408
|
+
* Ships with a MemoryQueue (dev/testing); use BullMQ, Redis, or
|
|
409
|
+
* database-backed adapters in production.
|
|
410
|
+
*
|
|
411
|
+
* @example
|
|
412
|
+
* ```typescript
|
|
413
|
+
* import { NotificationService } from '@classytic/notifications';
|
|
414
|
+
* import { MemoryQueue } from '@classytic/notifications/utils';
|
|
415
|
+
*
|
|
416
|
+
* const queue = new MemoryQueue();
|
|
417
|
+
* const service = new NotificationService({
|
|
418
|
+
* channels: [...],
|
|
419
|
+
* queue,
|
|
420
|
+
* });
|
|
421
|
+
*
|
|
422
|
+
* // Notifications are now queued before sending
|
|
423
|
+
* await service.send({ event: 'user.created', ... });
|
|
424
|
+
*
|
|
425
|
+
* // For production, implement QueueAdapter with BullMQ:
|
|
426
|
+
* // import { BullMQAdapter } from './your-bullmq-adapter';
|
|
427
|
+
* // const queue = new BullMQAdapter({ connection: { host: 'redis' } });
|
|
428
|
+
* ```
|
|
429
|
+
*/
|
|
430
|
+
/** Generate a collision-free job ID (Node 18+ `crypto.randomUUID`). */
|
|
342
431
|
function generateId() {
|
|
343
|
-
return `q-${
|
|
432
|
+
return `q-${randomUUID()}`;
|
|
344
433
|
}
|
|
345
434
|
/**
|
|
346
435
|
* In-memory queue for development and testing.
|
|
@@ -356,8 +445,12 @@ var MemoryQueue = class {
|
|
|
356
445
|
concurrency;
|
|
357
446
|
activeCount = 0;
|
|
358
447
|
delayTimers = /* @__PURE__ */ new Map();
|
|
448
|
+
defaultRetryDelay;
|
|
449
|
+
defaultMaxRetryDelay;
|
|
359
450
|
constructor(options) {
|
|
360
451
|
this.concurrency = options?.concurrency ?? 5;
|
|
452
|
+
this.defaultRetryDelay = options?.retryDelay ?? 1e3;
|
|
453
|
+
this.defaultMaxRetryDelay = options?.maxRetryDelay ?? 3e4;
|
|
361
454
|
}
|
|
362
455
|
enqueue(payload, options) {
|
|
363
456
|
const id = generateId();
|
|
@@ -367,6 +460,8 @@ var MemoryQueue = class {
|
|
|
367
460
|
status: "pending",
|
|
368
461
|
attempts: 0,
|
|
369
462
|
maxAttempts: options?.maxAttempts ?? 3,
|
|
463
|
+
retryDelay: options?.retryDelay ?? this.defaultRetryDelay,
|
|
464
|
+
maxRetryDelay: options?.maxRetryDelay ?? this.defaultMaxRetryDelay,
|
|
370
465
|
createdAt: /* @__PURE__ */ new Date(),
|
|
371
466
|
updatedAt: /* @__PURE__ */ new Date()
|
|
372
467
|
};
|
|
@@ -403,6 +498,17 @@ var MemoryQueue = class {
|
|
|
403
498
|
this.paused = false;
|
|
404
499
|
this.drain_queue();
|
|
405
500
|
}
|
|
501
|
+
/**
|
|
502
|
+
* Drain the queue: cancel delayed timers and remove all not-yet-running
|
|
503
|
+
* jobs from the pipeline.
|
|
504
|
+
*
|
|
505
|
+
* Semantics note: drained jobs (both delayed-but-unfired and pending) are
|
|
506
|
+
* marked with status `'completed'`, NOT a distinct "drained"/"cancelled"
|
|
507
|
+
* state — `QueueJobStatus` has no such value. So `'completed'` here means
|
|
508
|
+
* "no longer in the queue", which is NOT the same as "delivered". Anything
|
|
509
|
+
* that treats `completed` as proof of delivery (dashboards, metrics) should
|
|
510
|
+
* read delivery success from the delivery log, not from queue job status.
|
|
511
|
+
*/
|
|
406
512
|
drain() {
|
|
407
513
|
for (const timer of this.delayTimers.values()) clearTimeout(timer);
|
|
408
514
|
for (const [id] of this.delayTimers) {
|
|
@@ -448,17 +554,20 @@ var MemoryQueue = class {
|
|
|
448
554
|
job.status = "completed";
|
|
449
555
|
job.updatedAt = /* @__PURE__ */ new Date();
|
|
450
556
|
}).catch((err) => {
|
|
451
|
-
|
|
557
|
+
job.error = err instanceof Error ? err.message : String(err);
|
|
558
|
+
job.updatedAt = /* @__PURE__ */ new Date();
|
|
452
559
|
if (job.attempts < job.maxAttempts) {
|
|
560
|
+
const base = Math.min(job.retryDelay * Math.pow(2, job.attempts - 1), job.maxRetryDelay);
|
|
561
|
+
const jitter = base * .25 * (Math.random() * 2 - 1);
|
|
562
|
+
const delay = Math.max(0, Math.round(base + jitter));
|
|
453
563
|
job.status = "pending";
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
}
|
|
564
|
+
const timer = setTimeout(() => {
|
|
565
|
+
this.delayTimers.delete(jobId);
|
|
566
|
+
this.pending.push(jobId);
|
|
567
|
+
this.drain_queue();
|
|
568
|
+
}, delay);
|
|
569
|
+
this.delayTimers.set(jobId, timer);
|
|
570
|
+
} else job.status = "failed";
|
|
462
571
|
}).finally(() => {
|
|
463
572
|
this.activeCount--;
|
|
464
573
|
this.drain_queue();
|
|
@@ -475,15 +584,21 @@ var MemoryQueue = class {
|
|
|
475
584
|
* Replaces `${key}` patterns with values from the data object.
|
|
476
585
|
* Supports nested access: `${user.name}`.
|
|
477
586
|
*
|
|
587
|
+
* **Safe by default:** values interpolated into the `html` field are
|
|
588
|
+
* HTML-escaped to prevent injection/XSS from user-controlled data. Pass
|
|
589
|
+
* `{ escape: false }` to opt out for pre-trusted HTML. The `subject` and
|
|
590
|
+
* `text` fields are never escaped.
|
|
591
|
+
*
|
|
478
592
|
* For advanced templating (loops, conditionals, partials),
|
|
479
593
|
* plug in any engine via the `TemplateResolver` interface.
|
|
480
594
|
*/
|
|
481
|
-
function createSimpleResolver(templates) {
|
|
595
|
+
function createSimpleResolver(templates, options = {}) {
|
|
596
|
+
const escapeHtmlField = options.escape ?? true;
|
|
482
597
|
return (templateId, data) => {
|
|
483
598
|
const template = templates[templateId];
|
|
484
599
|
if (!template) throw new Error(`Template "${templateId}" not found`);
|
|
485
600
|
const result = {};
|
|
486
|
-
for (const [field, value] of Object.entries(template)) if (typeof value === "string") result[field] = interpolate(value, data);
|
|
601
|
+
for (const [field, value] of Object.entries(template)) if (typeof value === "string") result[field] = interpolate(value, data, escapeHtmlField && field === "html");
|
|
487
602
|
return result;
|
|
488
603
|
};
|
|
489
604
|
}
|
|
@@ -493,13 +608,58 @@ function getNestedValue(obj, path) {
|
|
|
493
608
|
if (current != null && typeof current === "object") return current[key];
|
|
494
609
|
}, obj);
|
|
495
610
|
}
|
|
496
|
-
/**
|
|
497
|
-
|
|
611
|
+
/**
|
|
612
|
+
* Replace `${key}` patterns with values from data.
|
|
613
|
+
* When `escape` is true, substituted values are HTML-escaped (the template
|
|
614
|
+
* skeleton is never escaped — only the interpolated value).
|
|
615
|
+
*/
|
|
616
|
+
function interpolate(template, data, escape = false) {
|
|
498
617
|
return template.replace(/\$\{([^}]+)\}/g, (_, key) => {
|
|
499
618
|
const value = getNestedValue(data, key.trim());
|
|
500
|
-
|
|
619
|
+
if (value == null) return "";
|
|
620
|
+
const str = String(value);
|
|
621
|
+
return escape ? escapeHtml(str) : str;
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Interpolate `{{key}}` / `{{ key }}` placeholders (Handlebars/Mustache style).
|
|
626
|
+
*
|
|
627
|
+
* Supports nested access: `{{ contact.email }}`.
|
|
628
|
+
* Values are HTML-escaped by default — safe to use with untrusted contact data.
|
|
629
|
+
* Use `escape: false` only for plain-text subjects or pre-sanitised HTML fragments.
|
|
630
|
+
*
|
|
631
|
+
* @example
|
|
632
|
+
* interpolateHtml('<p>Hi {{firstName}},</p>', { firstName: 'Alice' })
|
|
633
|
+
* // → '<p>Hi Alice,</p>'
|
|
634
|
+
*
|
|
635
|
+
* interpolateHtml('Hello {{ contact.email }}', { contact: { email: 'a@b.com' } })
|
|
636
|
+
* // → 'Hello a@b.com'
|
|
637
|
+
*
|
|
638
|
+
* // Strict mode: throws on missing keys (useful in tests)
|
|
639
|
+
* interpolateHtml('Hi {{name}}', {}, { strict: true })
|
|
640
|
+
* // → throws Error: Template variable "name" is not defined
|
|
641
|
+
*
|
|
642
|
+
* // Raw HTML values (opt out of escaping)
|
|
643
|
+
* interpolateHtml('<p>{{content}}</p>', { content: '<b>Bold</b>' }, { escape: false })
|
|
644
|
+
* // → '<p><b>Bold</b></p>'
|
|
645
|
+
*/
|
|
646
|
+
function interpolateHtml(template, vars, options = {}) {
|
|
647
|
+
const { escape: shouldEscape = true, strict = false } = options;
|
|
648
|
+
return template.replace(/\{\{\s*([^}]+?)\s*\}\}/g, (full, key) => {
|
|
649
|
+
const trimmed = key.trim();
|
|
650
|
+
const value = getNestedValue(vars, trimmed);
|
|
651
|
+
if (value == null) {
|
|
652
|
+
if (strict) throw new Error(`Template variable "${trimmed}" is not defined`);
|
|
653
|
+
return "";
|
|
654
|
+
}
|
|
655
|
+
const str = String(value);
|
|
656
|
+
return shouldEscape ? escapeHtml(str) : str;
|
|
501
657
|
});
|
|
502
658
|
}
|
|
659
|
+
/** Escape HTML entities to prevent XSS when interpolating untrusted values. */
|
|
660
|
+
function escapeHtml(str) {
|
|
661
|
+
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'").replace(/`/g, "`");
|
|
662
|
+
}
|
|
503
663
|
|
|
504
664
|
//#endregion
|
|
505
665
|
//#region src/utils/fallback.ts
|
|
@@ -579,4 +739,4 @@ function createStatusHandler(config = {}) {
|
|
|
579
739
|
}
|
|
580
740
|
|
|
581
741
|
//#endregion
|
|
582
|
-
export {
|
|
742
|
+
export { MemoryQueue as a, pMap as c, MemoryIdempotencyStore as d, isQuietHours as f, Emitter as g, withRetry as h, interpolateHtml as i, MemoryRateLimitStore as l, resolveRetryConfig as m, withFallback as n, MemoryDeliveryLog as o, calculateDelay as p, createSimpleResolver as r, mergeHooks as s, createStatusHandler as t, IDEMPOTENCY_DEFAULT_TTL as u };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as RetryConfig, S as ResolvedRetryConfig, d as HookMap, h as NotificationPayload, k as TemplateResolver, o as DispatchResult, u as HookHandler } from "./types-
|
|
1
|
+
import { C as RetryConfig, S as ResolvedRetryConfig, d as HookMap, h as NotificationPayload, k as TemplateResolver, o as DispatchResult, u as HookHandler } from "./types-QIV0Th2F.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/utils/merge-hooks.d.ts
|
|
4
4
|
type HookInput = Record<string, HookHandler | HookHandler[]>;
|
|
@@ -86,6 +86,12 @@ interface QuietHoursConfig {
|
|
|
86
86
|
* Supports overnight ranges (e.g. 22:00 - 07:00).
|
|
87
87
|
* Returns false if start/end are missing or malformed.
|
|
88
88
|
*
|
|
89
|
+
* Note: an invalid `timezone` (not a recognised IANA zone) causes
|
|
90
|
+
* `Intl.DateTimeFormat` to throw a `RangeError` — this function does not
|
|
91
|
+
* catch it. `NotificationService` calls this inside its preference try/catch
|
|
92
|
+
* and fails open (sends anyway) on such errors; standalone callers should
|
|
93
|
+
* validate the timezone or wrap the call themselves.
|
|
94
|
+
*
|
|
89
95
|
* @param quiet - Quiet hours config with start, end, and optional timezone
|
|
90
96
|
* @param now - Current date (defaults to new Date(), injectable for testing)
|
|
91
97
|
*/
|
|
@@ -146,16 +152,80 @@ interface TemplateDefinition {
|
|
|
146
152
|
}
|
|
147
153
|
/** Map of template ID to template definition */
|
|
148
154
|
type TemplateMap = Record<string, TemplateDefinition>;
|
|
155
|
+
/** Options for `createSimpleResolver` */
|
|
156
|
+
interface SimpleResolverOptions {
|
|
157
|
+
/**
|
|
158
|
+
* HTML-escape interpolated values in the `html` field. Default `true`.
|
|
159
|
+
*
|
|
160
|
+
* Interpolated *values* are escaped (`&`, `<`, `>`, `"`, `'`, `` ` ``);
|
|
161
|
+
* the template skeleton is left untouched, so `<h1>Hi ${name}</h1>` keeps
|
|
162
|
+
* its tags while a malicious `${name}` like `<script>…` is neutralised.
|
|
163
|
+
* This is safe-by-default — most callers feed user-controlled data
|
|
164
|
+
* (names, order details) straight into an email `html` body.
|
|
165
|
+
*
|
|
166
|
+
* The `subject` and `text` fields are NEVER HTML-escaped (they are not
|
|
167
|
+
* HTML contexts — escaping would corrupt plain text into `&` noise).
|
|
168
|
+
*
|
|
169
|
+
* Set `false` only when the `html` values are already trusted HTML
|
|
170
|
+
* fragments (e.g. pre-sanitised rich content you intentionally inline).
|
|
171
|
+
*/
|
|
172
|
+
escape?: boolean;
|
|
173
|
+
}
|
|
149
174
|
/**
|
|
150
175
|
* Simple string interpolation resolver (zero dependencies).
|
|
151
176
|
*
|
|
152
177
|
* Replaces `${key}` patterns with values from the data object.
|
|
153
178
|
* Supports nested access: `${user.name}`.
|
|
154
179
|
*
|
|
180
|
+
* **Safe by default:** values interpolated into the `html` field are
|
|
181
|
+
* HTML-escaped to prevent injection/XSS from user-controlled data. Pass
|
|
182
|
+
* `{ escape: false }` to opt out for pre-trusted HTML. The `subject` and
|
|
183
|
+
* `text` fields are never escaped.
|
|
184
|
+
*
|
|
155
185
|
* For advanced templating (loops, conditionals, partials),
|
|
156
186
|
* plug in any engine via the `TemplateResolver` interface.
|
|
157
187
|
*/
|
|
158
|
-
declare function createSimpleResolver(templates: TemplateMap): TemplateResolver;
|
|
188
|
+
declare function createSimpleResolver(templates: TemplateMap, options?: SimpleResolverOptions): TemplateResolver;
|
|
189
|
+
/** Options for `interpolateHtml` */
|
|
190
|
+
interface InterpolateOptions {
|
|
191
|
+
/**
|
|
192
|
+
* Escape HTML entities in substituted values.
|
|
193
|
+
* Default `true` — safe for HTML email bodies. Set `false` only
|
|
194
|
+
* when the template is plain text or values are already trusted HTML.
|
|
195
|
+
*
|
|
196
|
+
* Escapes: `&`, `<`, `>`, `"`, `'`, `` ` ``.
|
|
197
|
+
*/
|
|
198
|
+
escape?: boolean;
|
|
199
|
+
/**
|
|
200
|
+
* Throw when a placeholder references a key that is absent from `vars`.
|
|
201
|
+
* Default `false` — missing keys are replaced with an empty string.
|
|
202
|
+
* Enable in CI / tests to catch typos in template definitions.
|
|
203
|
+
*/
|
|
204
|
+
strict?: boolean;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Interpolate `{{key}}` / `{{ key }}` placeholders (Handlebars/Mustache style).
|
|
208
|
+
*
|
|
209
|
+
* Supports nested access: `{{ contact.email }}`.
|
|
210
|
+
* Values are HTML-escaped by default — safe to use with untrusted contact data.
|
|
211
|
+
* Use `escape: false` only for plain-text subjects or pre-sanitised HTML fragments.
|
|
212
|
+
*
|
|
213
|
+
* @example
|
|
214
|
+
* interpolateHtml('<p>Hi {{firstName}},</p>', { firstName: 'Alice' })
|
|
215
|
+
* // → '<p>Hi Alice,</p>'
|
|
216
|
+
*
|
|
217
|
+
* interpolateHtml('Hello {{ contact.email }}', { contact: { email: 'a@b.com' } })
|
|
218
|
+
* // → 'Hello a@b.com'
|
|
219
|
+
*
|
|
220
|
+
* // Strict mode: throws on missing keys (useful in tests)
|
|
221
|
+
* interpolateHtml('Hi {{name}}', {}, { strict: true })
|
|
222
|
+
* // → throws Error: Template variable "name" is not defined
|
|
223
|
+
*
|
|
224
|
+
* // Raw HTML values (opt out of escaping)
|
|
225
|
+
* interpolateHtml('<p>{{content}}</p>', { content: '<b>Bold</b>' }, { escape: false })
|
|
226
|
+
* // → '<p><b>Bold</b></p>'
|
|
227
|
+
*/
|
|
228
|
+
declare function interpolateHtml(template: string, vars: Record<string, unknown>, options?: InterpolateOptions): string;
|
|
159
229
|
//#endregion
|
|
160
230
|
//#region src/utils/fallback.d.ts
|
|
161
231
|
/** Service-like object that can send to specific channels */
|
|
@@ -265,4 +335,4 @@ interface StatusHandler {
|
|
|
265
335
|
*/
|
|
266
336
|
declare function createStatusHandler(config?: StatusHandlerConfig): StatusHandler;
|
|
267
337
|
//#endregion
|
|
268
|
-
export {
|
|
338
|
+
export { resolveRetryConfig as C, calculateDelay as S, mergeHooks as T, isQuietHours as _, createStatusHandler as a, ProviderNotInstalledError as b, InterpolateOptions as c, TemplateMap as d, createSimpleResolver as f, QuietHoursConfig as g, pMap as h, StatusUpdate as i, SimpleResolverOptions as l, PMapOptions as m, StatusHandler as n, FallbackOptions as o, interpolateHtml as p, StatusHandlerConfig as r, withFallback as s, DeliveryStatus as t, TemplateDefinition as u, ChannelError as v, withRetry as w, Emitter as x, NotificationError as y };
|