@feathers-baas/plugin-notifications 0.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/dist/index.js ADDED
@@ -0,0 +1,334 @@
1
+ // src/registry.ts
2
+ var DriverRegistry = class {
3
+ drivers = /* @__PURE__ */ new Map();
4
+ eventMap = /* @__PURE__ */ new Map();
5
+ /** Register a driver under its name. Overwrites any existing driver with the same name. */
6
+ registerDriver(driver) {
7
+ this.drivers.set(driver.name, driver);
8
+ }
9
+ /** Map a notification event to a driver name. Multiple calls for the same event add drivers. */
10
+ mapEvent(event, driverName) {
11
+ const existing = this.eventMap.get(event) ?? [];
12
+ if (!existing.includes(driverName)) {
13
+ existing.push(driverName);
14
+ }
15
+ this.eventMap.set(event, existing);
16
+ }
17
+ /** Look up a driver by name. Returns undefined if not registered. */
18
+ getDriver(name) {
19
+ return this.drivers.get(name);
20
+ }
21
+ /** Get all driver names mapped to the given event. */
22
+ getDriversForEvent(event) {
23
+ return this.eventMap.get(event) ?? [];
24
+ }
25
+ /** All registered driver names. */
26
+ listDriverNames() {
27
+ return [...this.drivers.keys()];
28
+ }
29
+ };
30
+
31
+ // src/queue/producer.ts
32
+ import { Queue } from "bullmq";
33
+ var NOTIFICATION_QUEUE_NAME = "feathers-baas:notifications";
34
+ function createNotificationQueue(redis) {
35
+ return new Queue(NOTIFICATION_QUEUE_NAME, {
36
+ connection: redis,
37
+ defaultJobOptions: {
38
+ attempts: 5,
39
+ backoff: {
40
+ type: "exponential",
41
+ delay: 1e3
42
+ // initial delay: 1s → 2s → 4s → 8s → 16s
43
+ },
44
+ removeOnComplete: { count: 100 },
45
+ removeOnFail: { count: 500 }
46
+ }
47
+ });
48
+ }
49
+ async function enqueueNotification(queue, job) {
50
+ await queue.add("send", job);
51
+ }
52
+
53
+ // src/notifier.ts
54
+ var AUTH_MANAGEMENT_EVENT_MAP = {
55
+ resendVerifySignup: "auth.resend-verify-signup",
56
+ verifySignup: "auth.verify-signup",
57
+ verifySignupSetPassword: "auth.verify-signup-set-password",
58
+ sendResetPwd: "auth.send-reset-pwd",
59
+ resetPwd: "auth.reset-pwd",
60
+ passwordChange: "auth.password-change",
61
+ identityChange: "auth.identity-change"
62
+ };
63
+ function buildAuthNotification(type, user, appUrl) {
64
+ const email = user["email"];
65
+ if (!email) return null;
66
+ switch (type) {
67
+ case "auth.verify-signup":
68
+ case "auth.resend-verify-signup": {
69
+ const token = user["verifyToken"];
70
+ const verifyUrl = `${appUrl}/verify?token=${token ?? ""}`;
71
+ return {
72
+ to: email,
73
+ channel: "email",
74
+ subject: "Verify your email address",
75
+ bodyTemplate: `
76
+ <h2>Welcome!</h2>
77
+ <p>Click the link below to verify your email address:</p>
78
+ <p><a href="<%= verifyUrl %>">Verify email</a></p>
79
+ <p>This link expires in 24 hours.</p>
80
+ `,
81
+ textTemplate: `Verify your email: <%= verifyUrl %>`,
82
+ data: { verifyUrl, user }
83
+ };
84
+ }
85
+ case "auth.send-reset-pwd": {
86
+ const token = user["resetToken"];
87
+ const resetUrl = `${appUrl}/reset-password?token=${token ?? ""}`;
88
+ return {
89
+ to: email,
90
+ channel: "email",
91
+ subject: "Reset your password",
92
+ bodyTemplate: `
93
+ <h2>Password reset requested</h2>
94
+ <p>Click the link below to reset your password:</p>
95
+ <p><a href="<%= resetUrl %>">Reset password</a></p>
96
+ <p>This link expires in 2 hours. If you did not request this, ignore this email.</p>
97
+ `,
98
+ textTemplate: `Reset your password: <%= resetUrl %>`,
99
+ data: { resetUrl, user }
100
+ };
101
+ }
102
+ case "auth.reset-pwd": {
103
+ return {
104
+ to: email,
105
+ channel: "email",
106
+ subject: "Your password has been reset",
107
+ bodyTemplate: `<p>Your password has been successfully reset. If you did not do this, please contact support immediately.</p>`,
108
+ textTemplate: `Your password has been reset. If you did not do this, please contact support.`,
109
+ data: { user }
110
+ };
111
+ }
112
+ case "auth.password-change": {
113
+ return {
114
+ to: email,
115
+ channel: "email",
116
+ subject: "Your password has been changed",
117
+ bodyTemplate: `<p>Your account password was just changed. If this was not you, please contact support immediately.</p>`,
118
+ textTemplate: `Your password was changed. Contact support if this wasn't you.`,
119
+ data: { user }
120
+ };
121
+ }
122
+ case "auth.identity-change": {
123
+ return {
124
+ to: email,
125
+ channel: "email",
126
+ subject: "Your email address is being changed",
127
+ bodyTemplate: `<p>A request was made to change your email address. Click the link to confirm.</p>`,
128
+ textTemplate: `Confirm your email change by clicking the link in the HTML email.`,
129
+ data: { user }
130
+ };
131
+ }
132
+ case "auth.verify-signup-set-password": {
133
+ const token = user["verifyToken"];
134
+ const verifyUrl = `${appUrl}/verify-set-password?token=${token ?? ""}`;
135
+ return {
136
+ to: email,
137
+ channel: "email",
138
+ subject: "Set your password",
139
+ bodyTemplate: `
140
+ <h2>Set your password</h2>
141
+ <p><a href="<%= verifyUrl %>">Set password</a></p>
142
+ `,
143
+ textTemplate: `Set your password: <%= verifyUrl %>`,
144
+ data: { verifyUrl, user }
145
+ };
146
+ }
147
+ }
148
+ }
149
+ function createDirectNotifier(opts) {
150
+ return async (type, user, _notifierOptions) => {
151
+ const eventKey = AUTH_MANAGEMENT_EVENT_MAP[type];
152
+ if (!eventKey) return;
153
+ const notification = buildAuthNotification(eventKey, user, opts.appUrl);
154
+ if (!notification) return;
155
+ const driverNames = opts.registry.getDriversForEvent(eventKey);
156
+ if (driverNames.length === 0) return;
157
+ await Promise.all(
158
+ driverNames.map(async (driverName) => {
159
+ const driver = opts.registry.getDriver(driverName);
160
+ if (!driver) return;
161
+ await driver.send(notification);
162
+ })
163
+ );
164
+ };
165
+ }
166
+ function createBullMQNotifier(opts) {
167
+ return async (type, user, _notifierOptions) => {
168
+ const eventKey = AUTH_MANAGEMENT_EVENT_MAP[type];
169
+ if (!eventKey) return;
170
+ const notification = buildAuthNotification(eventKey, user, opts.appUrl);
171
+ if (!notification) return;
172
+ const driverNames = opts.registry.getDriversForEvent(eventKey);
173
+ if (driverNames.length === 0) return;
174
+ await Promise.all(
175
+ driverNames.map(
176
+ (driverName) => enqueueNotification(opts.queue, { driverName, notification })
177
+ )
178
+ );
179
+ };
180
+ }
181
+
182
+ // src/queue/worker.ts
183
+ import { Worker } from "bullmq";
184
+ function createNotificationWorker(registry, redis, opts = {}) {
185
+ const concurrency = opts.concurrency ?? 5;
186
+ const worker = new Worker(
187
+ NOTIFICATION_QUEUE_NAME,
188
+ async (job) => {
189
+ const { driverName, notification } = job.data;
190
+ const driver = registry.getDriver(driverName);
191
+ if (!driver) {
192
+ throw new Error(`Notification driver "${driverName}" is not registered`);
193
+ }
194
+ await driver.send(notification);
195
+ },
196
+ {
197
+ connection: redis,
198
+ concurrency,
199
+ // Don't create a new redis connection per job — reuse the pool
200
+ autorun: true
201
+ }
202
+ );
203
+ worker.on("failed", (job, err) => {
204
+ const jobId = job?.id ?? "unknown";
205
+ const message = err instanceof Error ? err.message : String(err);
206
+ console.error(`[notifications] Job ${jobId} failed: ${message}`);
207
+ });
208
+ return worker;
209
+ }
210
+
211
+ // src/drivers/smtp.driver.ts
212
+ import nodemailer from "nodemailer";
213
+ import * as ejs from "ejs";
214
+ var ejsRender = ejs.render ?? ejs.render;
215
+ var SMTPDriver = class {
216
+ constructor(opts) {
217
+ this.opts = opts;
218
+ this.transporter = nodemailer.createTransport(opts.url);
219
+ }
220
+ opts;
221
+ name = "smtp";
222
+ transporter;
223
+ async send(notification) {
224
+ const html = ejsRender(notification.bodyTemplate, notification.data, { async: false });
225
+ const text = notification.textTemplate ? ejsRender(notification.textTemplate, notification.data, { async: false }) : void 0;
226
+ await this.transporter.sendMail({
227
+ from: `"${this.opts.fromName}" <${this.opts.fromAddress}>`,
228
+ to: notification.to,
229
+ subject: notification.subject ?? "(no subject)",
230
+ html,
231
+ text
232
+ });
233
+ }
234
+ /** Verify SMTP connectivity. Throws if the server is unreachable. */
235
+ async verify() {
236
+ await this.transporter.verify();
237
+ }
238
+ /** Close the underlying connection pool. */
239
+ close() {
240
+ this.transporter.close();
241
+ }
242
+ };
243
+
244
+ // src/drivers/resend.driver.ts
245
+ import { Resend } from "resend";
246
+ import * as ejs2 from "ejs";
247
+ var ejsRender2 = ejs2.render ?? ejs2.render;
248
+ var ResendDriver = class {
249
+ constructor(opts) {
250
+ this.opts = opts;
251
+ this.client = new Resend(opts.apiKey);
252
+ }
253
+ opts;
254
+ name = "resend";
255
+ client;
256
+ async send(notification) {
257
+ const html = ejsRender2(notification.bodyTemplate, notification.data, { async: false });
258
+ const text = notification.textTemplate ? ejsRender2(notification.textTemplate, notification.data, { async: false }) : void 0;
259
+ const result = await this.client.emails.send({
260
+ from: `${this.opts.fromName} <${this.opts.fromAddress}>`,
261
+ to: [notification.to],
262
+ subject: notification.subject ?? "(no subject)",
263
+ html,
264
+ text
265
+ });
266
+ if ("error" in result && result.error) {
267
+ throw new Error(`Resend error: ${result.error.message}`);
268
+ }
269
+ }
270
+ };
271
+
272
+ // src/drivers/sendgrid.driver.ts
273
+ import sgMail from "@sendgrid/mail";
274
+ import * as ejs3 from "ejs";
275
+ var ejsRender3 = ejs3.render ?? ejs3.render;
276
+ var SendGridDriver = class {
277
+ constructor(opts) {
278
+ this.opts = opts;
279
+ sgMail.setApiKey(opts.apiKey);
280
+ }
281
+ opts;
282
+ name = "sendgrid";
283
+ async send(notification) {
284
+ const html = ejsRender3(notification.bodyTemplate, notification.data, { async: false });
285
+ const text = notification.textTemplate ? ejsRender3(notification.textTemplate, notification.data, { async: false }) : void 0;
286
+ await sgMail.send({
287
+ from: { name: this.opts.fromName, email: this.opts.fromAddress },
288
+ to: notification.to,
289
+ subject: notification.subject ?? "(no subject)",
290
+ html,
291
+ ...text ? { text } : {}
292
+ });
293
+ }
294
+ };
295
+
296
+ // src/drivers/brevo.driver.ts
297
+ import { TransactionalEmailsApi, TransactionalEmailsApiApiKeys, SendSmtpEmail } from "@getbrevo/brevo";
298
+ import * as ejs4 from "ejs";
299
+ var ejsRender4 = ejs4.render ?? ejs4.render;
300
+ var BrevoDriver = class {
301
+ constructor(opts) {
302
+ this.opts = opts;
303
+ this.apiInstance = new TransactionalEmailsApi();
304
+ this.apiInstance.setApiKey(TransactionalEmailsApiApiKeys.apiKey, opts.apiKey);
305
+ }
306
+ opts;
307
+ name = "brevo";
308
+ apiInstance;
309
+ async send(notification) {
310
+ const html = ejsRender4(notification.bodyTemplate, notification.data, { async: false });
311
+ const text = notification.textTemplate ? ejsRender4(notification.textTemplate, notification.data, { async: false }) : void 0;
312
+ const email = new SendSmtpEmail();
313
+ email.sender = { name: this.opts.fromName, email: this.opts.fromAddress };
314
+ email.to = [{ email: notification.to }];
315
+ email.subject = notification.subject ?? "(no subject)";
316
+ email.htmlContent = html;
317
+ if (text) email.textContent = text;
318
+ await this.apiInstance.sendTransacEmail(email);
319
+ }
320
+ };
321
+ export {
322
+ BrevoDriver,
323
+ DriverRegistry,
324
+ NOTIFICATION_QUEUE_NAME,
325
+ ResendDriver,
326
+ SMTPDriver,
327
+ SendGridDriver,
328
+ createBullMQNotifier,
329
+ createDirectNotifier,
330
+ createNotificationQueue,
331
+ createNotificationWorker,
332
+ enqueueNotification
333
+ };
334
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/registry.ts","../src/queue/producer.ts","../src/notifier.ts","../src/queue/worker.ts","../src/drivers/smtp.driver.ts","../src/drivers/resend.driver.ts","../src/drivers/sendgrid.driver.ts","../src/drivers/brevo.driver.ts"],"sourcesContent":["// Generated by feathers-baas. Safe to edit.\nimport type { NotifierDriver, NotificationEvent } from './types.js'\n\n/**\n * DriverRegistry maps event keys to the list of drivers that should handle\n * that event.\n *\n * A single driver instance can handle multiple events (e.g. the SMTP driver\n * handles all auth.* email events).\n *\n * @example\n * ```ts\n * const registry = new DriverRegistry()\n * registry.registerDriver(smtpDriver)\n * registry.mapEvent('auth.verify-signup', 'smtp')\n * registry.mapEvent('auth.send-reset-pwd', 'smtp')\n * ```\n */\nexport class DriverRegistry {\n private readonly drivers = new Map<string, NotifierDriver>()\n private readonly eventMap = new Map<NotificationEvent, string[]>()\n\n /** Register a driver under its name. Overwrites any existing driver with the same name. */\n registerDriver(driver: NotifierDriver): void {\n this.drivers.set(driver.name, driver)\n }\n\n /** Map a notification event to a driver name. Multiple calls for the same event add drivers. */\n mapEvent(event: NotificationEvent, driverName: string): void {\n const existing = this.eventMap.get(event) ?? []\n if (!existing.includes(driverName)) {\n existing.push(driverName)\n }\n this.eventMap.set(event, existing)\n }\n\n /** Look up a driver by name. Returns undefined if not registered. */\n getDriver(name: string): NotifierDriver | undefined {\n return this.drivers.get(name)\n }\n\n /** Get all driver names mapped to the given event. */\n getDriversForEvent(event: NotificationEvent): string[] {\n return this.eventMap.get(event) ?? []\n }\n\n /** All registered driver names. */\n listDriverNames(): string[] {\n return [...this.drivers.keys()]\n }\n}\n","// Generated by feathers-baas. Safe to edit.\nimport { Queue } from 'bullmq'\nimport type { Redis } from 'ioredis'\nimport type { NotificationJob } from '../types.js'\n\nexport const NOTIFICATION_QUEUE_NAME = 'feathers-baas:notifications'\n\n/**\n * Create a BullMQ Queue instance for notification jobs.\n *\n * @example\n * ```ts\n * const redis = new Redis(process.env.REDIS_URL)\n * const queue = createNotificationQueue(redis)\n * await enqueueNotification(queue, { driverName: 'smtp', notification: { ... } })\n * ```\n */\nexport function createNotificationQueue(redis: Redis): Queue<NotificationJob> {\n return new Queue<NotificationJob>(NOTIFICATION_QUEUE_NAME, {\n connection: redis,\n defaultJobOptions: {\n attempts: 5,\n backoff: {\n type: 'exponential',\n delay: 1_000, // initial delay: 1s → 2s → 4s → 8s → 16s\n },\n removeOnComplete: { count: 100 },\n removeOnFail: { count: 500 },\n },\n })\n}\n\n/**\n * Enqueue a notification job.\n *\n * @param queue BullMQ Queue instance from createNotificationQueue()\n * @param job Job payload { driverName, notification }\n */\nexport async function enqueueNotification(\n queue: Queue<NotificationJob>,\n job: NotificationJob,\n): Promise<void> {\n await queue.add('send', job)\n}\n","// Generated by feathers-baas. Safe to edit.\nimport type { Queue } from 'bullmq'\nimport type { NotificationJob, Notification, AuthNotificationEvent } from './types.js'\nimport { enqueueNotification } from './queue/producer.js'\nimport type { DriverRegistry } from './registry.js'\n\n/**\n * Auth-management notification types mapped to feathers-baas event keys.\n * feathers-authentication-management passes these type strings to the notifier.\n */\nconst AUTH_MANAGEMENT_EVENT_MAP: Record<string, AuthNotificationEvent> = {\n resendVerifySignup: 'auth.resend-verify-signup',\n verifySignup: 'auth.verify-signup',\n verifySignupSetPassword: 'auth.verify-signup-set-password',\n sendResetPwd: 'auth.send-reset-pwd',\n resetPwd: 'auth.reset-pwd',\n passwordChange: 'auth.password-change',\n identityChange: 'auth.identity-change',\n}\n\n/**\n * Build a default Notification payload for each auth event type.\n * Templates use EJS — `<%= variable %>` for output, `<% code %>` for logic.\n */\nfunction buildAuthNotification(\n type: AuthNotificationEvent,\n user: Record<string, unknown>,\n appUrl: string,\n): Notification | null {\n const email = user['email'] as string\n if (!email) return null\n\n switch (type) {\n case 'auth.verify-signup':\n case 'auth.resend-verify-signup': {\n const token = user['verifyToken'] as string | undefined\n const verifyUrl = `${appUrl}/verify?token=${token ?? ''}`\n return {\n to: email,\n channel: 'email',\n subject: 'Verify your email address',\n bodyTemplate: `\n <h2>Welcome!</h2>\n <p>Click the link below to verify your email address:</p>\n <p><a href=\"<%= verifyUrl %>\">Verify email</a></p>\n <p>This link expires in 24 hours.</p>\n `,\n textTemplate: `Verify your email: <%= verifyUrl %>`,\n data: { verifyUrl, user },\n }\n }\n\n case 'auth.send-reset-pwd': {\n const token = user['resetToken'] as string | undefined\n const resetUrl = `${appUrl}/reset-password?token=${token ?? ''}`\n return {\n to: email,\n channel: 'email',\n subject: 'Reset your password',\n bodyTemplate: `\n <h2>Password reset requested</h2>\n <p>Click the link below to reset your password:</p>\n <p><a href=\"<%= resetUrl %>\">Reset password</a></p>\n <p>This link expires in 2 hours. If you did not request this, ignore this email.</p>\n `,\n textTemplate: `Reset your password: <%= resetUrl %>`,\n data: { resetUrl, user },\n }\n }\n\n case 'auth.reset-pwd': {\n return {\n to: email,\n channel: 'email',\n subject: 'Your password has been reset',\n bodyTemplate: `<p>Your password has been successfully reset. If you did not do this, please contact support immediately.</p>`,\n textTemplate: `Your password has been reset. If you did not do this, please contact support.`,\n data: { user },\n }\n }\n\n case 'auth.password-change': {\n return {\n to: email,\n channel: 'email',\n subject: 'Your password has been changed',\n bodyTemplate: `<p>Your account password was just changed. If this was not you, please contact support immediately.</p>`,\n textTemplate: `Your password was changed. Contact support if this wasn't you.`,\n data: { user },\n }\n }\n\n case 'auth.identity-change': {\n return {\n to: email,\n channel: 'email',\n subject: 'Your email address is being changed',\n bodyTemplate: `<p>A request was made to change your email address. Click the link to confirm.</p>`,\n textTemplate: `Confirm your email change by clicking the link in the HTML email.`,\n data: { user },\n }\n }\n\n case 'auth.verify-signup-set-password': {\n const token = user['verifyToken'] as string | undefined\n const verifyUrl = `${appUrl}/verify-set-password?token=${token ?? ''}`\n return {\n to: email,\n channel: 'email',\n subject: 'Set your password',\n bodyTemplate: `\n <h2>Set your password</h2>\n <p><a href=\"<%= verifyUrl %>\">Set password</a></p>\n `,\n textTemplate: `Set your password: <%= verifyUrl %>`,\n data: { verifyUrl, user },\n }\n }\n }\n}\n\nexport type NotifierFn = (\n type: string,\n user: Record<string, unknown>,\n notifierOptions: Record<string, unknown>,\n) => Promise<void>\n\nexport interface BullMQNotifierOptions {\n /** BullMQ Queue instance — from createNotificationQueue(). */\n queue: Queue<NotificationJob>\n /** Driver registry — used to determine which drivers handle each event. */\n registry: DriverRegistry\n /**\n * Public base URL of the app, e.g. https://api.example.com\n * Used to construct verification / reset URLs in email templates.\n */\n appUrl: string\n}\n\n/**\n * Create a notifier function compatible with feathers-authentication-management.\n *\n * When an auth event fires (verifySignup, sendResetPwd, etc.), this notifier:\n * 1. Maps the event type to a feathers-baas notification event key\n * 2. Looks up all registered drivers for that event\n * 3. Enqueues one BullMQ job per driver\n * 4. Returns immediately — delivery is asynchronous\n *\n * Wire into the app:\n * ```ts\n * app.set('notifier', createBullMQNotifier({ queue, registry, appUrl }))\n * ```\n */\nexport interface DirectNotifierOptions {\n /** Driver registry — used to determine which drivers handle each event. */\n registry: DriverRegistry\n /** Public base URL of the app. */\n appUrl: string\n}\n\n/**\n * Create a notifier that sends notifications directly via the driver (no queue).\n * Use this when Redis/BullMQ is not available — suitable for API-based drivers\n * (Brevo, Resend, SendGrid) in development or low-traffic environments.\n */\nexport function createDirectNotifier(opts: DirectNotifierOptions): NotifierFn {\n return async (type, user, _notifierOptions) => {\n const eventKey = AUTH_MANAGEMENT_EVENT_MAP[type]\n if (!eventKey) return\n\n const notification = buildAuthNotification(eventKey, user, opts.appUrl)\n if (!notification) return\n\n const driverNames = opts.registry.getDriversForEvent(eventKey)\n if (driverNames.length === 0) return\n\n await Promise.all(\n driverNames.map(async (driverName) => {\n const driver = opts.registry.getDriver(driverName)\n if (!driver) return\n await driver.send(notification)\n }),\n )\n }\n}\n\nexport function createBullMQNotifier(opts: BullMQNotifierOptions): NotifierFn {\n return async (type, user, _notifierOptions) => {\n const eventKey = AUTH_MANAGEMENT_EVENT_MAP[type]\n if (!eventKey) return // Unknown event type — no-op\n\n const notification = buildAuthNotification(eventKey, user, opts.appUrl)\n if (!notification) return // Missing required user fields — no-op\n\n const driverNames = opts.registry.getDriversForEvent(eventKey)\n if (driverNames.length === 0) return // No drivers configured for this event\n\n await Promise.all(\n driverNames.map((driverName) =>\n enqueueNotification(opts.queue, { driverName, notification }),\n ),\n )\n }\n}\n","// Generated by feathers-baas. Safe to edit.\nimport { Worker } from 'bullmq'\nimport type { Redis } from 'ioredis'\nimport type { DriverRegistry } from '../registry.js'\nimport type { NotificationJob } from '../types.js'\nimport { NOTIFICATION_QUEUE_NAME } from './producer.js'\n\nexport interface WorkerOptions {\n /** BullMQ concurrency — number of jobs processed in parallel. */\n concurrency?: number\n}\n\n/**\n * Create and start the BullMQ worker that processes notification jobs.\n *\n * The worker looks up the driver from the registry by name, renders the\n * EJS template, and calls driver.send(). BullMQ handles retries with\n * exponential back-off automatically.\n *\n * Call worker.close() during graceful shutdown to drain in-flight jobs.\n *\n * @example\n * ```ts\n * const worker = createNotificationWorker(registry, redis, { concurrency: 5 })\n *\n * process.on('SIGTERM', async () => {\n * await worker.close()\n * })\n * ```\n */\nexport function createNotificationWorker(\n registry: DriverRegistry,\n redis: Redis,\n opts: WorkerOptions = {},\n): Worker<NotificationJob> {\n const concurrency = opts.concurrency ?? 5\n\n const worker = new Worker<NotificationJob>(\n NOTIFICATION_QUEUE_NAME,\n async (job) => {\n const { driverName, notification } = job.data\n\n const driver = registry.getDriver(driverName)\n if (!driver) {\n throw new Error(`Notification driver \"${driverName}\" is not registered`)\n }\n\n await driver.send(notification)\n },\n {\n connection: redis,\n concurrency,\n // Don't create a new redis connection per job — reuse the pool\n autorun: true,\n },\n )\n\n worker.on('failed', (job, err) => {\n // BullMQ handles retries; this is just for observability\n const jobId = job?.id ?? 'unknown'\n const message = err instanceof Error ? err.message : String(err)\n console.error(`[notifications] Job ${jobId} failed: ${message}`)\n })\n\n return worker\n}\n","// Generated by feathers-baas. Safe to edit.\nimport nodemailer from 'nodemailer'\nimport * as ejs from 'ejs'\nimport type { NotifierDriver, Notification } from '../types.js'\n\n// ejs is a CommonJS module — alias the render function defensively\nconst ejsRender = (ejs as unknown as { render?: typeof ejs.render }).render ?? ejs.render\n\nexport interface SMTPDriverOptions {\n /** SMTP connection URL, e.g. smtp://user:pass@mail.example.com:587 */\n url: string\n /** Display name shown in the From field. */\n fromName: string\n /** Email address shown in the From field. */\n fromAddress: string\n}\n\n/**\n * Email driver backed by nodemailer over SMTP.\n * Templates are rendered with EJS at send time.\n *\n * Use this driver for self-hosted SMTP servers (Postfix, Mailtrap, etc.).\n * For transactional email services, prefer ResendDriver.\n */\nexport class SMTPDriver implements NotifierDriver {\n readonly name = 'smtp'\n\n private readonly transporter: nodemailer.Transporter\n\n constructor(private readonly opts: SMTPDriverOptions) {\n this.transporter = nodemailer.createTransport(opts.url)\n }\n\n async send(notification: Notification): Promise<void> {\n const html = ejsRender(notification.bodyTemplate, notification.data, { async: false })\n const text = notification.textTemplate\n ? ejsRender(notification.textTemplate, notification.data, { async: false })\n : undefined\n\n await this.transporter.sendMail({\n from: `\"${this.opts.fromName}\" <${this.opts.fromAddress}>`,\n to: notification.to,\n subject: notification.subject ?? '(no subject)',\n html,\n text,\n })\n }\n\n /** Verify SMTP connectivity. Throws if the server is unreachable. */\n async verify(): Promise<void> {\n await this.transporter.verify()\n }\n\n /** Close the underlying connection pool. */\n close(): void {\n this.transporter.close()\n }\n}\n","// Generated by feathers-baas. Safe to edit.\nimport { Resend } from 'resend'\nimport * as ejs from 'ejs'\nimport type { NotifierDriver, Notification } from '../types.js'\n\nconst ejsRender = (ejs as unknown as { render?: typeof ejs.render }).render ?? ejs.render\n\nexport interface ResendDriverOptions {\n /** Resend API key (from https://resend.com/api-keys). */\n apiKey: string\n /** Display name shown in the From field. */\n fromName: string\n /** Verified sender address. Must be a verified domain in your Resend account. */\n fromAddress: string\n}\n\n/**\n * Email driver backed by the Resend transactional email API.\n * Templates are rendered with EJS at send time.\n *\n * Resend offers generous free tier and excellent deliverability,\n * making it the recommended choice for new projects.\n */\nexport class ResendDriver implements NotifierDriver {\n readonly name = 'resend'\n\n private readonly client: Resend\n\n constructor(private readonly opts: ResendDriverOptions) {\n this.client = new Resend(opts.apiKey)\n }\n\n async send(notification: Notification): Promise<void> {\n const html = ejsRender(notification.bodyTemplate, notification.data, { async: false })\n const text = notification.textTemplate\n ? ejsRender(notification.textTemplate, notification.data, { async: false })\n : undefined\n\n const result = await this.client.emails.send({\n from: `${this.opts.fromName} <${this.opts.fromAddress}>`,\n to: [notification.to],\n subject: notification.subject ?? '(no subject)',\n html,\n text,\n })\n\n if ('error' in result && result.error) {\n throw new Error(`Resend error: ${result.error.message}`)\n }\n }\n}\n","// Generated by feathers-baas. Safe to edit.\nimport sgMail from '@sendgrid/mail'\nimport * as ejs from 'ejs'\nimport type { NotifierDriver, Notification } from '../types.js'\n\n// ejs is a CommonJS module — alias the render function defensively\nconst ejsRender = (ejs as unknown as { render?: typeof ejs.render }).render ?? ejs.render\n\nexport interface SendGridDriverOptions {\n /** SendGrid API key (from https://app.sendgrid.com/settings/api_keys). */\n apiKey: string\n /** Display name shown in the From field. */\n fromName: string\n /** Verified sender address. Must be verified in your SendGrid account. */\n fromAddress: string\n}\n\n/**\n * Email driver backed by the SendGrid API.\n * Templates are rendered with EJS at send time.\n */\nexport class SendGridDriver implements NotifierDriver {\n readonly name = 'sendgrid'\n\n constructor(private readonly opts: SendGridDriverOptions) {\n sgMail.setApiKey(opts.apiKey)\n }\n\n async send(notification: Notification): Promise<void> {\n const html = ejsRender(notification.bodyTemplate, notification.data, { async: false })\n const text = notification.textTemplate\n ? ejsRender(notification.textTemplate, notification.data, { async: false })\n : undefined\n\n await sgMail.send({\n from: { name: this.opts.fromName, email: this.opts.fromAddress },\n to: notification.to,\n subject: notification.subject ?? '(no subject)',\n html,\n ...(text ? { text } : {}),\n })\n }\n}\n","// Generated by feathers-baas. Safe to edit.\nimport { TransactionalEmailsApi, TransactionalEmailsApiApiKeys, SendSmtpEmail } from '@getbrevo/brevo'\nimport * as ejs from 'ejs'\nimport type { NotifierDriver, Notification } from '../types.js'\n\n// ejs is a CommonJS module — alias the render function defensively\nconst ejsRender = (ejs as unknown as { render?: typeof ejs.render }).render ?? ejs.render\n\nexport interface BrevoDriverOptions {\n /** Brevo API key (from https://app.brevo.com/settings/keys/api). */\n apiKey: string\n /** Display name shown in the From field. */\n fromName: string\n /** Verified sender address. Must be verified in your Brevo account. */\n fromAddress: string\n}\n\n/**\n * Email driver backed by the Brevo (formerly Sendinblue) Transactional Email API.\n * Templates are rendered with EJS at send time.\n */\nexport class BrevoDriver implements NotifierDriver {\n readonly name = 'brevo'\n\n private readonly apiInstance: TransactionalEmailsApi\n\n constructor(private readonly opts: BrevoDriverOptions) {\n this.apiInstance = new TransactionalEmailsApi()\n this.apiInstance.setApiKey(TransactionalEmailsApiApiKeys.apiKey, opts.apiKey)\n }\n\n async send(notification: Notification): Promise<void> {\n const html = ejsRender(notification.bodyTemplate, notification.data, { async: false })\n const text = notification.textTemplate\n ? ejsRender(notification.textTemplate, notification.data, { async: false })\n : undefined\n\n const email = new SendSmtpEmail()\n email.sender = { name: this.opts.fromName, email: this.opts.fromAddress }\n email.to = [{ email: notification.to }]\n email.subject = notification.subject ?? '(no subject)'\n email.htmlContent = html\n if (text) email.textContent = text\n\n await this.apiInstance.sendTransacEmail(email)\n }\n}\n"],"mappings":";AAkBO,IAAM,iBAAN,MAAqB;AAAA,EACT,UAAU,oBAAI,IAA4B;AAAA,EAC1C,WAAW,oBAAI,IAAiC;AAAA;AAAA,EAGjE,eAAe,QAA8B;AAC3C,SAAK,QAAQ,IAAI,OAAO,MAAM,MAAM;AAAA,EACtC;AAAA;AAAA,EAGA,SAAS,OAA0B,YAA0B;AAC3D,UAAM,WAAW,KAAK,SAAS,IAAI,KAAK,KAAK,CAAC;AAC9C,QAAI,CAAC,SAAS,SAAS,UAAU,GAAG;AAClC,eAAS,KAAK,UAAU;AAAA,IAC1B;AACA,SAAK,SAAS,IAAI,OAAO,QAAQ;AAAA,EACnC;AAAA;AAAA,EAGA,UAAU,MAA0C;AAClD,WAAO,KAAK,QAAQ,IAAI,IAAI;AAAA,EAC9B;AAAA;AAAA,EAGA,mBAAmB,OAAoC;AACrD,WAAO,KAAK,SAAS,IAAI,KAAK,KAAK,CAAC;AAAA,EACtC;AAAA;AAAA,EAGA,kBAA4B;AAC1B,WAAO,CAAC,GAAG,KAAK,QAAQ,KAAK,CAAC;AAAA,EAChC;AACF;;;ACjDA,SAAS,aAAa;AAIf,IAAM,0BAA0B;AAYhC,SAAS,wBAAwB,OAAsC;AAC5E,SAAO,IAAI,MAAuB,yBAAyB;AAAA,IACzD,YAAY;AAAA,IACZ,mBAAmB;AAAA,MACjB,UAAU;AAAA,MACV,SAAS;AAAA,QACP,MAAM;AAAA,QACN,OAAO;AAAA;AAAA,MACT;AAAA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QAAQ,IAAI,cAAc;AAChC,UAAM,SAAS,EAAE,MAAM,KAAK,KAAK,UAAU,OAAO,KAAK,KAAK,YAAY;AACxE,UAAM,KAAK,CAAC,EAAE,OAAO,aAAa,GAAG,CAAC;AACtC,UAAM,UAAU,aAAa,WAAW;AACxC,UAAM,cAAc;AACpB,QAAI,KAAM,OAAM,cAAc;AAE9B,UAAM,KAAK,YAAY,iBAAiB,KAAK;AAAA,EAC/C;AACF;","names":["ejs","ejsRender","ejs","ejsRender","ejs","ejsRender"]}
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@feathers-baas/plugin-notifications",
3
+ "version": "0.1.0",
4
+ "description": "Notifications plugin for feathers-baas — BullMQ-backed email drivers (SMTP, Resend, SendGrid, Brevo)",
5
+ "keywords": [
6
+ "feathers",
7
+ "feathersjs",
8
+ "notifications",
9
+ "email",
10
+ "bullmq",
11
+ "feathers-baas-plugin"
12
+ ],
13
+ "feathers-baas-plugin": true,
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "type": "module",
18
+ "main": "./dist/index.cjs",
19
+ "module": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "import": {
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ },
27
+ "require": {
28
+ "types": "./dist/index.d.cts",
29
+ "default": "./dist/index.cjs"
30
+ }
31
+ }
32
+ },
33
+ "dependencies": {
34
+ "@feathersjs/feathers": "^5.0.30",
35
+ "@getbrevo/brevo": "^2.2.0",
36
+ "@sendgrid/mail": "^8.1.0",
37
+ "bullmq": "^5.12.0",
38
+ "ejs": "^3.1.10",
39
+ "ioredis": "^5.3.2",
40
+ "nodemailer": "^6.9.14",
41
+ "resend": "^3.5.0"
42
+ },
43
+ "devDependencies": {
44
+ "@types/ejs": "^3.1.5",
45
+ "@types/nodemailer": "^6.4.15",
46
+ "ioredis-mock": "^8.9.0",
47
+ "tsup": "*",
48
+ "typescript": "*",
49
+ "vitest": "*"
50
+ },
51
+ "scripts": {
52
+ "build": "tsup",
53
+ "clean": "rm -rf dist",
54
+ "typecheck": "tsc --noEmit",
55
+ "test": "vitest run",
56
+ "test:watch": "vitest"
57
+ }
58
+ }
@@ -0,0 +1,47 @@
1
+ // Generated by feathers-baas. Safe to edit.
2
+ import { TransactionalEmailsApi, TransactionalEmailsApiApiKeys, SendSmtpEmail } from '@getbrevo/brevo'
3
+ import * as ejs from 'ejs'
4
+ import type { NotifierDriver, Notification } from '../types.js'
5
+
6
+ // ejs is a CommonJS module — alias the render function defensively
7
+ const ejsRender = (ejs as unknown as { render?: typeof ejs.render }).render ?? ejs.render
8
+
9
+ export interface BrevoDriverOptions {
10
+ /** Brevo API key (from https://app.brevo.com/settings/keys/api). */
11
+ apiKey: string
12
+ /** Display name shown in the From field. */
13
+ fromName: string
14
+ /** Verified sender address. Must be verified in your Brevo account. */
15
+ fromAddress: string
16
+ }
17
+
18
+ /**
19
+ * Email driver backed by the Brevo (formerly Sendinblue) Transactional Email API.
20
+ * Templates are rendered with EJS at send time.
21
+ */
22
+ export class BrevoDriver implements NotifierDriver {
23
+ readonly name = 'brevo'
24
+
25
+ private readonly apiInstance: TransactionalEmailsApi
26
+
27
+ constructor(private readonly opts: BrevoDriverOptions) {
28
+ this.apiInstance = new TransactionalEmailsApi()
29
+ this.apiInstance.setApiKey(TransactionalEmailsApiApiKeys.apiKey, opts.apiKey)
30
+ }
31
+
32
+ async send(notification: Notification): Promise<void> {
33
+ const html = ejsRender(notification.bodyTemplate, notification.data, { async: false })
34
+ const text = notification.textTemplate
35
+ ? ejsRender(notification.textTemplate, notification.data, { async: false })
36
+ : undefined
37
+
38
+ const email = new SendSmtpEmail()
39
+ email.sender = { name: this.opts.fromName, email: this.opts.fromAddress }
40
+ email.to = [{ email: notification.to }]
41
+ email.subject = notification.subject ?? '(no subject)'
42
+ email.htmlContent = html
43
+ if (text) email.textContent = text
44
+
45
+ await this.apiInstance.sendTransacEmail(email)
46
+ }
47
+ }
@@ -0,0 +1,51 @@
1
+ // Generated by feathers-baas. Safe to edit.
2
+ import { Resend } from 'resend'
3
+ import * as ejs from 'ejs'
4
+ import type { NotifierDriver, Notification } from '../types.js'
5
+
6
+ const ejsRender = (ejs as unknown as { render?: typeof ejs.render }).render ?? ejs.render
7
+
8
+ export interface ResendDriverOptions {
9
+ /** Resend API key (from https://resend.com/api-keys). */
10
+ apiKey: string
11
+ /** Display name shown in the From field. */
12
+ fromName: string
13
+ /** Verified sender address. Must be a verified domain in your Resend account. */
14
+ fromAddress: string
15
+ }
16
+
17
+ /**
18
+ * Email driver backed by the Resend transactional email API.
19
+ * Templates are rendered with EJS at send time.
20
+ *
21
+ * Resend offers generous free tier and excellent deliverability,
22
+ * making it the recommended choice for new projects.
23
+ */
24
+ export class ResendDriver implements NotifierDriver {
25
+ readonly name = 'resend'
26
+
27
+ private readonly client: Resend
28
+
29
+ constructor(private readonly opts: ResendDriverOptions) {
30
+ this.client = new Resend(opts.apiKey)
31
+ }
32
+
33
+ async send(notification: Notification): Promise<void> {
34
+ const html = ejsRender(notification.bodyTemplate, notification.data, { async: false })
35
+ const text = notification.textTemplate
36
+ ? ejsRender(notification.textTemplate, notification.data, { async: false })
37
+ : undefined
38
+
39
+ const result = await this.client.emails.send({
40
+ from: `${this.opts.fromName} <${this.opts.fromAddress}>`,
41
+ to: [notification.to],
42
+ subject: notification.subject ?? '(no subject)',
43
+ html,
44
+ text,
45
+ })
46
+
47
+ if ('error' in result && result.error) {
48
+ throw new Error(`Resend error: ${result.error.message}`)
49
+ }
50
+ }
51
+ }
@@ -0,0 +1,43 @@
1
+ // Generated by feathers-baas. Safe to edit.
2
+ import sgMail from '@sendgrid/mail'
3
+ import * as ejs from 'ejs'
4
+ import type { NotifierDriver, Notification } from '../types.js'
5
+
6
+ // ejs is a CommonJS module — alias the render function defensively
7
+ const ejsRender = (ejs as unknown as { render?: typeof ejs.render }).render ?? ejs.render
8
+
9
+ export interface SendGridDriverOptions {
10
+ /** SendGrid API key (from https://app.sendgrid.com/settings/api_keys). */
11
+ apiKey: string
12
+ /** Display name shown in the From field. */
13
+ fromName: string
14
+ /** Verified sender address. Must be verified in your SendGrid account. */
15
+ fromAddress: string
16
+ }
17
+
18
+ /**
19
+ * Email driver backed by the SendGrid API.
20
+ * Templates are rendered with EJS at send time.
21
+ */
22
+ export class SendGridDriver implements NotifierDriver {
23
+ readonly name = 'sendgrid'
24
+
25
+ constructor(private readonly opts: SendGridDriverOptions) {
26
+ sgMail.setApiKey(opts.apiKey)
27
+ }
28
+
29
+ async send(notification: Notification): Promise<void> {
30
+ const html = ejsRender(notification.bodyTemplate, notification.data, { async: false })
31
+ const text = notification.textTemplate
32
+ ? ejsRender(notification.textTemplate, notification.data, { async: false })
33
+ : undefined
34
+
35
+ await sgMail.send({
36
+ from: { name: this.opts.fromName, email: this.opts.fromAddress },
37
+ to: notification.to,
38
+ subject: notification.subject ?? '(no subject)',
39
+ html,
40
+ ...(text ? { text } : {}),
41
+ })
42
+ }
43
+ }
@@ -0,0 +1,58 @@
1
+ // Generated by feathers-baas. Safe to edit.
2
+ import nodemailer from 'nodemailer'
3
+ import * as ejs from 'ejs'
4
+ import type { NotifierDriver, Notification } from '../types.js'
5
+
6
+ // ejs is a CommonJS module — alias the render function defensively
7
+ const ejsRender = (ejs as unknown as { render?: typeof ejs.render }).render ?? ejs.render
8
+
9
+ export interface SMTPDriverOptions {
10
+ /** SMTP connection URL, e.g. smtp://user:pass@mail.example.com:587 */
11
+ url: string
12
+ /** Display name shown in the From field. */
13
+ fromName: string
14
+ /** Email address shown in the From field. */
15
+ fromAddress: string
16
+ }
17
+
18
+ /**
19
+ * Email driver backed by nodemailer over SMTP.
20
+ * Templates are rendered with EJS at send time.
21
+ *
22
+ * Use this driver for self-hosted SMTP servers (Postfix, Mailtrap, etc.).
23
+ * For transactional email services, prefer ResendDriver.
24
+ */
25
+ export class SMTPDriver implements NotifierDriver {
26
+ readonly name = 'smtp'
27
+
28
+ private readonly transporter: nodemailer.Transporter
29
+
30
+ constructor(private readonly opts: SMTPDriverOptions) {
31
+ this.transporter = nodemailer.createTransport(opts.url)
32
+ }
33
+
34
+ async send(notification: Notification): Promise<void> {
35
+ const html = ejsRender(notification.bodyTemplate, notification.data, { async: false })
36
+ const text = notification.textTemplate
37
+ ? ejsRender(notification.textTemplate, notification.data, { async: false })
38
+ : undefined
39
+
40
+ await this.transporter.sendMail({
41
+ from: `"${this.opts.fromName}" <${this.opts.fromAddress}>`,
42
+ to: notification.to,
43
+ subject: notification.subject ?? '(no subject)',
44
+ html,
45
+ text,
46
+ })
47
+ }
48
+
49
+ /** Verify SMTP connectivity. Throws if the server is unreachable. */
50
+ async verify(): Promise<void> {
51
+ await this.transporter.verify()
52
+ }
53
+
54
+ /** Close the underlying connection pool. */
55
+ close(): void {
56
+ this.transporter.close()
57
+ }
58
+ }