@astratra/notify 0.2.0 → 0.3.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/README.md CHANGED
@@ -196,6 +196,8 @@ const push = createPushSender({
196
196
  webpush.sendNotification(subscription, JSON.stringify(payload)),
197
197
  // LE point du module : l'abonnement mort t'est rendu pour suppression.
198
198
  onGone: (subscription) => Subscriptions.deleteOne({ endpoint: subscription.endpoint }),
199
+ concurrency: 10, // défaut : 10 envois simultanés au maximum
200
+ timeoutMs: 30_000, // défaut : un fournisseur a 30 secondes pour répondre
199
201
  });
200
202
 
201
203
  const { delivered, gone, failed } = await push.broadcast(subscriptions, payload);
@@ -206,17 +208,174 @@ Trois issues distinctes, jamais confondues : `delivered`, `gone` (mort, élagué
206
208
  n'arrête jamais les autres, et un élagage qui échoue ne transforme pas un `gone`
207
209
  en `failed`.
208
210
 
211
+ `broadcast` utilise un nombre borné de workers : un fournisseur lent ne retient
212
+ plus tous les abonnements placés derrière lui, sans pour autant déclencher une
213
+ rafale non bornée. Un dépassement de `timeoutMs` compte comme `failed` et les
214
+ autres envois continuent. La forme du rapport reste exactement
215
+ `{ delivered, gone, failed, errors }` ; même si les envois finissent dans le
216
+ désordre, `errors` suit toujours l'ordre des abonnements d'entrée (et conserve
217
+ sa limite historique de dix raisons).
218
+
209
219
  Le statut du fournisseur est cherché où qu'il l'ait mis — `statusCode`,
210
220
  `status`, `response.status` — parce que web-push et les clients HTTP ne sont pas
211
221
  d'accord entre eux.
212
222
 
213
223
  ---
214
224
 
225
+ # La boîte de notifications, côté serveur
226
+
227
+ ## Lire par pages, ranger, et ne jamais toucher au compte d'un autre
228
+
229
+ Trois défauts, tous du même produit :
230
+
231
+ - La liste rendait « les cinquante dernières », point. Au-delà, une
232
+ notification existait en base sans que personne ne puisse jamais la revoir.
233
+ - La suppression prenait un identifiant. Un identifiant se devine, ou fuit —
234
+ dans une URL, un journal, une capture. La **seule** barrière entre
235
+ « supprimer la mienne » et « supprimer celle de n'importe qui » est le
236
+ propriétaire **dans la requête elle-même**, pas une vérification faite après
237
+ et oubliée sur la route suivante.
238
+ - « Absente » et « à quelqu'un d'autre » doivent recevoir **la même réponse**.
239
+ Les distinguer dit à un inconnu quels identifiants existent.
240
+
241
+ ```js
242
+ const {
243
+ createNotificationInbox, createInboxHandlers, mountInbox,
244
+ } = require('@astratra/notify');
245
+
246
+ const inbox = createNotificationInbox({
247
+ store: myInboxStore, // injecté, voir plus bas
248
+ isValidId: (id) => mongoose.isValidObjectId(id), // 404 au lieu d'une erreur de conversion (500)
249
+ // pageSize: 50, maxPageSize: 100
250
+ });
251
+
252
+ const router = express.Router();
253
+ router.use(auth);
254
+ mountInbox(router, createInboxHandlers(inbox, {
255
+ owner: (req) => req.user.id, // la SESSION, jamais le corps ni la requête
256
+ }));
257
+ app.use('/api/notifications', router);
258
+ ```
259
+
260
+ | Route | Réponse |
261
+ |---|---|
262
+ | `GET /?page=2&limit=20` | `{ notifications, unreadCount, pagination: { total, page, limit, totalPages } }` |
263
+ | `GET /:id` | `{ notification }` ou 404 |
264
+ | `DELETE /:id` | `{ unreadCount }` ou 404 — absente et étrangère : même 404 |
265
+ | `DELETE /read` | `{ deleted, unreadCount }` — les **lues** seulement |
266
+ | `PATCH /:id/read`, `PATCH /read-all` | `{ unreadCount }` |
267
+
268
+ - **Sans paramètre, rien ne change** : première page de cinquante, comme les
269
+ appelants qui n'ont jamais paginé l'attendent. Une valeur absurde (`-4`,
270
+ `abc`) retombe sur le défaut, une trop grande est plafonnée.
271
+ - **Le nombre de non-lues revient avec chaque suppression** : la pastille se
272
+ recale sans attendre le prochain relevé.
273
+ - **Ranger n'efface pas ce qu'on n'a pas vu** : `DELETE /read` garde les
274
+ non-lues.
275
+ - **`mountInbox` enregistre les chemins fixes AVANT `/:id`.** Sinon
276
+ `DELETE /read` est lu comme « supprimer la notification d'identifiant
277
+ "read" », répond 404, et le bouton de rangement ne fait rien sans rien dire.
278
+ - Tes enveloppes de réponse passent par `respond: (res, status, body) => …`.
279
+
280
+ ### Le stockage est injecté
281
+
282
+ Chaque méthode reçoit `ownerId` et **doit l'appliquer dans la requête** :
283
+
284
+ ```js
285
+ const myInboxStore = {
286
+ list: ({ ownerId, offset, limit }) => Notification.find({ userId: ownerId })
287
+ .sort({ createdAt: -1, _id: -1 }) // _id départage deux avis du même instant
288
+ .skip(offset).limit(limit).lean(),
289
+ count: ({ ownerId, read }) => Notification.countDocuments({ userId: ownerId, ...(read === undefined ? {} : { read }) }),
290
+ get: ({ ownerId, id }) => Notification.findOne({ _id: id, userId: ownerId }).lean(),
291
+ remove: async ({ ownerId, id }) => (await Notification.deleteOne({ _id: id, userId: ownerId })).deletedCount,
292
+ removeRead: async ({ ownerId }) => (await Notification.deleteMany({ userId: ownerId, read: true })).deletedCount,
293
+ markRead: async ({ ownerId, id }) => (await Notification.updateOne({ _id: id, userId: ownerId }, { read: true })).matchedCount,
294
+ markAllRead: async ({ ownerId }) => (await Notification.updateMany({ userId: ownerId, read: false }, { read: true })).modifiedCount,
295
+ };
296
+ ```
297
+
298
+ Sans départage par identifiant, une base rend les égalités dans l'ordre qui
299
+ lui plaît, et peut changer d'avis d'une requête à l'autre : une notification
300
+ apparaît alors sur deux pages, ou sur aucune.
301
+
302
+ `createMemoryInboxStore()` est l'adaptateur de référence, pour les tests : il
303
+ **applique** le filtre propriétaire comme une base le ferait, et refuse une
304
+ requête sans propriétaire. Une boîte qui oublierait de le passer atteindrait
305
+ ici l'autre compte exactement comme en production — c'est ce qui rend les
306
+ tests honnêtes.
307
+
308
+ ## Des notifications traduites, et un texte neutre pour l'écran verrouillé
309
+
310
+ Une notification produite par le serveur (une note, une facture, un résultat)
311
+ est une clé et des paramètres ; le titre et le message sont rendus pour chaque
312
+ destinataire, dans sa langue. **Les textes sont à toi** : ce package n'en
313
+ contient aucun.
314
+
315
+ La leçon qui justifie un module plutôt qu'un dictionnaire : un push s'affiche
316
+ sur un **écran verrouillé**, sous les yeux de quiconque tient ou regarde le
317
+ téléphone. Une décision de fin d'année sur un enfant y est apparue en toutes
318
+ lettres — sous un titre pourtant rendu neutre, puisque le corps était le
319
+ message lui-même. Une entrée peut donc déclarer `pushBody` : une ligne neutre
320
+ qui remplace le message **dans le push seulement**. La boîte, l'écran et
321
+ l'e-mail — lu dans une boîte personnelle, une fois déverrouillé — gardent le
322
+ message complet.
323
+
324
+ ```js
325
+ const { createNotificationCatalog } = require('@astratra/notify');
326
+
327
+ const catalog = createNotificationCatalog({
328
+ languages: ['fr', 'en'],
329
+ entries: [grades, billing], // un objet par domaine ; une clé en double lève au démarrage
330
+ });
331
+
332
+ // grades.js
333
+ module.exports = {
334
+ year_result: {
335
+ fr: (p) => ({ title: 'Résultat de fin d\'année disponible', message: `${p.student} …`, pushBody: 'Ouvrez l\'application pour le consulter.' }),
336
+ en: (p) => ({ title: 'End-of-year result available', message: `${p.student} …`, pushBody: 'Open the app to view it.' }),
337
+ },
338
+ };
339
+
340
+ const n = catalog.render('year_result', recipientLanguage, { student: 'Ada' });
341
+ await inboxStore.create({ ownerId, title: n.title, message: n.message }); // complet
342
+ await push.broadcast(devices, n.push); // { title, body } neutre
343
+ ```
344
+
345
+ Une langue non écrite pour une clé retombe sur la langue par défaut
346
+ (`n.language` dit laquelle a été rendue) ; chaque entrée doit donc exister
347
+ dans la langue par défaut. Une clé inconnue lève : c'est une faute de frappe
348
+ dans le code.
349
+
350
+ ### L'audit
351
+
352
+ ```js
353
+ test('le catalogue des notifications', () => {
354
+ const report = catalog.audit({ params: SAMPLE_PARAMS });
355
+ expect(report.pushBodyGaps).toEqual([]);
356
+ expect(report.placeholders).toEqual([]);
357
+ expect(report.errors).toEqual([]);
358
+ });
359
+ ```
360
+
361
+ - `pushBodyGaps` : un corps neutre déclaré dans certaines langues et oublié
362
+ dans d'autres. La fuite n'existe que dans la langue oubliée — personne ne la
363
+ voit en relisant le catalogue dans la sienne.
364
+ - `placeholders` : `undefined`, `null`, `NaN` ou `[object Object]` dans un
365
+ texte rendu — un paramètre attendu et jamais reçu.
366
+ - `missing` : les langues non écrites, servies dans la langue par défaut.
367
+
368
+ ---
369
+
215
370
  ## Ce que ce package ne fait pas
216
371
 
217
372
  - Il n'envoie **rien** lui-même : les transports sont injectés. Aucun SDK — ni
218
373
  nodemailer, ni Twilio, ni web-push — n'est importé.
219
374
  - Il ne stocke pas les abonnements : il te rend les morts, tu les supprimes.
375
+ Il ne tient pas non plus de registre d'appareils par compte : tu choisis la
376
+ liste, `broadcast` l'envoie.
377
+ - La boîte de notifications ne crée pas les notifications et ne les pousse
378
+ pas : elle lit, range et supprime ce que ton stockage contient.
220
379
  - Il ne fait ni file d'attente ni relance — voir `@astratra/resilience`.
221
380
  - Il ne gère pas le temps réel (websockets).
222
381
  - Il n'a pas d'avis sur ton identité visuelle, seulement sur ce qui survit aux
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@astratra/notify",
3
- "version": "0.2.0",
4
- "description": "Outbound messages done once \u2014 email, SMS and push. Transport injected, never throws, header-injection safe, loud simulation when unconfigured, dead push subscriptions handed back for pruning.",
3
+ "version": "0.3.0",
4
+ "description": "Outbound messages done once — email, SMS and push. Transport injected, never throws, header-injection safe, loud simulation when unconfigured, dead push subscriptions handed back for pruning.",
5
5
  "engines": {
6
6
  "node": ">=20"
7
7
  },
package/src/catalog.js ADDED
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Notifications written by the server, in the recipient's language — and a
3
+ * separate, NEUTRAL text for the lock screen.
4
+ *
5
+ * A notification generated by the server (a grade, an invoice, a result) is a
6
+ * key and some parameters; the title and the message are rendered per
7
+ * recipient, in their language. The texts are yours — this module holds none.
8
+ *
9
+ * The lesson that justifies a module rather than a dictionary: a push is shown
10
+ * on a LOCKED screen, to whoever holds or glances at the phone. An end-of-year
11
+ * decision about a child appeared there in full — under a title that had been
12
+ * carefully made neutral, because the body was the message itself. So an
13
+ * entry may declare `pushBody`: a neutral line ("Open the app to view it")
14
+ * that replaces the message in the push only. The inbox, the screen and the
15
+ * email — read in a personal mailbox, after unlocking — keep the full message.
16
+ *
17
+ * And the lesson that justifies `audit()`: a neutral push body declared in
18
+ * one language and forgotten in another leaks in that other language only.
19
+ * Nobody reading the catalogue in their own language will ever see it.
20
+ */
21
+
22
+ const PLACEHOLDER_LEAK = /\b(undefined|null|NaN)\b|\[object Object\]/;
23
+
24
+ /**
25
+ * @param {object} options
26
+ * @param {string[]} options.languages
27
+ * @param {string} [options.defaultLanguage] defaults to the first entry.
28
+ * @param {object|object[]} options.entries key -> { language: render }, where
29
+ * render is `(params) => ({ title, message?, pushBody? })` or that object
30
+ * itself. Several objects (one per domain) are merged, and a key declared
31
+ * twice is an error at start-up — never a silent overwrite.
32
+ */
33
+ function createNotificationCatalog(options = {}) {
34
+ const languages = options.languages || [];
35
+ if (!languages.length) throw new Error('createNotificationCatalog requires options.languages.');
36
+ const defaultLanguage = options.defaultLanguage || languages[0];
37
+ if (!languages.includes(defaultLanguage)) {
38
+ throw new Error(`createNotificationCatalog: defaultLanguage "${defaultLanguage}" is not in options.languages.`);
39
+ }
40
+ const supported = new Set(languages);
41
+
42
+ const entries = new Map();
43
+ for (const group of [].concat(options.entries || [])) {
44
+ for (const [key, byLanguage] of Object.entries(group || {})) {
45
+ if (entries.has(key)) {
46
+ throw new Error(`createNotificationCatalog: key "${key}" is declared twice.`);
47
+ }
48
+ if (!byLanguage || typeof byLanguage !== 'object') {
49
+ throw new Error(`createNotificationCatalog: "${key}" must be an object keyed by language.`);
50
+ }
51
+ for (const language of Object.keys(byLanguage)) {
52
+ if (!supported.has(language)) {
53
+ throw new Error(`createNotificationCatalog: "${key}" declares unknown language "${language}".`);
54
+ }
55
+ }
56
+ if (!byLanguage[defaultLanguage]) {
57
+ /* The fallback of every other language: without it, a recipient in a
58
+ half-filled language would get nothing at all. */
59
+ throw new Error(`createNotificationCatalog: "${key}" has no "${defaultLanguage}" version.`);
60
+ }
61
+ entries.set(key, byLanguage);
62
+ }
63
+ }
64
+
65
+ const base = (tag) => String(tag || '').trim().toLowerCase().split('-')[0];
66
+
67
+ /**
68
+ * @returns {{key: string, language: string, title: string, message: string,
69
+ * push: {title: string, body: string}, neutralPush: boolean}}
70
+ * `language` is the one actually rendered — the default when the requested
71
+ * one is missing. `push.body` is the neutral text when the entry has one,
72
+ * the message otherwise.
73
+ * @throws on an unknown key: that is a typo in the code, and a notification
74
+ * with no text is worse than a failed call during development.
75
+ */
76
+ function render(key, language, params = {}) {
77
+ const byLanguage = entries.get(key);
78
+ if (!byLanguage) throw new Error(`Unknown notification key: ${key}`);
79
+
80
+ const requested = base(language);
81
+ const rendered = byLanguage[requested] ? requested : defaultLanguage;
82
+ const template = byLanguage[rendered];
83
+ const content = (typeof template === 'function' ? template(params || {}) : template) || {};
84
+
85
+ const title = content.title === undefined || content.title === null ? '' : String(content.title);
86
+ const message = content.message === undefined || content.message === null ? '' : String(content.message);
87
+ const neutral = content.pushBody !== undefined && content.pushBody !== null;
88
+
89
+ return {
90
+ key,
91
+ language: rendered,
92
+ title,
93
+ message,
94
+ push: { title, body: neutral ? String(content.pushBody) : message },
95
+ neutralPush: neutral
96
+ };
97
+ }
98
+
99
+ /**
100
+ * What would go wrong, found before a recipient finds it.
101
+ *
102
+ * @param {object} [auditOptions]
103
+ * @param {Record<string, object>} [auditOptions.params] sample parameters
104
+ * per key, so templates render as they would in production.
105
+ * @returns {{missing: Array<{key: string, language: string}>,
106
+ * pushBodyGaps: Array<{key: string, languages: string[]}>,
107
+ * placeholders: Array<{key: string, language: string, text: string}>,
108
+ * errors: Array<{key: string, language: string, error: string}>}}
109
+ * - missing: a language not written for a key (the default is served).
110
+ * - pushBodyGaps: a neutral push declared in some languages and not in
111
+ * others — the lock-screen leak nobody sees in their own language.
112
+ * - placeholders: "undefined", "null", "NaN" or "[object Object]" in a
113
+ * rendered text — a parameter the template expected and did not get.
114
+ * - errors: a template that throws on the sample parameters.
115
+ */
116
+ function audit(auditOptions = {}) {
117
+ const samples = auditOptions.params || {};
118
+ const report = { missing: [], pushBodyGaps: [], placeholders: [], errors: [] };
119
+
120
+ for (const [key, byLanguage] of entries) {
121
+ const withNeutral = [];
122
+ const without = [];
123
+ for (const language of languages) {
124
+ if (!byLanguage[language]) {
125
+ report.missing.push({ key, language });
126
+ continue;
127
+ }
128
+ let rendered;
129
+ try {
130
+ rendered = render(key, language, samples[key] || {});
131
+ } catch (error) {
132
+ report.errors.push({ key, language, error: error.message });
133
+ continue;
134
+ }
135
+ (rendered.neutralPush ? withNeutral : without).push(language);
136
+ for (const text of [rendered.title, rendered.message, rendered.push.body]) {
137
+ if (PLACEHOLDER_LEAK.test(text)) report.placeholders.push({ key, language, text });
138
+ }
139
+ }
140
+ if (withNeutral.length && without.length) report.pushBodyGaps.push({ key, languages: without });
141
+ }
142
+
143
+ return report;
144
+ }
145
+
146
+ return {
147
+ languages: [...languages],
148
+ defaultLanguage,
149
+ render,
150
+ audit,
151
+ has: (key) => entries.has(key),
152
+ keys: () => [...entries.keys()]
153
+ };
154
+ }
155
+
156
+ module.exports = { createNotificationCatalog };
package/src/inbox.js ADDED
@@ -0,0 +1,292 @@
1
+ /**
2
+ * The notification inbox, server side: read it by pages, tidy it, and never
3
+ * let one account touch another's.
4
+ *
5
+ * Three defects shaped this, all from the same product:
6
+ *
7
+ * The list returned "the latest fifty" and nothing else. Past fifty, a
8
+ * notification existed in the database and nobody could ever see it again —
9
+ * and a page that opened a notification by looking for it in that list
10
+ * could not open the fifty-first.
11
+ *
12
+ * Deleting took an id. An id is guessable, or leaks — in a URL, a log, a
13
+ * screenshot. The ONLY barrier between "delete mine" and "delete anyone's"
14
+ * is the owner being part of the query itself, not a check made afterwards
15
+ * that someone forgets on the next route. So every store call here carries
16
+ * the owner, and a store call without one is refused.
17
+ *
18
+ * "Not found" and "not yours" must be the same answer. Distinguishing them
19
+ * tells a stranger which ids exist, and whose.
20
+ *
21
+ * The store is injected: a notification is one document PER RECIPIENT (a
22
+ * message to a whole class writes one copy per account), so deleting yours
23
+ * never touches anyone else's copy, and there is nothing to hide or mask.
24
+ */
25
+
26
+ const DEFAULT_PAGE_SIZE = 50;
27
+ const DEFAULT_MAX_PAGE_SIZE = 100;
28
+
29
+ const positiveInteger = (value, fallback) => {
30
+ const number = Number.parseInt(value, 10);
31
+ return Number.isFinite(number) && number > 0 ? number : fallback;
32
+ };
33
+
34
+ const missingOwner = (ownerId) => ownerId === undefined || ownerId === null || ownerId === '';
35
+
36
+ /**
37
+ * @param {object} options
38
+ * @param {object} options.store see createMemoryInboxStore for the contract.
39
+ * @param {number} [options.pageSize] default page size. Default 50.
40
+ * @param {number} [options.maxPageSize] a caller cannot ask for more. Default 100.
41
+ * @param {Function} [options.isValidId] (id) => boolean. An id the store would
42
+ * choke on (a malformed database id raising a cast error, i.e. a 500) is
43
+ * answered as "not found" without reaching the store.
44
+ */
45
+ function createNotificationInbox(options = {}) {
46
+ const store = options.store;
47
+ for (const method of ['list', 'count', 'get', 'remove', 'removeRead', 'markRead', 'markAllRead']) {
48
+ if (!store || typeof store[method] !== 'function') {
49
+ throw new Error(`createNotificationInbox: options.store needs a ${method}() method.`);
50
+ }
51
+ }
52
+
53
+ const maxPageSize = positiveInteger(options.maxPageSize, DEFAULT_MAX_PAGE_SIZE);
54
+ const pageSize = Math.min(positiveInteger(options.pageSize, DEFAULT_PAGE_SIZE), maxPageSize);
55
+ const isValidId = typeof options.isValidId === 'function'
56
+ ? options.isValidId
57
+ : (id) => (typeof id === 'string' && id.length > 0) || typeof id === 'number';
58
+
59
+ /* A programming error, not a user error: an inbox call without an owner
60
+ would read or delete across every account. Loud, immediately. */
61
+ const requireOwner = (ownerId) => {
62
+ if (missingOwner(ownerId)) throw new Error('notification inbox: every call needs the owner id.');
63
+ };
64
+
65
+ const unreadOf = (ownerId) => store.count({ ownerId, read: false });
66
+
67
+ /**
68
+ * One page, newest first. Without parameters, the first page at the default
69
+ * size — existing callers that never paginated see no change.
70
+ *
71
+ * @returns {Promise<{notifications: object[], unreadCount: number,
72
+ * pagination: {total: number, page: number, limit: number, totalPages: number}}>}
73
+ */
74
+ async function list(ownerId, query = {}) {
75
+ requireOwner(ownerId);
76
+ /* Absurd values — negative, zero, text — fall back rather than error: a
77
+ list that refuses to load over a stray query parameter is worse than a
78
+ list at the default size. */
79
+ const limit = Math.min(positiveInteger(query.limit, pageSize), maxPageSize);
80
+ const page = positiveInteger(query.page, 1);
81
+
82
+ const [notifications, total, unreadCount] = await Promise.all([
83
+ store.list({ ownerId, offset: (page - 1) * limit, limit }),
84
+ store.count({ ownerId }),
85
+ unreadOf(ownerId)
86
+ ]);
87
+
88
+ return {
89
+ notifications,
90
+ unreadCount,
91
+ pagination: { total, page, limit, totalPages: Math.ceil(total / limit) }
92
+ };
93
+ }
94
+
95
+ /** One notification of this owner, or null — absent and foreign look alike. */
96
+ async function get(ownerId, id) {
97
+ requireOwner(ownerId);
98
+ if (!isValidId(id)) return null;
99
+ return (await store.get({ ownerId, id })) || null;
100
+ }
101
+
102
+ /**
103
+ * Delete one. The unread count comes back with it, so a badge can settle
104
+ * without waiting for the next refresh.
105
+ *
106
+ * @returns {Promise<{removed: boolean, unreadCount?: number}>}
107
+ */
108
+ async function remove(ownerId, id) {
109
+ requireOwner(ownerId);
110
+ const removed = isValidId(id) ? await store.remove({ ownerId, id }) : 0;
111
+ if (!removed) return { removed: false };
112
+ return { removed: true, unreadCount: await unreadOf(ownerId) };
113
+ }
114
+
115
+ /**
116
+ * Delete every READ notification of this owner. Unread ones stay: tidying
117
+ * up must not erase what has not been seen yet.
118
+ */
119
+ async function removeRead(ownerId) {
120
+ requireOwner(ownerId);
121
+ const deleted = (await store.removeRead({ ownerId })) || 0;
122
+ return { deleted, unreadCount: await unreadOf(ownerId) };
123
+ }
124
+
125
+ async function markRead(ownerId, id) {
126
+ requireOwner(ownerId);
127
+ const updated = isValidId(id) ? await store.markRead({ ownerId, id }) : 0;
128
+ if (!updated) return { updated: false };
129
+ return { updated: true, unreadCount: await unreadOf(ownerId) };
130
+ }
131
+
132
+ async function markAllRead(ownerId) {
133
+ requireOwner(ownerId);
134
+ const updated = (await store.markAllRead({ ownerId })) || 0;
135
+ /* Recounted, not assumed zero: a notification can land between the two. */
136
+ return { updated, unreadCount: await unreadOf(ownerId) };
137
+ }
138
+
139
+ return { list, get, remove, removeRead, markRead, markAllRead, pageSize, maxPageSize };
140
+ }
141
+
142
+ /**
143
+ * The reference store, in memory — for tests, and as the contract a real
144
+ * adapter follows. It APPLIES the owner filter it receives, like a database
145
+ * would: an inbox that forgot to pass it would reach the other account here
146
+ * exactly as it would in production, which is what makes tests against it
147
+ * honest.
148
+ *
149
+ * Items: { id, ownerId, read, createdAt, ...anything }.
150
+ * Order: newest first, id as tie-breaker — two notifications from the same
151
+ * instant would otherwise swap between pages, or appear on both.
152
+ */
153
+ function createMemoryInboxStore(options = {}) {
154
+ const items = [...(options.items || [])];
155
+
156
+ const owned = (ownerId) => {
157
+ if (missingOwner(ownerId)) throw new Error('memory inbox store: query without an owner refused.');
158
+ return items.filter((item) => String(item.ownerId) === String(ownerId));
159
+ };
160
+ const same = (a, b) => String(a) === String(b);
161
+ const newestFirst = (a, b) => (new Date(b.createdAt) - new Date(a.createdAt)) || String(b.id).localeCompare(String(a.id));
162
+ const drop = (predicate) => {
163
+ let removed = 0;
164
+ for (let i = items.length - 1; i >= 0; i -= 1) {
165
+ if (predicate(items[i])) { items.splice(i, 1); removed += 1; }
166
+ }
167
+ return removed;
168
+ };
169
+
170
+ return {
171
+ async list({ ownerId, offset = 0, limit }) {
172
+ return owned(ownerId).sort(newestFirst).slice(offset, offset + limit).map((item) => ({ ...item }));
173
+ },
174
+ async count({ ownerId, read }) {
175
+ return owned(ownerId).filter((item) => read === undefined || Boolean(item.read) === read).length;
176
+ },
177
+ async get({ ownerId, id }) {
178
+ const found = owned(ownerId).find((item) => same(item.id, id));
179
+ return found ? { ...found } : null;
180
+ },
181
+ async remove({ ownerId, id }) {
182
+ owned(ownerId);
183
+ /* The owner is IN the match, not checked afterwards: that is the barrier. */
184
+ const index = items.findIndex((item) => same(item.ownerId, ownerId) && same(item.id, id));
185
+ if (index === -1) return 0;
186
+ items.splice(index, 1);
187
+ return 1;
188
+ },
189
+ async removeRead({ ownerId }) {
190
+ owned(ownerId);
191
+ return drop((item) => same(item.ownerId, ownerId) && Boolean(item.read));
192
+ },
193
+ async markRead({ ownerId, id }) {
194
+ const found = owned(ownerId).find((item) => same(item.id, id));
195
+ if (!found) return 0;
196
+ found.read = true;
197
+ return 1;
198
+ },
199
+ async markAllRead({ ownerId }) {
200
+ let updated = 0;
201
+ for (const item of owned(ownerId)) {
202
+ if (!item.read) { item.read = true; updated += 1; }
203
+ }
204
+ return updated;
205
+ },
206
+ /** Test helpers: add a notification, read everything regardless of owner. */
207
+ add(item) { items.push({ read: false, createdAt: new Date(), ...item }); return item; },
208
+ all() { return items.map((item) => ({ ...item })); }
209
+ };
210
+ }
211
+
212
+ const defaultRespond = (res, status, body) => res.status(status).json(body);
213
+
214
+ /**
215
+ * HTTP handlers over an inbox, for express or anything with the same
216
+ * `(req, res, next)` shape. No framework is imported.
217
+ *
218
+ * @param {object} inbox from createNotificationInbox().
219
+ * @param {object} [options]
220
+ * @param {Function} [options.owner] (req) => owner id. Default req.user.id.
221
+ * From the SESSION, never from the body or the query: an owner the client
222
+ * can choose is not an owner.
223
+ * @param {Function} [options.respond] (res, status, body) => void — your
224
+ * response envelope. Default res.status(status).json(body).
225
+ * @param {string} [options.notFoundMessage]
226
+ */
227
+ function createInboxHandlers(inbox, options = {}) {
228
+ if (!inbox || typeof inbox.list !== 'function') {
229
+ throw new Error('createInboxHandlers requires an inbox from createNotificationInbox().');
230
+ }
231
+ const owner = options.owner || ((req) => req.user && req.user.id);
232
+ const respond = options.respond || defaultRespond;
233
+ const notFoundMessage = options.notFoundMessage || 'This notification could not be found.';
234
+
235
+ /* Every handler forwards its errors to next(): an async handler that throws
236
+ otherwise becomes an unhandled rejection and a request that never ends. */
237
+ const handler = (run) => async (req, res, next) => {
238
+ try {
239
+ const ownerId = owner(req);
240
+ if (missingOwner(ownerId)) return respond(res, 401, { message: 'Sign in to see your notifications.' });
241
+ return await run(req, res, ownerId);
242
+ } catch (error) {
243
+ return typeof next === 'function' ? next(error) : undefined;
244
+ }
245
+ };
246
+
247
+ const notFound = (res) => respond(res, 404, { message: notFoundMessage });
248
+
249
+ return {
250
+ list: handler(async (req, res, ownerId) => respond(res, 200, await inbox.list(ownerId, req.query || {}))),
251
+ get: handler(async (req, res, ownerId) => {
252
+ const notification = await inbox.get(ownerId, req.params && req.params.id);
253
+ return notification ? respond(res, 200, { notification }) : notFound(res);
254
+ }),
255
+ remove: handler(async (req, res, ownerId) => {
256
+ const result = await inbox.remove(ownerId, req.params && req.params.id);
257
+ return result.removed ? respond(res, 200, { unreadCount: result.unreadCount }) : notFound(res);
258
+ }),
259
+ removeRead: handler(async (_req, res, ownerId) => respond(res, 200, await inbox.removeRead(ownerId))),
260
+ markRead: handler(async (req, res, ownerId) => {
261
+ const result = await inbox.markRead(ownerId, req.params && req.params.id);
262
+ return result.updated ? respond(res, 200, { unreadCount: result.unreadCount }) : notFound(res);
263
+ }),
264
+ markAllRead: handler(async (_req, res, ownerId) => respond(res, 200, await inbox.markAllRead(ownerId)))
265
+ };
266
+ }
267
+
268
+ /**
269
+ * Register the handlers on a router, FIXED PATHS FIRST.
270
+ *
271
+ * `DELETE /read` registered after `DELETE /:id` is read as "delete the
272
+ * notification whose id is 'read'" — which answers 404, and the tidy-up button
273
+ * silently does nothing. Order is the whole point of this function.
274
+ *
275
+ * @param {object} router anything with get/patch/delete(path, handler).
276
+ */
277
+ function mountInbox(router, handlers) {
278
+ router.get('/', handlers.list);
279
+ router.patch('/read-all', handlers.markAllRead);
280
+ router.delete('/read', handlers.removeRead);
281
+ router.get('/:id', handlers.get);
282
+ router.patch('/:id/read', handlers.markRead);
283
+ router.delete('/:id', handlers.remove);
284
+ return router;
285
+ }
286
+
287
+ module.exports = {
288
+ createNotificationInbox,
289
+ createMemoryInboxStore,
290
+ createInboxHandlers,
291
+ mountInbox
292
+ };
package/src/index.d.ts CHANGED
@@ -157,5 +157,157 @@ export function createPushSender<Subscription = unknown, Payload = unknown>(opti
157
157
  isGone?: (error: unknown) => boolean;
158
158
  /** Delete the dead subscription from your store — the point of the module. */
159
159
  onGone?: (subscription: Subscription) => Awaitable<void>;
160
+ /** Maximum simultaneous sends. Default 10. */
161
+ concurrency?: number;
162
+ /** Provider deadline for one send, in milliseconds. Default 30000. */
163
+ timeoutMs?: number;
160
164
  logger?: { info?(m: string): void; warn?(m: string): void; error?(m: string): void };
161
165
  }): PushSender<Subscription, Payload>;
