@warlock.js/notifications 4.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.
Files changed (111) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +21 -0
  3. package/README.md +57 -0
  4. package/cjs/index.cjs +1034 -0
  5. package/cjs/index.cjs.map +1 -0
  6. package/esm/channels/database-channel.d.mts +10 -0
  7. package/esm/channels/database-channel.d.mts.map +1 -0
  8. package/esm/channels/database-channel.mjs +19 -0
  9. package/esm/channels/database-channel.mjs.map +1 -0
  10. package/esm/channels/index.d.mts +2 -0
  11. package/esm/channels/index.mjs +4 -0
  12. package/esm/channels/mail-channel.d.mts +11 -0
  13. package/esm/channels/mail-channel.d.mts.map +1 -0
  14. package/esm/channels/mail-channel.mjs +43 -0
  15. package/esm/channels/mail-channel.mjs.map +1 -0
  16. package/esm/config.d.mts +46 -0
  17. package/esm/config.d.mts.map +1 -0
  18. package/esm/config.mjs +32 -0
  19. package/esm/config.mjs.map +1 -0
  20. package/esm/contracts/channel.contract.d.mts +38 -0
  21. package/esm/contracts/channel.contract.d.mts.map +1 -0
  22. package/esm/contracts/index.d.mts +5 -0
  23. package/esm/contracts/notification.contract.d.mts +18 -0
  24. package/esm/contracts/notification.contract.d.mts.map +1 -0
  25. package/esm/contracts/preference-provider.contract.d.mts +20 -0
  26. package/esm/contracts/preference-provider.contract.d.mts.map +1 -0
  27. package/esm/contracts/queue-dispatcher.contract.d.mts +23 -0
  28. package/esm/contracts/queue-dispatcher.contract.d.mts.map +1 -0
  29. package/esm/contracts/rate-limiter.contract.d.mts +23 -0
  30. package/esm/contracts/rate-limiter.contract.d.mts.map +1 -0
  31. package/esm/dispatch/define-channel.d.mts +37 -0
  32. package/esm/dispatch/define-channel.d.mts.map +1 -0
  33. package/esm/dispatch/define-channel.mjs +39 -0
  34. package/esm/dispatch/define-channel.mjs.map +1 -0
  35. package/esm/dispatch/define-notification.d.mts +22 -0
  36. package/esm/dispatch/define-notification.d.mts.map +1 -0
  37. package/esm/dispatch/define-notification.mjs +125 -0
  38. package/esm/dispatch/define-notification.mjs.map +1 -0
  39. package/esm/dispatch/dispatch-id.mjs +15 -0
  40. package/esm/dispatch/dispatch-id.mjs.map +1 -0
  41. package/esm/dispatch/dispatcher.mjs +120 -0
  42. package/esm/dispatch/dispatcher.mjs.map +1 -0
  43. package/esm/dispatch/index.d.mts +4 -0
  44. package/esm/dispatch/index.mjs +6 -0
  45. package/esm/dispatch/notifications-event-bus.d.mts +18 -0
  46. package/esm/dispatch/notifications-event-bus.d.mts.map +1 -0
  47. package/esm/dispatch/notifications-event-bus.mjs +58 -0
  48. package/esm/dispatch/notifications-event-bus.mjs.map +1 -0
  49. package/esm/dispatch/notify.d.mts +20 -0
  50. package/esm/dispatch/notify.d.mts.map +1 -0
  51. package/esm/dispatch/notify.mjs +80 -0
  52. package/esm/dispatch/notify.mjs.map +1 -0
  53. package/esm/errors.d.mts +32 -0
  54. package/esm/errors.d.mts.map +1 -0
  55. package/esm/errors.mjs +56 -0
  56. package/esm/errors.mjs.map +1 -0
  57. package/esm/in-app/base-notifications-repository.d.mts +82 -0
  58. package/esm/in-app/base-notifications-repository.d.mts.map +1 -0
  59. package/esm/in-app/base-notifications-repository.mjs +187 -0
  60. package/esm/in-app/base-notifications-repository.mjs.map +1 -0
  61. package/esm/in-app/column-map.d.mts +65 -0
  62. package/esm/in-app/column-map.d.mts.map +1 -0
  63. package/esm/in-app/column-map.mjs +28 -0
  64. package/esm/in-app/column-map.mjs.map +1 -0
  65. package/esm/in-app/database-notification.d.mts +30 -0
  66. package/esm/in-app/database-notification.d.mts.map +1 -0
  67. package/esm/in-app/database-notification.mjs +70 -0
  68. package/esm/in-app/database-notification.mjs.map +1 -0
  69. package/esm/in-app/in-app.d.mts +56 -0
  70. package/esm/in-app/in-app.d.mts.map +1 -0
  71. package/esm/in-app/in-app.mjs +67 -0
  72. package/esm/in-app/in-app.mjs.map +1 -0
  73. package/esm/in-app/index.d.mts +4 -0
  74. package/esm/in-app/index.mjs +6 -0
  75. package/esm/index.d.mts +25 -0
  76. package/esm/index.mjs +23 -0
  77. package/esm/migration/index.d.mts +1 -0
  78. package/esm/migration/index.mjs +3 -0
  79. package/esm/migration/notification-columns.d.mts +13 -0
  80. package/esm/migration/notification-columns.d.mts.map +1 -0
  81. package/esm/migration/notification-columns.mjs +53 -0
  82. package/esm/migration/notification-columns.mjs.map +1 -0
  83. package/esm/queue/herald-queue.d.mts +10 -0
  84. package/esm/queue/herald-queue.d.mts.map +1 -0
  85. package/esm/queue/herald-queue.mjs +14 -0
  86. package/esm/queue/herald-queue.mjs.map +1 -0
  87. package/esm/queue/index.d.mts +3 -0
  88. package/esm/queue/index.mjs +5 -0
  89. package/esm/queue/load-herald.d.mts +6 -0
  90. package/esm/queue/load-herald.d.mts.map +1 -0
  91. package/esm/queue/load-herald.mjs +35 -0
  92. package/esm/queue/load-herald.mjs.map +1 -0
  93. package/esm/queue/notifications-worker.d.mts +9 -0
  94. package/esm/queue/notifications-worker.d.mts.map +1 -0
  95. package/esm/queue/notifications-worker.mjs +46 -0
  96. package/esm/queue/notifications-worker.mjs.map +1 -0
  97. package/esm/types.d.mts +130 -0
  98. package/esm/types.d.mts.map +1 -0
  99. package/llms-full.txt +994 -0
  100. package/llms.txt +17 -0
  101. package/package.json +40 -0
  102. package/skills/README.md +23 -0
  103. package/skills/configure-notifications/SKILL.md +138 -0
  104. package/skills/define-channel/SKILL.md +107 -0
  105. package/skills/define-notification/SKILL.md +133 -0
  106. package/skills/notifications-basics/SKILL.md +94 -0
  107. package/skills/observe-notifications/SKILL.md +66 -0
  108. package/skills/queue-notifications/SKILL.md +81 -0
  109. package/skills/send-ad-hoc/SKILL.md +95 -0
  110. package/skills/use-in-app/SKILL.md +168 -0
  111. package/skills/write-notification-migration/SKILL.md +70 -0