166
+
167
+ /* ───────────────────────── The notification inbox ───────────────────────── */
168
+
169
+ export interface InboxPagination {
170
+ total: number;
171
+ page: number;
172
+ limit: number;
173
+ totalPages: number;
174
+ }
175
+
176
+ export interface InboxPage<Item> {
177
+ notifications: Item[];
178
+ unreadCount: number;
179
+ pagination: InboxPagination;
180
+ }
181
+
182
+ /**
183
+ * The storage contract. Every call carries `ownerId`, and the store MUST apply
184
+ * it inside the query — the owner in the match is the only barrier.
185
+ * `list` returns newest first, ties broken by id (descending).
186
+ * `remove`, `removeRead`, `markRead`, `markAllRead` return how many documents changed.
187
+ */
188
+ export interface InboxStore<Item = InboxItem> {
189
+ list(query: { ownerId: unknown; offset: number; limit: number }): Awaitable<Item[]>;
190
+ count(query: { ownerId: unknown; read?: boolean }): Awaitable<number>;
191
+ get(query: { ownerId: unknown; id: unknown }): Awaitable<Item | null | undefined>;
192
+ remove(query: { ownerId: unknown; id: unknown }): Awaitable<number>;
193
+ removeRead(query: { ownerId: unknown }): Awaitable<number>;
194
+ markRead(query: { ownerId: unknown; id: unknown }): Awaitable<number>;
195
+ markAllRead(query: { ownerId: unknown }): Awaitable<number>;
196
+ }
197
+
198
+ export interface InboxItem {
199
+ id: string | number;
200
+ ownerId: string | number;
201
+ read?: boolean;
202
+ createdAt?: Date | string | number;
203
+ [field: string]: unknown;
204
+ }
205
+
206
+ export interface NotificationInbox<Item = InboxItem> {
207
+ /** Throws when ownerId is missing — a programming error, never a user one. */
208
+ list(ownerId: unknown, query?: { page?: unknown; limit?: unknown }): Promise<InboxPage<Item>>;
209
+ /** Absent and "belongs to someone else" both return null. */
210
+ get(ownerId: unknown, id: unknown): Promise<Item | null>;
211
+ remove(ownerId: unknown, id: unknown): Promise<{ removed: boolean; unreadCount?: number }>;
212
+ /** Read notifications only — unread ones are never tidied away. */
213
+ removeRead(ownerId: unknown): Promise<{ deleted: number; unreadCount: number }>;
214
+ markRead(ownerId: unknown, id: unknown): Promise<{ updated: boolean; unreadCount?: number }>;
215
+ markAllRead(ownerId: unknown): Promise<{ updated: number; unreadCount: number }>;
216
+ pageSize: number;
217
+ maxPageSize: number;
218
+ }
219
+
220
+ export function createNotificationInbox<Item = InboxItem>(options: {
221
+ store: InboxStore<Item>;
222
+ /** Default 50. */
223
+ pageSize?: number;
224
+ /** Default 100. */
225
+ maxPageSize?: number;
226
+ /** An id failing this is "not found" without reaching the store. */
227
+ isValidId?: (id: unknown) => boolean;
228
+ }): NotificationInbox<Item>;
229
+
230
+ export interface MemoryInboxStore extends InboxStore<InboxItem> {
231
+ add(item: Partial<InboxItem> & { id: string | number; ownerId: string | number }): InboxItem;
232
+ all(): InboxItem[];
233
+ }
234
+
235
+ /** The reference adapter: applies the owner filter like a database would, refuses ownerless queries. */
236
+ export function createMemoryInboxStore(options?: { items?: InboxItem[] }): MemoryInboxStore;
237
+
238
+ export type InboxHandler = (req: any, res: any, next?: (error?: unknown) => unknown) => Promise<unknown>;
239
+
240
+ export interface InboxHandlers {
241
+ list: InboxHandler;
242
+ get: InboxHandler;
243
+ remove: InboxHandler;
244
+ removeRead: InboxHandler;
245
+ markRead: InboxHandler;
246
+ markAllRead: InboxHandler;
247
+ }
248
+
249
+ export function createInboxHandlers(inbox: NotificationInbox<any>, options?: {
250
+ /** From the session, never from the body or the query. Default req.user.id. */
251
+ owner?: (req: any) => unknown;
252
+ /** Your response envelope. Default res.status(status).json(body). */
253
+ respond?: (res: any, status: number, body: unknown) => unknown;
254
+ notFoundMessage?: string;
255
+ }): InboxHandlers;
256
+
257
+ export interface RouterLike {
258
+ get(path: string, handler: InboxHandler): unknown;
259
+ patch(path: string, handler: InboxHandler): unknown;
260
+ delete(path: string, handler: InboxHandler): unknown;
261
+ }
262
+
263
+ /** Registers fixed paths (`/read-all`, `/read`) BEFORE `/:id`. */
264
+ export function mountInbox<Router extends RouterLike>(router: Router, handlers: InboxHandlers): Router;
265
+
266
+ /* ─────────────────────── Translated notifications ─────────────────────── */
267
+
268
+ export interface NotificationContent {
269
+ title?: string;
270
+ message?: string;
271
+ /** A neutral line that replaces the message on the lock screen only. */
272
+ pushBody?: string;
273
+ }
274
+
275
+ export type NotificationTemplate<Params = any> = NotificationContent | ((params: Params) => NotificationContent);
276
+
277
+ export type NotificationEntries = Record<string, Record<string, NotificationTemplate>>;
278
+
279
+ export interface RenderedNotification {
280
+ key: string;
281
+ /** The language actually rendered — the default when the requested one is missing. */
282
+ language: string;
283
+ title: string;
284
+ message: string;
285
+ /** What a push may show: the neutral body when the entry has one, the message otherwise. */
286
+ push: { title: string; body: string };
287
+ neutralPush: boolean;
288
+ }
289
+
290
+ export interface NotificationCatalogAudit {
291
+ missing: Array<{ key: string; language: string }>;
292
+ /** A neutral push declared in some languages and forgotten in these. */
293
+ pushBodyGaps: Array<{ key: string; languages: string[] }>;
294
+ placeholders: Array<{ key: string; language: string; text: string }>;
295
+ errors: Array<{ key: string; language: string; error: string }>;
296
+ }
297
+
298
+ export interface NotificationCatalog {
299
+ languages: string[];
300
+ defaultLanguage: string;
301
+ /** Throws on an unknown key. */
302
+ render(key: string, language?: string | null, params?: Record<string, unknown>): RenderedNotification;
303
+ audit(options?: { params?: Record<string, Record<string, unknown>> }): NotificationCatalogAudit;
304
+ has(key: string): boolean;
305
+ keys(): string[];
306
+ }
307
+
308
+ export function createNotificationCatalog(options: {
309
+ languages: string[];
310
+ defaultLanguage?: string;
311
+ /** One object, or several (one per domain) — a key declared twice throws. */
312
+ entries: NotificationEntries | NotificationEntries[];
313
+ }): NotificationCatalog;
package/src/index.js CHANGED
@@ -3,5 +3,7 @@ module.exports = {
3
3
  ...require('./mailer'),
4
4
  ...require('./template'),
5
5
  ...require('./sms'),
6
- ...require('./push')
6
+ ...require('./push'),
7
+ ...require('./inbox'),
8
+ ...require('./catalog')
7
9
  };