package/llms-full.txt ADDED
@@ -0,0 +1,994 @@
1
+ # Warlock Notifications — full skills
2
+
3
+ > Package: `@warlock.js/notifications`
4
+
5
+ > Generated artifact. Concatenates every SKILL.md and reference file under `@warlock.js/notifications/skills/`. Re-run `node scripts/generate-llms.mjs` after any change.
6
+
7
+ ## configure-notifications `@warlock.js/notifications/configure-notifications/SKILL.md`
8
+
9
+ ---
10
+ name: configure-notifications
11
+ description: 'Wire `@warlock.js/notifications` via a declarative `src/config/notifications.ts` that exports a `NotificationConfig` default — the notifications connector registers it at boot, so app code never calls `setNotificationConfig`. `channels`: registry mapping name → factory result (`mailChannel`, `inApp.configure`, custom `defineChannel`); `queue`: optional `QueueDispatcher` (`.queue()` throws without it); `preferences`: optional `PreferenceProvider` (drops channels the recipient muted); `rateLimit`: optional `RateLimiter` (drops channels exceeding per-recipient budgets). Triggers: `config/notifications.ts`, `NotificationConfig`, `setNotificationConfig`, `getNotificationConfig`, `mailChannel`, `inApp.configure`, "configure notifications", "wire notifications at boot", "set preferences provider", "set rate limit"; typical import `import { type NotificationConfig, mailChannel, inApp } from "@warlock.js/notifications"`. Skip: building a reusable notification — `@warlock.js/notifications/define-notification/SKILL.md`; the in-app read API — `@warlock.js/notifications/use-in-app/SKILL.md`; adding a custom channel — `@warlock.js/notifications/define-channel/SKILL.md`.'
12
+ ---
13
+
14
+ # Configure notifications
15
+
16
+ `src/config/notifications.ts` exports a `NotificationConfig` as its default; the notifications connector registers it at boot and the dispatcher reads from it on every send. The file is **declarative** — you never call `setNotificationConfig` yourself (the connector does, the same way the rest of `src/config/*.ts` is wired).
17
+
18
+ > `npx warlock add notifications` ejects this file pre-wired (mail + in-app) alongside the `Notification` model + migration. Edit the ejected config to taste — the sections below are the full surface.
19
+
20
+ ## Minimal
21
+
22
+ ```ts title="src/config/notifications.ts"
23
+ import { type NotificationConfig, inApp, mailChannel } from "@warlock.js/notifications";
24
+ import { Notification } from "app/notifications/notification.model";
25
+
26
+ const config: NotificationConfig = {
27
+ channels: {
28
+ mail: mailChannel({ from: "no-reply@store.com" }),
29
+ database: inApp.configure({ model: Notification }),
30
+ },
31
+ };
32
+
33
+ export default config;
34
+ ```
35
+
36
+ The `database` channel is returned by `inApp.configure({ model | repository })` — it binds the in-app store AND returns the channel, so the read side + the write side share ONE repository instance.
37
+
38
+ ## Full surface
39
+
40
+ ```ts
41
+ const config: NotificationConfig = {
42
+ channels: {
43
+ mail: mailChannel({ from }),
44
+ database: inApp.configure({ model: Notification }),
45
+
46
+ // custom channels
47
+ discord: discordChannel(), // defineChannel + declare module
48
+ },
49
+
50
+ // optional gates — both app-owned; package ships no defaults
51
+ preferences: userPreferences, // drops channels recipient muted
52
+ rateLimit, // drops channels over budget
53
+ queue: heraldQueue(), // backs `.queue()` (needs @warlock.js/herald)
54
+ };
55
+
56
+ export default config;
57
+ ```
58
+
59
+ ## Channel keys must match the registry
60
+
61
+ `channels: { mail, database, discord }` — keys correspond to `NotificationChannels` entries. Built-ins (`mail`, `database`) ship in the registry; custom channels extend it with `declare module`.
62
+
63
+ ```ts
64
+ // in your custom channel file
65
+ declare module "@warlock.js/notifications" {
66
+ interface NotificationChannels {
67
+ discord: { content: string };
68
+ }
69
+ }
70
+ ```
71
+
72
+ After that, `notify.discord(...)`, `via: ["discord"]`, and the `discord:` key in `defineNotification` all autocomplete + type-check.
73
+
74
+ ## `inApp.configure({ model | repository })`
75
+
76
+ Two paths; mutually exclusive at the type level.
77
+
78
+ ```ts
79
+ // 90% case — pass the model class; default repo built internally.
80
+ database: inApp.configure({ model: Notification }),
81
+
82
+ // 10% case — pass a custom repo (only for EXTRA query methods; column names
83
+ // come from the model's columnMap, not a repo override).
84
+ database: inApp.configure({ repository: notificationsRepository }),
85
+ ```
86
+
87
+ There is NO zero-arg form — the package ships no concrete table/model.
88
+
89
+ ## `preferences` — pre-send opt-in gate (optional)
90
+
91
+ ```ts
92
+ import type { PreferenceProvider } from "@warlock.js/notifications";
93
+
94
+ export const userPreferences: PreferenceProvider = {
95
+ resolveChannels(user, type, requested) {
96
+ const muted: Record<string, string[]> = user.get("preferences.muted") ?? {};
97
+ return requested.filter((c) => !(muted[c] ?? []).includes(type));
98
+ },
99
+ };
100
+ ```
101
+
102
+ Dropped channels fire a `skipped` event with reason `"preference"`. `SendOptions.force === true` bypasses this gate.
103
+
104
+ ## `rateLimit` — pre-send safety valve (optional)
105
+
106
+ ```ts
107
+ import { cache } from "@warlock.js/cache";
108
+ import type { RateLimiter } from "@warlock.js/notifications";
109
+
110
+ export const rateLimit: RateLimiter = {
111
+ async allow(user, channel, type) {
112
+ const key = `notif.rl.${user.id}.${channel}.${type}`;
113
+ const count = await cache.increment(key, 1);
114
+ if (count === 1) await cache.set(key, 1, { ttl: 3600 });
115
+ return count <= 5;
116
+ },
117
+ };
118
+ ```
119
+
120
+ Dropped channels fire a `skipped` event with reason `"rate-limit"`. `force` does NOT bypass this — rate limits are a safety valve, not a UX preference.
121
+
122
+ ## Reading the config back
123
+
124
+ ```ts
125
+ import { getNotificationConfig } from "@warlock.js/notifications";
126
+
127
+ const cfg = getNotificationConfig(); // throws NotificationsNotConfiguredError if unset
128
+ ```
129
+
130
+ ## Tests
131
+
132
+ Tests call `setNotificationConfig` directly — bypassing the connector — to set state, then `resetNotificationConfig` to tear down:
133
+
134
+ ```ts
135
+ import { resetNotificationConfig, setNotificationConfig } from "@warlock.js/notifications";
136
+
137
+ beforeEach(() => setNotificationConfig({ channels: { ... } }));
138
+ afterEach(() => resetNotificationConfig());
139
+ ```
140
+
141
+ ## See also
142
+
143
+ - [`notifications-basics/SKILL.md`](../notifications-basics/SKILL.md) — package front door.
144
+ - [`define-notification/SKILL.md`](../define-notification/SKILL.md) — reusable multi-channel definitions.
145
+ - [`use-in-app/SKILL.md`](../use-in-app/SKILL.md) — in-app read API.
146
+ - [`define-channel/SKILL.md`](../define-channel/SKILL.md) — custom channels.
147
+
148
+
149
+ ## define-channel `@warlock.js/notifications/define-channel/SKILL.md`
150
+
151
+ ---
152
+ name: define-channel
153
+ description: 'Add a custom notification channel — `defineChannel<P>({ name, route?, send })` returns a `Channel<P>` you register in the `channels` map of `setNotificationConfig`. `name` matches the key in `NotificationChannels` (extend via `declare module` for typing); `route(notifiable)` resolves the recipient''s address (defaults to `{ id }` when omitted); `send({ payload, route, notifiable, options })` does the actual transport. Use for Slack/Discord/internal-webhook/anything else — `fetch`-based with NO SDK is the simplest variant. Channels that load a heavy SDK should follow the lazy-import pattern from the develop-feature playbook. Triggers: `defineChannel`, `Channel<P>`, "custom notification channel", "add discord channel", "slack channel", "webhook channel", "new channel type", `declare module "@warlock.js/notifications"`; typical import `import { defineChannel } from "@warlock.js/notifications"`. Skip: lazy-loading an optional SDK behind the channel — `D:/xampp/htdocs/mongez/node/.claude/skills/develop-warlock.js-feature/SKILL.md`; using built-in channels — `@warlock.js/notifications/configure-notifications/SKILL.md`.'
154
+ ---
155
+
156
+ # `defineChannel` — custom channels
157
+
158
+ The escape hatch for channel types the package doesn't ship.
159
+
160
+ ## Minimal — `fetch`-based webhook (no SDK)
161
+
162
+ ```ts title="src/app/notifications/channels/discord.channel.ts"
163
+ import { defineChannel } from "@warlock.js/notifications";
164
+
165
+ type DiscordPayload = { content: string };
166
+
167
+ export const discordChannel = () =>
168
+ defineChannel<DiscordPayload>({
169
+ name: "discord",
170
+ route: (notifiable) => notifiable.get("discord_webhook") as string,
171
+ async send({ payload, route }) {
172
+ const response = await fetch(route as string, {
173
+ method: "POST",
174
+ headers: { "content-type": "application/json" },
175
+ body: JSON.stringify(payload),
176
+ });
177
+ if (!response.ok) throw new Error(`Discord send failed: ${response.status}`);
178
+ },
179
+ });
180
+
181
+ // Teach TypeScript about the new channel — picks up notify.discord and
182
+ // `defineNotification` typing.
183
+ declare module "@warlock.js/notifications" {
184
+ interface NotificationChannels {
185
+ discord: DiscordPayload;
186
+ }
187
+ }
188
+ ```
189
+
190
+ Register in `config/notifications.ts`:
191
+
192
+ ```ts
193
+ channels: {
194
+ // ...
195
+ discord: discordChannel(),
196
+ }
197
+ ```
198
+
199
+ Now `notify.discord(user, { content: "🎉" })` works, and `discord:` is a valid renderer key in `defineNotification`.
200
+
201
+ ## `route` resolution
202
+
203
+ | What `route` returns | Effect |
204
+ |---|---|
205
+ | `string` | Used directly as the address (`"user@example.com"`, webhook URL). |
206
+ | `{ id: Id }` | The recipient's storage id — for database/internal channels. |
207
+ | `undefined` | Dispatcher falls back to `{ id: notifiable.id }`. |
208
+ | `route` omitted | Same as returning `undefined` — `{ id }` fallback. |
209
+
210
+ For raw-target ad-hoc sends (`notify.discord("https://hooks.../foo", payload)`), the raw string wins over `route()`.
211
+
212
+ ## `send` — the contract
213
+
214
+ ```ts
215
+ async send({
216
+ payload, // P — the channel's payload type
217
+ route, // string | { id: Id } — resolved by `route()` or raw target
218
+ notifiable, // Notifiable | undefined — undefined for raw-target ad-hoc
219
+ options, // SendOptions — delay/locale/meta/idempotencyKey/force/type
220
+ }): Promise<void>
221
+ ```
222
+
223
+ Throw to fail the send. The dispatcher catches per channel, fires a `failed` event, and continues with siblings (per-channel isolation).
224
+
225
+ ## SDK-backed channels — lazy-import the SDK
226
+
227
+ Channels that wrap a heavy SDK (Twilio, Slack SDK, FCM SDK) should follow the lazy-import pattern so apps that don't use them don't pay the install/load cost. The recipe + race-safe template lives in [`develop-warlock.js-feature`](../../../../.claude/skills/develop-warlock.js-feature/SKILL.md) — copy from there; do not invent a variant.
228
+
229
+ Sketch:
230
+
231
+ ```ts
232
+ import type { WebClient } from "@slack/web-api";
233
+ let Slack: typeof import("@slack/web-api");
234
+ let isModuleExists: boolean | null = null;
235
+
236
+ async function loadSlack() { /* try/catch await import; set flag */ }
237
+ loadSlack();
238
+
239
+ export const slackChannel = (config: { token: string }) =>
240
+ defineChannel<{ text: string }>({
241
+ name: "slack",
242
+ route: (n) => n.get("slack_channel"),
243
+ async send({ payload, route }) {
244
+ await loadSlack();
245
+ if (!isModuleExists) throw new Error(INSTALL_INSTRUCTIONS);
246
+ const client = new Slack.WebClient(config.token);
247
+ await client.chat.postMessage({ channel: route as string, text: payload.text });
248
+ },
249
+ });
250
+ ```
251
+
252
+ ## See also
253
+
254
+ - [`configure-notifications/SKILL.md`](../configure-notifications/SKILL.md) — register channels in the config.
255
+ - [`send-ad-hoc/SKILL.md`](../send-ad-hoc/SKILL.md) — `notify.<custom-channel>` works after registration.
256
+ - [`define-notification/SKILL.md`](../define-notification/SKILL.md) — multi-channel renderers with the custom channel key.
257
+ - `D:/xampp/htdocs/mongez/node/.claude/skills/develop-warlock.js-feature/SKILL.md` — lazy-import pattern for SDK-backed channels.
258
+
259
+
260
+ ## define-notification `@warlock.js/notifications/define-notification/SKILL.md`
261
+
262
+ ---
263
+ name: define-notification
264
+ description: 'Build a reusable multi-channel notification with `defineNotification<Data>({ type, via, ...renderers })`. `type` is the stable identifier preference/rate-limit gates use AND defaults the database channel''s `type`. `via` is `ChannelName[]` OR `(data, to) => ChannelName[]` for per-recipient channel selection. Renderers are `(data, to, ctx) => NotificationChannels[C]`; `ctx` carries `locale` + `meta` from `SendOptions`. The returned object exposes `.send(to|to[], data, options?)`, `.queue(to|to[], data, options?)`, and `.only(...channels)`. Per-recipient + per-channel `Promise.allSettled` isolates failures; the database channel''s `type` is auto-defaulted from `def.type`; `SendOptions.idempotencyKey` is injected into the database payload. Triggers: `defineNotification`, `via`, "reusable notification", "multi-channel notification", "send through several channels at once", "render per channel", `RenderContext`, `def.type`; "force on a notification", "queue with delay"; typical import `import { defineNotification } from "@warlock.js/notifications"`. Skip: single-channel ad-hoc sends — `@warlock.js/notifications/send-ad-hoc/SKILL.md`; adding a brand-new channel — `@warlock.js/notifications/define-channel/SKILL.md`; observing dispatch outcomes — `@warlock.js/notifications/observe-notifications/SKILL.md`.'
265
+ ---
266
+
267
+ # `defineNotification` — reusable multi-channel notification
268
+
269
+ The reusable pattern. Define a notification once with `type` + `via` + a renderer per channel; fire it anywhere with `.send` / `.queue` / `.only`.
270
+
271
+ ## Shape
272
+
273
+ ```ts
274
+ defineNotification<Data>({
275
+ type: string, // REQUIRED — gate key + database default
276
+ via: ChannelName[] | (data, to) => ChannelName[], // static array OR per-recipient callback
277
+ mail?: (data, to, ctx) => MailPayload,
278
+ database?: (data, to, ctx) => Omit<DatabasePayload, "type">, // `type` defaulted from `def.type`
279
+ // ...one renderer per channel listed in `via`
280
+ });
281
+ ```
282
+
283
+ Returns `{ send, queue, only }`:
284
+
285
+ | Method | Signature | What it does |
286
+ |---|---|---|
287
+ | `.send` | `(to, data, options?)` | Render + dispatch synchronously. |
288
+ | `.queue` | `(to, data, options?)` | Render + enqueue. Throws if no queue dispatcher is configured. |
289
+ | `.only(...channels)` | returns `{send, queue, only}` | Restrict dispatch to a subset of channels. |
290
+
291
+ `to` accepts a `Notifiable` OR a `Notifiable[]`. Fan-out emits one render+dispatch per recipient with per-recipient + per-channel `Promise.allSettled` (one failure does not abort the others).
292
+
293
+ ## Static `via`
294
+
295
+ ```ts
296
+ export const welcome = defineNotification<{ name: string }>({
297
+ type: "welcome",
298
+ via: ["mail"],
299
+ mail: ({ name }) => ({ subject: "Welcome", html: `<p>Hi ${name}</p>` }),
300
+ });
301
+
302
+ await welcome.send(user, { name: "Hasan" });
303
+ ```
304
+
305
+ ## Dynamic `via` per recipient
306
+
307
+ ```ts
308
+ export const orderShipped = defineNotification<{ order: Order }>({
309
+ type: "order.shipped",
310
+ via: (_data, to) =>
311
+ to.get("telegram_chat_id")
312
+ ? ["database", "telegram"]
313
+ : ["database", "mail"],
314
+ database: ({ order }) => ({ title: `Order #${order.number} shipped` }),
315
+ mail: ({ order }, to) => ({
316
+ subject: `Order #${order.number} shipped`,
317
+ html: `<p>Hi ${to.get("name")}, on the way.</p>`,
318
+ }),
319
+ // telegram: ... (Phase 2 — bridges)
320
+ });
321
+ ```
322
+
323
+ ## The renderer's 3rd arg — `RenderContext`
324
+
325
+ ```ts
326
+ mail: ({ campaignId }, to, { locale = "en", meta }) => ({
327
+ subject: subjectsByLocale[locale],
328
+ html: htmlByLocale[locale],
329
+ }),
330
+
331
+ // usage:
332
+ await marketing.queue(user, payload, {
333
+ locale: user.get("locale"),
334
+ meta: { campaignId, source: "blast" },
335
+ });
336
+ ```
337
+
338
+ `ctx` carries `locale` + `meta` from `SendOptions`. `meta` flows through to every observability event too.
339
+
340
+ ## Database channel — `type` is defaulted
341
+
342
+ The `database` renderer may OMIT `type` — the dispatcher injects `def.type` automatically. This keeps the notification type in ONE place.
343
+
344
+ ```ts
345
+ defineNotification({
346
+ type: "order.shipped", // ← single source of truth
347
+ via: ["database"],
348
+ database: () => ({ title: "Shipped" }), // type omitted; dispatcher injects "order.shipped"
349
+ });
350
+ ```
351
+
352
+ ## Fan-out
353
+
354
+ ```ts
355
+ await orderShipped.send([buyer, salesRep], { order });
356
+ // One render+dispatch per recipient. Database does N inserts (Phase 0);
357
+ // Phase 1 ships a single bulk insert via `Channel.sendMany?`.
358
+ ```
359
+
360
+ ## `.only(...)` — restrict channels
361
+
362
+ ```ts
363
+ await orderShipped.only("mail").send(user, { order });
364
+ // `via` is filtered to just "mail"; other channels are skipped.
365
+ ```
366
+
367
+ ## Queue (Phase 2)
368
+
369
+ ```ts
370
+ await orderShipped.queue(user, { order }, { delay: "10m" });
371
+ // Throws NoQueueDispatcherError if no `queue` is configured in config/notifications.ts.
372
+ ```
373
+
374
+ ## SendOptions
375
+
376
+ | Field | Effect |
377
+ |---|---|
378
+ | `delay` | Reserved — `"10m"` / `"3d"` / `600` (seconds). NOT honored yet: both `.send()` and the current `.queue()` worker dispatch immediately; delay-aware delivery is a follow-up. |
379
+ | `locale` | Passed to renderers via `RenderContext.locale`. |
380
+ | `meta` | Passed to renderers + included in every observability event. |
381
+ | `idempotencyKey` | Injected into the database payload (dedupe via unique index). |
382
+ | `force` | Bypass `PreferenceProvider`. Does NOT bypass `RateLimiter`. |
383
+ | `type` | Ignored by `defineNotification` — see `send-ad-hoc` for ad-hoc gating. |
384
+
385
+ ## Failure isolation
386
+
387
+ Per-recipient: each recipient gets an independent `Promise.allSettled`. Per-channel: each channel within a recipient gets an independent `allSettled`. A throw becomes a `failed` event on the event bus AND re-throws within its own slot — never aborts siblings.
388
+
389
+ ## See also
390
+
391
+ - [`notifications-basics/SKILL.md`](../notifications-basics/SKILL.md) — package front door.
392
+ - [`send-ad-hoc/SKILL.md`](../send-ad-hoc/SKILL.md) — `notify.<channel>` per-channel shorthand.
393
+ - [`configure-notifications/SKILL.md`](../configure-notifications/SKILL.md) — wire channels + preferences + rate-limit + queue.
394
+ - [`observe-notifications/SKILL.md`](../observe-notifications/SKILL.md) — `notifications.on("sending" | "sent" | "failed" | "skipped", …)`.
395
+
396
+
397
+ ## notifications-basics `@warlock.js/notifications/notifications-basics/SKILL.md`
398
+
399
+ ---
400
+ name: notifications-basics
401
+ description: 'Front-door for `@warlock.js/notifications` — what the package is, when to reach for it, and the four moving parts (channel registry, defineNotification, notify, inApp). Multi-channel dispatch: define once, fire anywhere. Recipients are cascade `Model` instances; payloads are typed per channel via a declaration-merge `NotificationChannels` registry; reusable definitions go through `defineNotification`; ad-hoc per-channel sends go through the `notify.<channel>` proxy; the in-app database channel is read via the `inApp` facade. Phase 1 ships `mail` + `database`; bridges-backed channels (whatsapp/telegram/push/slack) arrive in Phase 2. Triggers: `defineNotification`, `notify.<channel>`, `inApp.configure`, `setNotificationConfig`, `NotificationConfig`, `NotificationChannels`; "send a notification", "in-app notifications", "what channels can I use", "what is `@warlock.js/notifications`", "where do I start"; typical import `import { defineNotification, notify, inApp } from "@warlock.js/notifications"`. Skip: configuring channels in `config/notifications.ts` — `@warlock.js/notifications/configure-notifications/SKILL.md`; building a multi-channel definition — `@warlock.js/notifications/define-notification/SKILL.md`; reading in-app rows — `@warlock.js/notifications/use-in-app/SKILL.md`.'
402
+ ---
403
+
404
+ # `@warlock.js/notifications` — basics
405
+
406
+ Multi-channel notifications for Warlock.js. **Define once, fire anywhere.**
407
+
408
+ ## What the package is for
409
+
410
+ You have an event (`order.shipped`, `comment.mentioned`, `password.changed`) and one or more recipients. You want to address them through any combination of channels (mail, in-app, push, ...) with one render. That's what this package is.
411
+
412
+ It is NOT a queue, a template engine, a transport library, or an analytics pipeline — it orchestrates *over* the transports cascade / core / herald / bridges already provide.
413
+
414
+ ## Four moving parts
415
+
416
+ 1. **`NotificationChannels`** — a TypeScript interface (declaration-merge target) mapping channel name → payload type. Drives `notify.<channel>` typing and `defineNotification` renderers.
417
+ 2. **`defineNotification`** — reusable multi-channel notification. Pass a `type`, a `via`, and a renderer per channel. Returns `{ send, queue, only }`.
418
+ 3. **`notify`** — Proxy facade for ad-hoc single-channel sends. `notify.<channel>(to, payload, options?)` works for any registered channel.
419
+ 4. **`inApp`** — facade for the database channel's read side. `inApp.configure({ model })` in the config returns the channel; `inApp.listUnread` / `markAsRead` / `markAsUnread` are the read API.
420
+
421
+ ## Minimal end-to-end
422
+
423
+ `npx warlock add notifications` ejects the config + model + migration. The config is **declarative** — the notifications connector registers its default export at boot, so you never call `setNotificationConfig` yourself.
424
+
425
+ ```ts title="src/config/notifications.ts"
426
+ import { type NotificationConfig, mailChannel, inApp } from "@warlock.js/notifications";
427
+ import { Notification } from "app/notifications/notification.model";
428
+
429
+ const config: NotificationConfig = {
430
+ channels: {
431
+ mail: mailChannel({ from: "no-reply@store.com" }),
432
+ database: inApp.configure({ model: Notification }),
433
+ },
434
+ };
435
+
436
+ export default config;
437
+ ```
438
+
439
+ ```ts title="src/app/orders/notifications/order-shipped.ts"
440
+ import { defineNotification } from "@warlock.js/notifications";
441
+
442
+ export const orderShipped = defineNotification<{ orderId: string; number: string }>({
443
+ type: "order.shipped",
444
+ via: ["database", "mail"],
445
+ database: ({ orderId, number }) => ({
446
+ title: `Order #${number} shipped`,
447
+ payload: { orderId },
448
+ }),
449
+ mail: ({ number }, to) => ({
450
+ subject: `Order #${number} shipped`,
451
+ html: `<p>Hi ${to.get("name")}, on the way.</p>`,
452
+ }),
453
+ });
454
+ ```
455
+
456
+ ```ts title="anywhere"
457
+ import { notify, inApp } from "@warlock.js/notifications";
458
+ import { orderShipped } from "app/orders/notifications/order-shipped";
459
+
460
+ await orderShipped.send(user, { orderId: order.id, number: order.number });
461
+ await notify.mail(user, { subject: "Welcome", html: "<p>Hi!</p>" });
462
+
463
+ const unread = await inApp.listUnread(user);
464
+ const badge = await inApp.countUnread(user);
465
+ await inApp.markAsRead(user, "ntf_123");
466
+ ```
467
+
468
+ ## Recipient = cascade `Model` instance
469
+
470
+ `Notifiable` is typed as `Model`, so any cascade model is a valid recipient — `.id` (number | string) and `.get(path)` come for free. Routing is a **channel concern**, not a model concern — channels resolve `notifiable.email` / `.phone` / `.id` / etc. by convention (overridable in channel config).
471
+
472
+ ## Phase 1 vs Phase 2
473
+
474
+ | Channel | Phase | How |
475
+ |---|---|---|
476
+ | `mail` | 1 ✅ | core `sendMail` |
477
+ | `database` | 1 ✅ | cascade repo (recipient-scoped reads) |
478
+ | `whatsapp` | 2 | bridges `MessageProvider` |
479
+ | `telegram` | 2 | bridges `MessageProvider` |
480
+ | `slack` | 2 | bridges `MessageProvider` |
481
+ | `push` | 2 | bridges `PushProvider` |
482
+ | your own | 1 ✅ | `defineChannel` + 3-line `declare module` |
483
+
484
+ ## See also
485
+
486
+ - [`configure-notifications/SKILL.md`](../configure-notifications/SKILL.md) — wire `config/notifications.ts`.
487
+ - [`define-notification/SKILL.md`](../define-notification/SKILL.md) — reusable multi-channel definitions.
488
+ - [`send-ad-hoc/SKILL.md`](../send-ad-hoc/SKILL.md) — `notify.<channel>` shorthand.
489
+ - [`use-in-app/SKILL.md`](../use-in-app/SKILL.md) — `inApp` read API.
490
+ - [`define-channel/SKILL.md`](../define-channel/SKILL.md) — custom channels.
491
+ - [`write-notification-migration/SKILL.md`](../write-notification-migration/SKILL.md) — columnMap-driven columns.
492
+ - [`observe-notifications/SKILL.md`](../observe-notifications/SKILL.md) — events + metrics.
493
+
494
+
495
+ ## observe-notifications `@warlock.js/notifications/observe-notifications/SKILL.md`
496
+
497
+ ---
498
+ name: observe-notifications
499
+ description: 'Wire metrics, logging, tracing, and audits via `notifications.on(event, handler)` — four events fire per (channel, recipient): `sending` (gates passed, about to hit the transport), `sent` (succeeded), `failed` (channel threw — carries the Error), `skipped` (a pre-send gate dropped it — carries `reason: "preference" | "rate-limit"`). Every event carries the recipient as `notifiable?` (undefined only for raw-target ad-hoc sends) and a `dispatchId` — `sending` and its terminal `sent`/`failed` share it, so observers can pair them (spans, latency, hung-send detection). `sent`/`failed` also carry `durationMs`. Handler exceptions are logged-and-swallowed so one bad listener can not break the dispatcher. `on(...)` returns an unsubscribe function; `off(event, handler)` exists for symmetry. Triggers: `notifications.on`, `notifications.off`, `"sending"` event, `"sent"` event, `"failed"` event, `"skipped"` event, `dispatchId`, `durationMs`, `NotificationEvents`, "notification metrics", "notification latency", "trace notifications", "notification audit log", "track notification drops"; typical import `import { notifications } from "@warlock.js/notifications"`. Skip: building notifications — `@warlock.js/notifications/define-notification/SKILL.md`; configuring the preference/rate-limit gates that produce `skipped` — `@warlock.js/notifications/configure-notifications/SKILL.md`.'
500
+ ---
501
+
502
+ # Observe notifications
503
+
504
+ Every dispatch emits a `sending` event then a terminal `sent` / `failed` — or a `skipped` if a gate dropped it — per (channel, recipient).
505
+
506
+ ```ts
507
+ import { notifications } from "@warlock.js/notifications";
508
+
509
+ // latency + delivery, keyed by recipient
510
+ notifications.on("sent", ({ channel, notifiable, durationMs, options }) =>
511
+ metrics.timing(`notif.${channel}.sent`, durationMs, { userId: notifiable?.id, ...options.meta }));
512
+
513
+ notifications.on("failed", ({ channel, notifiable, error }) =>
514
+ log.error(`notif.${channel}`, error, { userId: notifiable?.id }));
515
+
516
+ notifications.on("skipped", ({ channel, reason }) =>
517
+ metrics.inc(`notif.${channel}.skipped.${reason}`));
518
+
519
+ // pair `sending` → terminal by dispatchId — open a span / arm a hung-send watchdog
520
+ notifications.on("sending", ({ dispatchId, channel, notifiable }) =>
521
+ tracer.open(dispatchId, { channel, userId: notifiable?.id }));
522
+ ```
523
+
524
+ ## Events
525
+
526
+ | Event | Fires when | Payload |
527
+ |---|---|---|
528
+ | `sending` | Gates passed; about to hit the transport (sync) / enqueue (queue) | `{ dispatchId, channel, notifiable?, payload, options }` |
529
+ | `sent` | Channel dispatched OR job enqueued | `{ dispatchId, channel, notifiable?, payload, options, durationMs }` |
530
+ | `failed` | `channel.send` (or `queue.dispatch`) threw | `{ dispatchId, channel, notifiable?, payload, error, options, durationMs }` |
531
+ | `skipped` | A pre-send gate dropped this channel | `{ dispatchId, channel, notifiable?, reason, options }` — `reason: "preference" \| "rate-limit"` |
532
+
533
+ `notifiable` is the recipient **model** (undefined only for raw-target ad-hoc sends like `notify.mail("x@y.com", …)`) — read `notifiable?.id` / `notifiable?.get(...)` to key your metrics or logs.
534
+
535
+ `dispatchId` is unique per (channel, recipient) dispatch — `sending` and its terminal `sent`/`failed` share it, so you can pair them for a span, a latency measurement, or a watchdog that flags a `sending` with no terminal (a hung send). `durationMs` is transport time on a sync send, enqueue time on a queued one.
536
+
537
+ `options` is the `SendOptions` passed at the call site — including `meta`. Tagging a send with `meta: { campaignId }` lets downstream observers join the event back to the campaign.
538
+
539
+ ## Unsubscribe
540
+
541
+ ```ts
542
+ const off = notifications.on("sent", handler);
543
+ // later
544
+ off();
545
+
546
+ // or
547
+ notifications.off("sent", handler);
548
+ ```
549
+
550
+ ## Fan-out emits N events
551
+
552
+ `orderShipped.send([buyer, salesRep], { order })` with `via: ["mail", "database"]` fires up to **4** `sent` events (2 recipients × 2 channels). Aggregate by `meta` or by `channel + notifiable.id` in your observer.
553
+
554
+ ## Handler isolation
555
+
556
+ A handler that throws is logged and swallowed — the other handlers for the same event still run, and the dispatcher never observes the throw. Observers can't **abort** a send (there's no veto here — use `preferences` / `rateLimit` for that). They can delay it, though: `sending` is awaited before the transport, so keep that handler fast.
557
+
558
+ ## See also
559
+
560
+ - [`notifications-basics/SKILL.md`](../notifications-basics/SKILL.md) — front door + mental model.
561
+ - [`configure-notifications/SKILL.md`](../configure-notifications/SKILL.md) — `preferences` / `rateLimit` slots that emit `skipped`.
562
+ - [`send-ad-hoc/SKILL.md`](../send-ad-hoc/SKILL.md) — when `notifiable` is undefined in events.
563
+
564
+
565
+ ## queue-notifications `@warlock.js/notifications/queue-notifications/SKILL.md`
566
+
567
+ ---
568
+ name: queue-notifications
569
+ description: 'Send notifications asynchronously via the herald-backed queue. `heraldQueue({ channel?, broker? })` is a `QueueDispatcher` you add to the `queue` slot of the declarative `config/notifications.ts` (the connector registers it at boot); then `notif.queue(to, data, options?)` / `notify` publish a rendered job instead of sending inline. `startNotificationsWorker({ channel?, broker? })` runs the consumer (in a worker or the web process) that pulls jobs and runs `channel.send`. Both lazy-import `@warlock.js/herald` (optional peer) — a missing package throws a curated install message at use time. `defineNotification` renders payloads + resolves routes BEFORE queuing, so the job (`{ channel, route, payload, options }`) is fully serializable — no model re-hydration. Without a queue configured, `.queue()` rejects `NoQueueDispatcherError`. Triggers: `heraldQueue`, `startNotificationsWorker`, `QueueDispatcher`, `.queue(`, "async notifications", "queue notifications", "notification worker", "background notifications", `notifications.dispatch`; typical import `import { heraldQueue, startNotificationsWorker } from "@warlock.js/notifications"`. Skip: synchronous sends — `@warlock.js/notifications/define-notification/SKILL.md`; herald itself — `@warlock.js/herald/*`.'
570
+ ---
571
+
572
+ # Queue notifications (async)
573
+
574
+ Move slow channels (SMTP, HTTP) off the request path. `.queue()` publishes a
575
+ rendered job to herald; a worker delivers it.
576
+
577
+ ## Wire the dispatcher
578
+
579
+ ```ts title="src/config/notifications.ts"
580
+ import { type NotificationConfig, heraldQueue, inApp, mailChannel } from "@warlock.js/notifications";
581
+ import { Notification } from "app/notifications/notification.model";
582
+
583
+ const config: NotificationConfig = {
584
+ channels: { mail: mailChannel(), database: inApp.configure({ model: Notification }) },
585
+ queue: heraldQueue(), // → `.queue()` now works
586
+ };
587
+
588
+ export default config; // the notifications connector registers it at boot
589
+ ```
590
+
591
+ `heraldQueue({ channel?, broker? })` publishes to `"notifications.dispatch"` on
592
+ the default broker unless overridden. It lazy-imports `@warlock.js/herald`; if
593
+ that package isn't installed, the first `.queue()` throws an install message.
594
+
595
+ Without `queue` configured, `.queue()` rejects `NoQueueDispatcherError` — a loud
596
+ config error, not a silent no-op.
597
+
598
+ ## Run the worker
599
+
600
+ In a worker entrypoint (or the web process), after the config + the herald
601
+ broker are up:
602
+
603
+ ```ts
604
+ import { startNotificationsWorker } from "@warlock.js/notifications";
605
+
606
+ await startNotificationsWorker(); // subscribes to "notifications.dispatch"
607
+ ```
608
+
609
+ The worker pulls each job, looks the channel up by name, and runs
610
+ `channel.send({ payload, route, options })`. The job carries an
611
+ ALREADY-RENDERED payload + resolved route (rendering happens at enqueue), so the
612
+ worker needs no recipient model.
613
+
614
+ ## Send
615
+
616
+ ```ts
617
+ await orderShipped.queue(user, { order }); // async
618
+ await orderShipped.queue(buyers, { order }, { delay: "10m" });
619
+ await notify.mail(user, payload, { /* sync — notify.* doesn't queue */ });
620
+ ```
621
+
622
+ `.queue()` renders synchronously then enqueues. Fan-out renders per recipient
623
+ and enqueues one job each.
624
+
625
+ ## Idempotency
626
+
627
+ Pass `idempotencyKey` so a redelivered/retried job doesn't create a duplicate
628
+ in-app row — `createFor` find-or-creates on the key.
629
+
630
+ ```ts
631
+ await orderShipped.queue(user, { order }, { idempotencyKey: `ship:${order.id}` });
632
+ ```
633
+
634
+ ## Phase notes / current limits
635
+
636
+ - **`delay` is carried on the job but not yet honored** — the worker delivers
637
+ immediately. Delay-aware delivery lands with a scheduled worker.
638
+ - **No retry / dead-letter yet** — a failed `channel.send` is logged + acked
639
+ (no poison-message loop). DLQ handling is a follow-up.
640
+ - Rate-limit budget is consumed at ENQUEUE time for queued sends (see
641
+ `RateLimiter` docstring).
642
+
643
+ ## See also
644
+
645
+ - [`define-notification/SKILL.md`](../define-notification/SKILL.md) — `.queue()` on a defined notification.
646
+ - [`configure-notifications/SKILL.md`](../configure-notifications/SKILL.md) — the `queue` config slot.
647
+ - [`@warlock.js/herald/herald-basics/SKILL.md`](../../../herald/skills/herald-basics/SKILL.md) — connecting the broker.
648
+
649
+
650
+ ## send-ad-hoc `@warlock.js/notifications/send-ad-hoc/SKILL.md`
651
+
652
+ ---
653
+ name: send-ad-hoc
654
+ description: 'Ad-hoc per-channel send via the `notify.<channel>(to, payload, options?)` Proxy facade. Works for any channel registered in `NotificationChannels` (built-in or custom). `to` accepts a `Notifiable` model OR a raw route string (`"x@y.com"`); `payload` is typed per channel via the registry; `options` is the standard `SendOptions`. `notify.channel(name).send(...)` is the runtime escape when the channel name is not a compile-time literal. Type-based preference gating applies when a type is known — explicit via `options.type` OR auto-detected from a database payload''s `type` field. For multi-channel sends use `defineNotification` instead — there is no inline `notify(to, { via, ... })` form on purpose. Triggers: `notify.<channel>`, `notify.channel(name)`, `notify.mail`, `notify.database`, "send a one-off notification", "ad-hoc notification", "send an email without defining a notification", "raw email target", "dynamic channel name"; typical import `import { notify } from "@warlock.js/notifications"`. Skip: reusable multi-channel notifications — `@warlock.js/notifications/define-notification/SKILL.md`; configuring channels — `@warlock.js/notifications/configure-notifications/SKILL.md`.'
655
+ ---
656
+
657
+ # `notify.<channel>` — ad-hoc, per-channel sends
658
+
659
+ When you don't need a reusable definition — fire one channel, one recipient.
660
+
661
+ ```ts
662
+ import { notify } from "@warlock.js/notifications";
663
+
664
+ await notify.mail(user, { subject: "Welcome", html: "<p>Hi!</p>" });
665
+ await notify.database(user, { type: "welcome", title: "Welcome!" });
666
+ ```
667
+
668
+ For **multi-channel** sends, use [`defineNotification`](../define-notification/SKILL.md) — that's the reusable pattern and the only mental model for "send through several channels at once" (no inline multi-channel overload).
669
+
670
+ ## Shape
671
+
672
+ ```ts
673
+ notify.<channel>(
674
+ to: Notifiable | string, // model OR raw route
675
+ payload: NotificationChannels[channel], // typed per channel
676
+ options?: SendOptions,
677
+ ): Promise<void>
678
+ ```
679
+
680
+ ## Raw target — no model
681
+
682
+ Pass a string instead of a model to use the string as the route directly:
683
+
684
+ ```ts
685
+ await notify.mail("guest@example.com", { subject: "Receipt", html: "<p>…</p>" });
686
+ await notify.whatsapp("+201234567890", { body: "Promo: 20% off!" }); // Phase 2
687
+ ```
688
+
689
+ When the recipient isn't a model, `PreferenceProvider` and `RateLimiter` are skipped — there's no `Notifiable` to consult.
690
+
691
+ ## Runtime-dynamic channel name
692
+
693
+ When the channel isn't a literal, use `notify.channel(name).send(...)`:
694
+
695
+ ```ts
696
+ const channelName = await chooseChannelForUser(user);
697
+ await notify.channel(channelName).send(user, payload);
698
+ ```
699
+
700
+ This is the only path with `unknown`-typed payloads — prefer the literal `notify.<channel>` when you can.
701
+
702
+ ## Opt into preference/rate-limit gating
703
+
704
+ Ad-hoc sends bypass the preference gate unless a notification `type` is known. Two ways to provide it:
705
+
706
+ ```ts
707
+ // 1. Explicit — wins regardless of payload.
708
+ await notify.mail(user, payload, { type: "marketing.weekly" });
709
+
710
+ // 2. Auto-detected — database payloads carry their own `type` field.
711
+ await notify.database(user, { type: "welcome", title: "Welcome!" });
712
+ // ^^^^^^^^^^^^^^^ used for gating
713
+ ```
714
+
715
+ `SendOptions.force === true` bypasses preferences. `RateLimiter` is consulted whenever a type is known (regardless of `force`).
716
+
717
+ ## Custom channels
718
+
719
+ After registering a custom channel (see [`define-channel`](../define-channel/SKILL.md)), it's first-class:
720
+
721
+ ```ts
722
+ await notify.discord(user, { content: "Build finished 🎉" });
723
+ await notify.slack(staff, { text: "Deploy starting" });
724
+ ```
725
+
726
+ ## SendOptions (3rd arg)
727
+
728
+ | Field | Effect |
729
+ |---|---|
730
+ | `delay` | Reserved for `.queue` paths; not used by `notify.<channel>` (sync). |
731
+ | `locale` | Forwarded to the channel's `send({ options })`. |
732
+ | `meta` | Forwarded to the channel + included in every observability event. |
733
+ | `idempotencyKey` | Injected into the database payload (dedupe). |
734
+ | `force` | Bypass `PreferenceProvider`. Does NOT bypass `RateLimiter`. |
735
+ | `type` | Notification type for gating (ad-hoc only). |
736
+
737
+ ## Failure surfaces
738
+
739
+ `notify.<channel>` rejects on configuration errors (`ChannelNotFoundError`) — those are loud, immediate, and don't fire a `failed` event. Channel-level send failures rethrow AND fire a `failed` event with the channel + error.
740
+
741
+ ## See also
742
+
743
+ - [`notifications-basics/SKILL.md`](../notifications-basics/SKILL.md) — front door + mental model.
744
+ - [`define-notification/SKILL.md`](../define-notification/SKILL.md) — reusable multi-channel.
745
+ - [`define-channel/SKILL.md`](../define-channel/SKILL.md) — register a custom channel.
746
+ - [`observe-notifications/SKILL.md`](../observe-notifications/SKILL.md) — `sending` / `sent` / `failed` / `skipped` events.
747
+
748
+
749
+ ## use-in-app `@warlock.js/notifications/use-in-app/SKILL.md`
750
+
751
+ ---
752
+ name: use-in-app
753
+ description: 'Use the `inApp` facade for the in-app/database channel''s READ side: `inApp.configure({ model: Notification })` or `{ repository: myRepo }` binds the store AND returns the channel; `inApp.list / listUnread / countUnread / markAsRead / markAsUnread` are RECIPIENT-SCOPED by construction (no IDOR — `markAsRead(user, id)` cannot flip another user''s row even with a foreign id). `countUnread` uses `RepositoryManager.countCached` for the badge fast-path. Triggers: `inApp.configure`, `inApp.list`, `inApp.listUnread`, `inApp.countUnread`, `inApp.markAsRead`, `inApp.markAsUnread`, `BaseNotificationsRepository`, `DatabaseNotification`, `NotificationsFilter`, "in-app notifications", "mark notification as read", "unread count", "notification badge", "IDOR-safe markAsRead"; typical import `import { inApp } from "@warlock.js/notifications"`. Skip: writing notifications (use `defineNotification` or `notify.database`) — `@warlock.js/notifications/define-notification/SKILL.md`; the migration columns — `@warlock.js/notifications/write-notification-migration/SKILL.md`; wiring it into config — `@warlock.js/notifications/configure-notifications/SKILL.md`.'
754
+ ---
755
+
756
+ # `inApp` — in-app notification read API
757
+
758
+ The in-app database channel has two sides:
759
+
760
+ - **Write side** — `notify.database(user, {...})` and the database channel inside `defineNotification` create rows.
761
+ - **Read side** — `inApp.list` / `listUnread` / `countUnread` / `markAsRead` / `markAsUnread` query and mutate.
762
+
763
+ `inApp.configure({ model | repository })` binds the same repository for both sides, so cache invalidation just works.
764
+
765
+ ## Configure (once, in `config/notifications.ts`)
766
+
767
+ ```ts
768
+ // 90% case — pass the model class; default repo built internally.
769
+ database: inApp.configure({ model: Notification }),
770
+
771
+ // 10% case — pass a custom repo.
772
+ database: inApp.configure({ repository: notificationsRepository }),
773
+ ```
774
+
775
+ ## Reads
776
+
777
+ ```ts
778
+ import { inApp } from "@warlock.js/notifications";
779
+
780
+ // all rows for this recipient (paginated via the repo's standard `list`)
781
+ const all = await inApp.list(user);
782
+
783
+ // unread-only — pass `filter` to add type/etc. constraints
784
+ const unread = await inApp.listUnread(user, { type: "order.shipped" });
785
+
786
+ // cached unread count — backs the badge
787
+ const badge = await inApp.countUnread(user);
788
+
789
+ // one notification — for a detail view (recipient-scoped)
790
+ const one = await inApp.find(user, "ntf_123");
791
+ ```
792
+
793
+ All read methods accept a cascade `Notifiable` model OR a raw `id` (string | number) — convenient when you only have an id without fetching the user.
794
+
795
+ ```ts
796
+ await inApp.list("user_42");
797
+ await inApp.countUnread(123);
798
+ ```
799
+
800
+ ## Writes (recipient-scoped → no IDOR)
801
+
802
+ ```ts
803
+ // mark ALL unread rows for this recipient as read
804
+ await inApp.markAsRead(user);
805
+
806
+ // mark ONE specific row — STILL scoped to this recipient
807
+ await inApp.markAsRead(user, "ntf_123");
808
+
809
+ // inverse
810
+ await inApp.markAsUnread(user, "ntf_123");
811
+
812
+ // delete / dismiss — one row, or clear all for this recipient
813
+ await inApp.dismiss(user, "ntf_123");
814
+ await inApp.dismiss(user);
815
+ ```
816
+
817
+ The recipient-id is forced into the `where` clause. A controller that receives an `id` from the request and naively calls `inApp.markAsRead(currentUser, id)` cannot accidentally flip another user's row — even if the request contains a forged id. The mutation will simply update 0 rows.
818
+
819
+ ## Behind the scenes — `columnMap` drives everything
820
+
821
+ The model declares its physical columns ONCE via `static columnMap`. The
822
+ shipped `DatabaseNotification` accessors and `BaseNotificationsRepository`
823
+ (read filter + write mapping) both derive from it, so they can never drift:
824
+
825
+ ```ts
826
+ abstract class DatabaseNotification extends Model implements NotificationContract {
827
+ public static columnMap: NotificationColumnMap = {};
828
+ // recipientId / tenantId / isRead / readAt / markRead all read `columnMap`.
829
+ }
830
+
831
+ class BaseNotificationsRepository extends RepositoryManager {
832
+ // constructor resolves the model's columnMap → builds `filterBy` +
833
+ // createFor / markRead / markUnread / deleteFor from it.
834
+ public createFor(recipientId, input, tenantId?) { /* one insert, starts unread */ }
835
+ }
836
+ ```
837
+
838
+ ### `columnMap` — map logical roles → your columns
839
+
840
+ ```ts
841
+ export type NotificationColumnMap = {
842
+ recipient?: string; // recipient FK. Default "user_id"
843
+ tenant?: string; // multi-tenant scope, written from the recipient. Omit → single-tenant
844
+ readAt?: string; // read-timestamp column
845
+ isRead?: string; // read-flag column (indexed)
846
+ };
847
+ ```
848
+
849
+ **Read-state is chosen by which keys are PRESENT:**
850
+
851
+ - `readAt` only → unread = `read_at IS NULL`; marking read stamps it.
852
+ - `isRead` only → unread = `is_read = false`; no timestamp.
853
+ - both → `is_read` is the indexed filter flag, `read_at` records WHEN.
854
+
855
+ Declare neither and you get the `readAt`-only default — so a model can omit
856
+ `columnMap` entirely. `unread` is the mode-agnostic read filter on `inApp` /
857
+ the repo; there is no `isRead` filter key to remember.
858
+
859
+ ## Your model — declare `table`, `schema`, and `columnMap`
860
+
861
+ ```ts title="src/app/notifications/notification.model.ts"
862
+ import { RegisterModel } from "@warlock.js/cascade";
863
+ import { v } from "@warlock.js/seal";
864
+ import { DatabaseNotification, type NotificationColumnMap } from "@warlock.js/notifications";
865
+
866
+ // Mirrors the migration columns; cascade validates + casts every write.
867
+ const notificationSchema = v.object({
868
+ user_id: v.string(),
869
+ type: v.string(),
870
+ title: v.string(),
871
+ body: v.string().nullish(),
872
+ payload: v.record(v.any()).nullish(),
873
+ read_at: v.date().nullish(),
874
+ idempotency_key: v.string().nullish(),
875
+ });
876
+
877
+ @RegisterModel()
878
+ export class Notification extends DatabaseNotification {
879
+ public static table = "notifications";
880
+ public static schema = notificationSchema;
881
+ // read_at-only, single-tenant. Add `tenant: "organization_id"` for multi-tenant,
882
+ // swap to `isRead: "is_read"` (or add it) to change the read-state representation.
883
+ public static columnMap: NotificationColumnMap = { readAt: "read_at" };
884
+ }
885
+ ```
886
+
887
+ To change columns, edit `columnMap` — the migration (`notificationColumns`), the
888
+ repo filter, and the accessors all follow. For a different driver's naming
889
+ (e.g. MongoDB camelCase), name the columns in `columnMap`
890
+ (`{ recipient: "userId", readAt: "readAt" }`).
891
+
892
+ ## Custom repository (advanced, optional)
893
+
894
+ `columnMap` already covers column naming. Subclass only for EXTRA query methods:
895
+
896
+ ```ts title="src/app/notifications/notifications.repository.ts"
897
+ import { BaseNotificationsRepository } from "@warlock.js/notifications";
898
+ import { Notification } from "./notification.model";
899
+
900
+ export class NotificationsRepository extends BaseNotificationsRepository<Notification> {
901
+ public source = Notification; // its columnMap still drives filter + write mapping
902
+ // …extra methods specific to your app
903
+ }
904
+ export const notificationsRepository = new NotificationsRepository();
905
+ ```
906
+
907
+ Then swap config:
908
+
909
+ ```ts
910
+ database: inApp.configure({ repository: notificationsRepository }),
911
+ ```
912
+
913
+ ## See also
914
+
915
+ - [`notifications-basics/SKILL.md`](../notifications-basics/SKILL.md) — package front door.
916
+ - [`configure-notifications/SKILL.md`](../configure-notifications/SKILL.md) — wire `inApp.configure` into the config.
917
+ - [`write-notification-migration/SKILL.md`](../write-notification-migration/SKILL.md) — `notificationColumns(Notification)`, named from `columnMap`.
918
+ - [`define-notification/SKILL.md`](../define-notification/SKILL.md) — create rows via the database channel.
919
+
920
+
921
+ ## write-notification-migration `@warlock.js/notifications/write-notification-migration/SKILL.md`
922
+
923
+ ---
924
+ name: write-notification-migration
925
+ description: 'Create the notifications table with the `notificationColumns(Notification)` factory + cascade `Migration.create`. Column NAMES come from the model''s `columnMap` (recipient / tenant / readAt / isRead); the fixed columns are `type` / `title` / `body` / `payload` / `idempotency_key`. Read-state follows columnMap presence: `readAt` → nullable timestamp, `isRead` → indexed boolean, both → both. Defaults to `user_id` + `read_at` when no columnMap. Spread + extend for extras (FK references, composite indexes). Triggers: `notificationColumns`, `Migration.create` for notifications, "create the notifications table", "notification migration", "add organization_id to notifications", `is_read` column, `read_at` column, `idempotency_key` column; typical import `import { Migration } from "@warlock.js/cascade"; import { notificationColumns } from "@warlock.js/notifications"`. Skip: generic cascade migration writing — `@warlock.js/cascade/write-migration/SKILL.md`; the model itself — `@warlock.js/notifications/use-in-app/SKILL.md`.'
926
+ ---
927
+
928
+ # Write the notifications migration
929
+
930
+ The package ships no table or migration (thin eject). You own the migration; the package gives you a column factory that names columns from your model's `columnMap`, so it's one line.
931
+
932
+ > `npx warlock add notifications` scaffolds this migration (+ the model) for you. Reach for this skill when you need to customize columns or add extras.
933
+
934
+ ## Common case — one line
935
+
936
+ ```ts title="src/app/notifications/migrations/01-01-2026_00-00-00-notifications.migration.ts"
937
+ import { Migration } from "@warlock.js/cascade";
938
+ import { notificationColumns } from "@warlock.js/notifications";
939
+ import { Notification } from "../notification.model";
940
+
941
+ export default Migration.create(Notification, notificationColumns(Notification));
942
+ ```
943
+
944
+ `notificationColumns(Notification)` reads the model's `columnMap` and returns the
945
+ matching columns:
946
+
947
+ | columnMap | Columns |
948
+ |---|---|
949
+ | _(none / default)_ | `user_id`, `type`, `title`, `body`, `payload`, `read_at`, `idempotency_key` |
950
+ | `{ tenant: "organization_id", readAt: "read_at" }` | adds `organization_id`; read_at-only |
951
+ | `{ isRead: "is_read" }` | swaps `read_at` for `is_read` (indexed boolean) |
952
+ | `{ isRead: "is_read", readAt: "read_at" }` | both read-state columns |
953
+
954
+ The recipient / tenant / read-state column NAMES come from `columnMap`; `type` /
955
+ `title` / `body` / `payload` / `idempotency_key` are fixed. `id` / `createdAt` /
956
+ `updatedAt` are added automatically by cascade.
957
+
958
+ ## With extras — spread + extend
959
+
960
+ Add your own columns — a category, a source channel, a tenant id, anything:
961
+
962
+ ```ts
963
+ import { Migration, string } from "@warlock.js/cascade";
964
+ import { notificationColumns } from "@warlock.js/notifications";
965
+ import { Notification } from "../notification.model";
966
+
967
+ export default Migration.create(Notification, {
968
+ ...notificationColumns(Notification),
969
+ category: string().index().nullable(),
970
+ });
971
+ ```
972
+
973
+ Mirror any extra column in the model `schema`. To make it filterable, add a method to a custom repository (see `use-in-app/SKILL.md`).
974
+
975
+ ## Column naming follows `columnMap`
976
+
977
+ The factory does NOT guess names from the driver — it reads the model's `columnMap`. To match a different convention (e.g. MongoDB camelCase), name the columns there and the migration follows:
978
+
979
+ ```ts
980
+ class Notification extends DatabaseNotification {
981
+ public static columnMap = { recipient: "userId", readAt: "readAt" };
982
+ }
983
+ // → notificationColumns(Notification) emits `userId` + `readAt`
984
+ ```
985
+
986
+ Without a model passed, defaults to `user_id` + `read_at` (read_at-only). See [`use-in-app/SKILL.md`](../use-in-app/SKILL.md) for the full `columnMap` shape.
987
+
988
+ ## See also
989
+
990
+ - [`use-in-app/SKILL.md`](../use-in-app/SKILL.md) — the model + repository the migration backs.
991
+ - [`@warlock.js/cascade/write-migration/SKILL.md`](../../../cascade/skills/write-migration/SKILL.md) — generic Cascade migration form, `Migration.alter`, etc.
992
+ - [`@warlock.js/cascade/manage-data-sources/SKILL.md`](../../../cascade/skills/manage-data-sources/SKILL.md) — multi-data-source setup.
993
+
994
+