package/src/push.js CHANGED
@@ -14,6 +14,20 @@
14
14
  */
15
15
 
16
16
  const NOOP_LOGGER = { info() {}, warn() {}, error() {} };
17
+ const DEFAULT_CONCURRENCY = 10;
18
+ const DEFAULT_TIMEOUT_MS = 30_000;
19
+
20
+ function withTimeout(value, timeoutMs) {
21
+ let timer;
22
+ const deadline = new Promise((resolve, reject) => {
23
+ timer = setTimeout(
24
+ () => reject(new Error(`Push delivery timed out after ${timeoutMs}ms.`)),
25
+ timeoutMs
26
+ );
27
+ timer.unref?.();
28
+ });
29
+ return Promise.race([Promise.resolve(value), deadline]).finally(() => clearTimeout(timer));
30
+ }
17
31
 
18
32
  /**
19
33
  * @param {object} options
@@ -23,6 +37,8 @@ const NOOP_LOGGER = { info() {}, warn() {}, error() {} };
23
37
  * @param {Function} [options.isGone] (error) => boolean. Default: 404 or 410.
24
38
  * @param {Function} [options.onGone] async (subscription) => void — delete it
25
39
  * from your store. THIS is the point of the module.
40
+ * @param {number} [options.concurrency=10] Maximum simultaneous sends.
41
+ * @param {number} [options.timeoutMs=30000] Provider deadline for one send.
26
42
  * @param {object} [options.logger]
27
43
  */
28
44
  function createPushSender(options = {}) {
@@ -37,6 +53,14 @@ function createPushSender(options = {}) {
37
53
  });
38
54
  const onGone = options.onGone || null;
39
55
  const logger = options.logger || NOOP_LOGGER;
56
+ const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
57
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
58
+ throw new Error('createPushSender options.concurrency must be a positive integer.');
59
+ }
60
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
61
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1) {
62
+ throw new Error('createPushSender options.timeoutMs must be a positive integer.');
63
+ }
40
64
 
41
65
  /**
42
66
  * Send to ONE subscription.
@@ -44,7 +68,7 @@ function createPushSender(options = {}) {
44
68
  */
45
69
  async function send(subscription, payload) {
46
70
  try {
47
- await transport(subscription, payload);
71
+ await withTimeout(transport(subscription, payload), timeoutMs);
48
72
  return { status: 'delivered' };
49
73
  } catch (error) {
50
74
  if (isGone(error)) {
@@ -65,13 +89,32 @@ function createPushSender(options = {}) {
65
89
  }
66
90
 
67
91
  /**
68
- * Send to MANY. One dead or failing subscription must not stop the others —
69
- * the report says how many of each, and failures carry their reasons.
92
+ * Send to MANY. Awaiting each send in sequence let one slow provider hold
93
+ * every later subscription for hours. Bounded workers isolate that defect
94
+ * without replacing it with an unbounded provider spike.
70
95
  */
71
96
  async function broadcast(subscriptions, payload) {
72
97
  const report = { delivered: 0, gone: 0, failed: 0, errors: [] };
73
- for (const subscription of subscriptions || []) {
74
- const outcome = await send(subscription, payload);
98
+ const items = subscriptions || [];
99
+ const outcomes = new Array(items.length);
100
+ let nextIndex = 0;
101
+
102
+ async function worker() {
103
+ while (nextIndex < items.length) {
104
+ const index = nextIndex;
105
+ nextIndex += 1;
106
+ outcomes[index] = await send(items[index], payload);
107
+ }
108
+ }
109
+
110
+ await Promise.all(Array.from(
111
+ { length: Math.min(concurrency, items.length) },
112
+ () => worker()
113
+ ));
114
+
115
+ /* Completion order is nondeterministic. Aggregate by input index so an
116
+ operator can still match each reported failure to the original batch. */
117
+ for (const outcome of outcomes) {
75
118
  report[outcome.status] += 1;
76
119
  if (outcome.status === 'failed' && report.errors.length < 10) report.errors.push(outcome.error);
77
120
  }