@oblax/notifications 0.0.0-stage → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,278 @@
1
- # Temporary Holding Version
1
+ # @oblax/notifications
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The user's notification inbox for Oblax apps: the bell with its unread count, the list, "mark all
4
+ as read", the settings screen where users pick which kinds they get and how, and, for app admins,
5
+ categories and sends.
6
+
7
+ ```bash
8
+ pnpm add @oblax/core @oblax/platform-browser @oblax/auth @oblax/realtime @oblax/notifications
9
+ ```
10
+
11
+ `@oblax/realtime` is a peer dependency: the bell (`onChange`) listens on its stream.
12
+
13
+ ```typescript
14
+ import { Oblax } from '@oblax/core'
15
+ import { PlatformBrowser } from '@oblax/platform-browser'
16
+ import { Auth } from '@oblax/auth'
17
+ import { Notifications } from '@oblax/notifications'
18
+
19
+ const oblax = new Oblax({
20
+ endpoint: 'https://api.my-app.oblax.io',
21
+ clientId: 'my-web-app',
22
+ modules: [PlatformBrowser(), Auth({ realm: 'webapp' }), Notifications()],
23
+ })
24
+ ```
25
+
26
+ Oblax never notifies anyone on its own: your flux scripts (or your backend, as an app admin) send
27
+ notifications, and every user route acts on the signed-in user. Someone else's notification
28
+ answers 404, as one that doesn't exist.
29
+
30
+ Methods take named parameters, like every module (`read({ id })`, `onChange({ handler })`).
31
+ Records come back as the API sends them, in snake_case (`read_at`, `actor_id`); params are
32
+ camelCase and mapped (`organizationId` → `organization_id`). A send's `data` is passed through
33
+ untouched, both ways.
34
+
35
+ > **`Notification` is also a DOM global** (the browser's Notifications API). In a browser app,
36
+ > `import type { Notification } from '@oblax/notifications'` shadows it in that file; to use both,
37
+ > rename on import: `import type { Notification as InboxItem } from '@oblax/notifications'`.
38
+
39
+ ## The inbox
40
+
41
+ ```typescript
42
+ // a page, newest first. `after` left out (or '') is the first page; pass `next` as `after`
43
+ // for the next one. `next` is '' on the last page: don't ask for more then
44
+ const { data, next } = await oblax.notifications.list({ limit: 20 })
45
+ if (next) {
46
+ const more = await oblax.notifications.list({ after: next, limit: 20 })
47
+ }
48
+
49
+ // filters: each narrows the others
50
+ await oblax.notifications.list({ unread: true }) // filter:eq=unread:true
51
+ await oblax.notifications.list({ critical: true }) // filter:eq=critical:true
52
+ await oblax.notifications.list({ category: 'assignments', organizationId: 'org-id' })
53
+ await oblax.notifications.list({ subjectType: 'workflows.item', subjectId: '981' })
54
+ await oblax.notifications.list({ archived: true }) // the archived ones instead
55
+
56
+ const { count } = await oblax.notifications.count() // { count }, for the badge
57
+ await oblax.notifications.count({ category: 'assignments' })
58
+
59
+ await oblax.notifications.read({ id }) // 204s: also when there was nothing to change
60
+ await oblax.notifications.unread({ id })
61
+ await oblax.notifications.archive({ id }) // hidden from the default list and the count
62
+ await oblax.notifications.delete({ id }) // gone from every list; again is 404
63
+
64
+ // mark all read: every one, a category's, a subject's, or a subject's in a category
65
+ const { changed } = await oblax.notifications.readAll()
66
+ await oblax.notifications.readAll({ subject: { type: 'workflows.item', id: '981' } }) // when the user opens item 981
67
+ ```
68
+
69
+ Each `Notification` has `id` (its own, not the send's), `category`, `title`, `body`, `link`
70
+ (empty, a `/path` or an `https://` URL: safe as an `href`), `data`, `actor_id`, `organization_id`,
71
+ `subject` (`{ type, id }` or `null`), `critical`, `expires_at`, `read_at`, `archived_at` (`null`
72
+ until read or archived) and `_created`. The list and the count read a replica.
73
+
74
+ ## The bell
75
+
76
+ `onChange({ handler })` calls `handler` whenever the user's inbox may have changed, so the app can
77
+ refetch the count:
78
+
79
+ - when the stream opens, the first time and after every reconnect (a ring may have been missed);
80
+ - on every `oblax.notifications.changed` (a send reached the user, or they read something in
81
+ another tab: your own tab rings too);
82
+ - once more `recheckDelay` (1.5 s) after the last ring, because the count is read from a replica
83
+ that can lag the write behind the ring.
84
+
85
+ The handler gets `{ reason, seq }`. `reason` is `'connected'`, `'reconnected'`, `'changed'` or
86
+ `'recheck'`. `seq` is 1 for the first call and one more for each call after it. Refetches can
87
+ answer out of order (a slow first one after a fast second one), so **keep the answer of the
88
+ latest `seq`** and drop one older than what's shown:
89
+
90
+ ```typescript
91
+ let shown = 0 // the seq of the count on screen
92
+ const bell = oblax.notifications.onChange({
93
+ handler: async ({ seq }) => {
94
+ const { count } = await oblax.notifications.count()
95
+ if (seq < shown) return // a later refetch answered first: this one is stale
96
+ shown = seq
97
+ setBadge(count)
98
+ },
99
+ })
100
+
101
+ // no live updates any more (not signed in, replaced, …): poll instead
102
+ let poll: ReturnType<typeof setInterval> | undefined
103
+ bell.stream.onClose(({ reason }) => {
104
+ if (reason !== 'closed') poll = setInterval(async () => setBadge((await oblax.notifications.count()).count), 60_000)
105
+ })
106
+
107
+ // on sign-out
108
+ bell.close()
109
+ clearInterval(poll)
110
+ ```
111
+
112
+ It opens its own stream with `@oblax/realtime`'s `connect()`, which gets the ticket and reconnects
113
+ on its own. Tune that stream module-wide in `Notifications(config)`, with realtime's options and
114
+ defaults, or per call; a bad value throws at once:
115
+
116
+ ```typescript
117
+ Notifications({ recheckDelay: 1500, reconnectDelay: 1000, maxReconnectDelay: 30000, idleTimeout: 60000 })
118
+ oblax.notifications.onChange({ handler: refreshBadge, maxReconnectDelay: 10000 }) // overrides the module's
119
+ ```
120
+
121
+ The realtime module's own `Realtime(config)` doesn't tune the bell's stream: the bell opens it
122
+ through its own config. If the app already has a stream, share it: one stream per tab serves the
123
+ bell and the app's own events, and a user has at most 10.
124
+
125
+ ```typescript
126
+ import { Realtime } from '@oblax/realtime'
127
+ // modules: [PlatformBrowser(), Auth({ realm: 'webapp' }), Realtime(), Notifications()]
128
+
129
+ const stream = oblax.realtime.connect()
130
+ stream.on('invoice.ready', (e) => reloadInvoice(e.data.invoice_id))
131
+ const bell = oblax.notifications.onChange({ handler: refreshBadge, stream })
132
+ bell.close() // removes the bell's handlers; a shared stream stays open
133
+ stream.close()
134
+ ```
135
+
136
+ A shared stream keeps its own tuning: `reconnectDelay`, `maxReconnectDelay` or `idleTimeout`
137
+ given with `stream` throws. A shared stream that's open already gets `connected` at once; one that
138
+ is reconnecting gets `reconnected` when it opens; one closed already ends the watch at once
139
+ (`bell.closed` is `true`, the handler never runs).
140
+
141
+ Params:
142
+
143
+ | Param | Does |
144
+ |---|---|
145
+ | `handler` | Required. Called with `{ reason, seq }` |
146
+ | `stream` | A `RealtimeStream` to share instead of opening one. `close()` leaves it open |
147
+ | `recheckDelay` | Milliseconds between a ring and the second call; `0` turns it off. Default 1500, or `Notifications({ recheckDelay })` |
148
+ | `signal` | Aborting it ends the watch, as `close()` does |
149
+ | `onError` | Gets what the handler throws or rejects with; without it those are ignored, and the bell carries on |
150
+ | `reconnectDelay`, `maxReconnectDelay`, `idleTimeout` | For the bell's own stream: override `Notifications(config)`'s. Not with `stream` |
151
+
152
+ `bell.closed` is `true` once the watch ended: `close()`, the signal, or its stream closed for good.
153
+ Load the list when the bell's menu opens, not on every ring.
154
+
155
+ ## Preferences
156
+
157
+ The settings screen is every category, `general` first, with the user's effective value for each
158
+ channel:
159
+
160
+ ```typescript
161
+ const { data } = await oblax.notifications.preferences.get()
162
+ // [{ category: 'assignments', name: 'Assignments', description: '…', locked: false,
163
+ // channels: { email: true, inbox: true, push: true } }, …]
164
+ ```
165
+
166
+ Show a locked category's switches disabled. `set({ changes })` takes a list of up to 500 (one is
167
+ `changes: [change]`) and answers the screen as saved; only switches that differ are written, so a
168
+ screen can send all of them:
169
+
170
+ ```typescript
171
+ const saved = await oblax.notifications.preferences.set({
172
+ changes: [
173
+ { category: 'assignments', channel: 'email', enabled: true },
174
+ { category: 'assignments', channel: 'push', enabled: false },
175
+ ],
176
+ })
177
+ ```
178
+
179
+ A refused request writes nothing.
180
+
181
+ ## Categories
182
+
183
+ Any signed-in user lists them; app admins write them. The built-in `general` is always first, has
184
+ no row (its `id` is `''` and it has no `_created`/`_modified`), and can't be written (400
185
+ `key: reserved`).
186
+
187
+ ```typescript
188
+ const { data } = await oblax.notifications.categories.list()
189
+
190
+ await oblax.notifications.categories.create({
191
+ key: 'assignments', // ^[a-z][a-z0-9_.-]{0,63}$, can't change
192
+ name: 'Assignments',
193
+ description: 'When someone assigns you an item.',
194
+ channels: { inbox: true, email: false, push: true }, // must hold inbox; each value is the default
195
+ locked: false, // true: users can't change their choices
196
+ })
197
+
198
+ // fields left out keep their stored values; channels, when given, replaces them whole
199
+ await oblax.notifications.categories.update({ key: 'assignments', locked: true })
200
+ // a category read back can be changed and passed whole (its id and times aren't sent)
201
+ const c = data.find((c) => c.key === 'assignments')!
202
+ await oblax.notifications.categories.update({ ...c, name: 'My assignments' })
203
+
204
+ await oblax.notifications.categories.delete({ key: 'assignments' })
205
+ ```
206
+
207
+ ## Sending (app admins)
208
+
209
+ Scripts usually send (`oblax.notifications.send` in flux); a backend signed in as an app admin can
210
+ too:
211
+
212
+ ```typescript
213
+ const { id, recipients, skipped } = await oblax.notifications.send({
214
+ to: { users: ['person-id'], roles: ['editor'], organizations: ['org-id'] }, // OR'd, at most 5,000 people
215
+ category: 'assignments',
216
+ title: 'You were assigned “Fix the login page”',
217
+ body: 'Bojan assigned you an item on the Website board.',
218
+ link: '/boards/42/items/981',
219
+ data: { icon: 'assign', item_id: '981' }, // any JSON, up to 4 KB, sent as-is
220
+ actorId: 'person-id-of-bojan',
221
+ subject: { type: 'workflows.item', id: '981' },
222
+ dedupKey: 'assigned:981:ana:7', // users who already have it are skipped
223
+ critical: false,
224
+ expiresAt: '2026-12-24T09:00:00Z',
225
+ })
226
+ ```
227
+
228
+ Only `to`, `category` and `title` are required. `recipients` counts the notifications written
229
+ (users with the inbox off included), `skipped` the users the dedup key skipped. A send is never
230
+ retried by the SDK; after a 503 it may still have been written, which a `dedupKey` makes harmless
231
+ to send again.
232
+
233
+ Read a send back (its content and counts, never its `to`; right after the send it can be 404 for a
234
+ moment, as it's read from a replica), and page through who has a channel on, to deliver email,
235
+ push or SMS from your backend:
236
+
237
+ ```typescript
238
+ const send = await oblax.notifications.sends.get({ id }) // … recipient_count, skipped_count
239
+
240
+ let after = ''
241
+ do {
242
+ const page = await oblax.notifications.sends.recipients({ id, channel: 'email', after, limit: 500 })
243
+ await mailEach(page.users) // a page can hold fewer users than limit, even none, while next is set
244
+ after = page.next
245
+ } while (after !== '')
246
+ ```
247
+
248
+ ## Errors
249
+
250
+ Failed calls throw core's `OblaxHttpError`, with the API's error body in `err.body`
251
+ (`NotificationsErrorBody`): `status`, `type`, `message` and, on most 400s, `validation_errors`,
252
+ every rule the request broke at once:
253
+
254
+ ```typescript
255
+ import { OblaxHttpError } from '@oblax/core'
256
+ import type { NotificationsErrorBody } from '@oblax/notifications'
257
+
258
+ try {
259
+ await oblax.notifications.send({ to: { users: ['u1'] }, category: 'nope', title: 'Hi' })
260
+ } catch (err) {
261
+ if (err instanceof OblaxHttpError && err.status === 400) {
262
+ for (const e of (err.body as NotificationsErrorBody).validation_errors ?? []) {
263
+ console.log(e.field, e.validation_check, e.value) // category unknown nope
264
+ }
265
+ }
266
+ }
267
+ ```
268
+
269
+ | Status | `type` | When |
270
+ |---|---|---|
271
+ | 400 | `VALIDATION_FAILED` | A rule broken, named in `validation_errors` (`title: max`, `category: unknown`, `1.channel: locked`, `key: reserved`, …) |
272
+ | 400 | `UNABLE_TO_PARSE_PAYLOAD` | A value of the wrong type |
273
+ | 403 | `AUTH_ACL_VALIDATION_FAILED` | Not signed in, a visitor; a user on an admin route (send, sends, category writes) |
274
+ | 404 | `NOT_FOUND` | A notification that isn't the user's, was deleted or expired; an unknown category key or send |
275
+ | 409 | `NOTIFICATIONS_ALREADY_EXISTS` | A category key that's taken |
276
+ | 503 | `NOTIFICATIONS_UNAVAILABLE` | The service, or identity behind it, can't be reached: retry with backoff |
277
+
278
+ Reads that fail with a 5xx are retried as the SDK's `retries` says; writes never are.
@@ -0,0 +1,40 @@
1
+ import type { OblaxContext } from '@oblax/core';
2
+ import type { Category, CreateCategoryParams, KeyParams, NotificationsList, UpdateCategoryParams } from './types.js';
3
+ /**
4
+ * The project's notification categories. Any signed-in user lists them;
5
+ * app admins create, change and delete them. The built-in `general` is
6
+ * listed first and can't be written (400 `key: reserved`).
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * await oblax.notifications.categories.create({
11
+ * key: 'assignments',
12
+ * name: 'Assignments',
13
+ * channels: { inbox: true, email: false, push: true },
14
+ * })
15
+ *
16
+ * const { data } = await oblax.notifications.categories.list()
17
+ * const c = data.find((c) => c.key === 'assignments')!
18
+ * await oblax.notifications.categories.update({ ...c, locked: true })
19
+ * ```
20
+ */
21
+ export declare class CategoriesSubmodule {
22
+ private readonly ctx;
23
+ constructor(ctx: OblaxContext);
24
+ /** Every category: `general` first, then the project's own by key. */
25
+ list(): Promise<NotificationsList<Category>>;
26
+ /** Creates a category. App admins only. A taken key is 409 `NOTIFICATIONS_ALREADY_EXISTS`. */
27
+ create(params: CreateCategoryParams): Promise<Category>;
28
+ /**
29
+ * Changes a category; answers it as saved. App admins only. Fields left
30
+ * out keep their stored values; `channels`, when given, replaces them
31
+ * whole (and must hold `inbox`). The key can't change; an unknown one is 404.
32
+ */
33
+ update(params: UpdateCategoryParams): Promise<Category>;
34
+ /**
35
+ * Deletes a category. App admins only. Its notifications stay in users'
36
+ * lists; new sends naming it are refused.
37
+ */
38
+ delete(params: KeyParams): Promise<void>;
39
+ }
40
+ //# sourceMappingURL=categories.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"categories.d.ts","sourceRoot":"","sources":["../src/categories.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAE/C,OAAO,KAAK,EACV,QAAQ,EAER,oBAAoB,EACpB,SAAS,EACT,iBAAiB,EACjB,oBAAoB,EACrB,MAAM,YAAY,CAAA;AAWnB;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,mBAAmB;IAClB,OAAO,CAAC,QAAQ,CAAC,GAAG;gBAAH,GAAG,EAAE,YAAY;IAE9C,sEAAsE;IAChE,IAAI,IAAI,OAAO,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CAAC;IAIlD,8FAA8F;IACxF,MAAM,CAAC,MAAM,EAAE,oBAAoB,GAAG,OAAO,CAAC,QAAQ,CAAC;IAO7D;;;;OAIG;IACG,MAAM,CAAC,MAAM,EAAE,oBAAoB,GAAG,OAAO,CAAC,QAAQ,CAAC;IAO7D;;;OAGG;IACG,MAAM,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC;CAG/C"}
@@ -0,0 +1,59 @@
1
+ import { pathSegment as seg } from '@oblax/core';
2
+ function fieldsToApi(p) {
3
+ return {
4
+ name: p.name,
5
+ description: p.description,
6
+ channels: p.channels,
7
+ locked: p.locked,
8
+ };
9
+ }
10
+ /**
11
+ * The project's notification categories. Any signed-in user lists them;
12
+ * app admins create, change and delete them. The built-in `general` is
13
+ * listed first and can't be written (400 `key: reserved`).
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * await oblax.notifications.categories.create({
18
+ * key: 'assignments',
19
+ * name: 'Assignments',
20
+ * channels: { inbox: true, email: false, push: true },
21
+ * })
22
+ *
23
+ * const { data } = await oblax.notifications.categories.list()
24
+ * const c = data.find((c) => c.key === 'assignments')!
25
+ * await oblax.notifications.categories.update({ ...c, locked: true })
26
+ * ```
27
+ */
28
+ export class CategoriesSubmodule {
29
+ constructor(ctx) {
30
+ this.ctx = ctx;
31
+ }
32
+ /** Every category: `general` first, then the project's own by key. */
33
+ async list() {
34
+ return this.ctx.http.get('/notifications/categories');
35
+ }
36
+ /** Creates a category. App admins only. A taken key is 409 `NOTIFICATIONS_ALREADY_EXISTS`. */
37
+ async create(params) {
38
+ return this.ctx.http.post('/notifications/categories', {
39
+ key: params.key,
40
+ ...fieldsToApi(params),
41
+ });
42
+ }
43
+ /**
44
+ * Changes a category; answers it as saved. App admins only. Fields left
45
+ * out keep their stored values; `channels`, when given, replaces them
46
+ * whole (and must hold `inbox`). The key can't change; an unknown one is 404.
47
+ */
48
+ async update(params) {
49
+ return this.ctx.http.put(`/notifications/categories/${seg(params.key)}`, fieldsToApi(params));
50
+ }
51
+ /**
52
+ * Deletes a category. App admins only. Its notifications stay in users'
53
+ * lists; new sends naming it are refused.
54
+ */
55
+ async delete(params) {
56
+ return this.ctx.http.delete(`/notifications/categories/${seg(params.key)}`);
57
+ }
58
+ }
59
+ //# sourceMappingURL=categories.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"categories.js","sourceRoot":"","sources":["../src/categories.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,IAAI,GAAG,EAAE,MAAM,aAAa,CAAA;AAUhD,SAAS,WAAW,CAAC,CAAiB;IACpC,OAAO;QACL,IAAI,EAAS,CAAC,CAAC,IAAI;QACnB,WAAW,EAAE,CAAC,CAAC,WAAW;QAC1B,QAAQ,EAAK,CAAC,CAAC,QAAQ;QACvB,MAAM,EAAO,CAAC,CAAC,MAAM;KACtB,CAAA;AACH,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,OAAO,mBAAmB;IAC9B,YAA6B,GAAiB;QAAjB,QAAG,GAAH,GAAG,CAAc;IAAG,CAAC;IAElD,sEAAsE;IACtE,KAAK,CAAC,IAAI;QACR,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAA8B,2BAA2B,CAAC,CAAA;IACpF,CAAC;IAED,8FAA8F;IAC9F,KAAK,CAAC,MAAM,CAAC,MAA4B;QACvC,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAW,2BAA2B,EAAE;YAC/D,GAAG,EAAE,MAAM,CAAC,GAAG;YACf,GAAG,WAAW,CAAC,MAAM,CAAC;SACvB,CAAC,CAAA;IACJ,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,MAAM,CAAC,MAA4B;QACvC,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CACtB,6BAA6B,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,EAC9C,WAAW,CAAC,MAAM,CAAC,CACpB,CAAA;IACH,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,MAAM,CAAC,MAAiB;QAC5B,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAO,6BAA6B,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;IACnF,CAAC;CACF"}
@@ -0,0 +1,40 @@
1
+ import type { OblaxModulePlugin } from '@oblax/core';
2
+ import { NotificationsModule } from './notifications-module.js';
3
+ import type { NotificationsConfig } from './types.js';
4
+ export { NotificationsModule } from './notifications-module.js';
5
+ export { PreferencesSubmodule } from './preferences.js';
6
+ export { CategoriesSubmodule } from './categories.js';
7
+ export { SendsSubmodule } from './sends.js';
8
+ export { NotificationsWatch, CHANGED_EVENT } from './watch.js';
9
+ export type { NotificationsConfig, NotificationsList, IdParams, KeyParams, NotificationSubject, ValidationError, NotificationsErrorBody, Notification, NotificationPage, ListNotificationsParams, CountParams, CountResult, ReadAllParams, ReadAllResult, PreferenceCategory, PreferenceChange, SetPreferencesParams, Category, CategoryFields, CreateCategoryParams, UpdateCategoryParams, NotificationTarget, SendParams, SendResult, Send, RecipientsParams, RecipientsPage, ChangeReason, ChangeInfo, OnChangeParams, } from './types.js';
10
+ /**
11
+ * Notifications module factory.
12
+ *
13
+ * Registers the notifications module with the Oblax SDK; it's available on
14
+ * `oblax.notifications`. `onChange()` (the bell) uses `@oblax/realtime`'s
15
+ * stream, so install it alongside. `config` sets the bell's `recheckDelay`
16
+ * and the realtime tuning (`reconnectDelay`, `maxReconnectDelay`,
17
+ * `idleTimeout`) of the streams `onChange()` opens itself; `onChange()` can
18
+ * override them. A bad value throws here.
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * import { Oblax } from '@oblax/core'
23
+ * import { PlatformBrowser } from '@oblax/platform-browser'
24
+ * import { Auth } from '@oblax/auth'
25
+ * import { Notifications } from '@oblax/notifications'
26
+ *
27
+ * const oblax = new Oblax({
28
+ * endpoint: 'https://api.my-app.oblax.io',
29
+ * clientId: 'my-web-app',
30
+ * modules: [PlatformBrowser(), Auth({ realm: 'webapp' }), Notifications()],
31
+ * })
32
+ *
33
+ * const bell = oblax.notifications.onChange({
34
+ * handler: async () => setBadge((await oblax.notifications.count()).count),
35
+ * })
36
+ * const { data } = await oblax.notifications.list({ unread: true })
37
+ * ```
38
+ */
39
+ export declare function Notifications(config?: NotificationsConfig): OblaxModulePlugin<'notifications', NotificationsModule>;
40
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgB,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAA;AAC/D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAErD,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAA;AAC/D,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAA;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAA;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAC3C,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAE9D,YAAY,EACV,mBAAmB,EACnB,iBAAiB,EACjB,QAAQ,EACR,SAAS,EACT,mBAAmB,EACnB,eAAe,EACf,sBAAsB,EACtB,YAAY,EACZ,gBAAgB,EAChB,uBAAuB,EACvB,WAAW,EACX,WAAW,EACX,aAAa,EACb,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,oBAAoB,EACpB,QAAQ,EACR,cAAc,EACd,oBAAoB,EACpB,oBAAoB,EACpB,kBAAkB,EAClB,UAAU,EACV,UAAU,EACV,IAAI,EACJ,gBAAgB,EAChB,cAAc,EACd,YAAY,EACZ,UAAU,EACV,cAAc,GACf,MAAM,YAAY,CAAA;AAEnB;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,aAAa,CAC3B,MAAM,GAAE,mBAAwB,GAC/B,iBAAiB,CAAC,eAAe,EAAE,mBAAmB,CAAC,CAOzD"}
package/dist/index.js ADDED
@@ -0,0 +1,44 @@
1
+ import { NotificationsModule } from './notifications-module.js';
2
+ export { NotificationsModule } from './notifications-module.js';
3
+ export { PreferencesSubmodule } from './preferences.js';
4
+ export { CategoriesSubmodule } from './categories.js';
5
+ export { SendsSubmodule } from './sends.js';
6
+ export { NotificationsWatch, CHANGED_EVENT } from './watch.js';
7
+ /**
8
+ * Notifications module factory.
9
+ *
10
+ * Registers the notifications module with the Oblax SDK; it's available on
11
+ * `oblax.notifications`. `onChange()` (the bell) uses `@oblax/realtime`'s
12
+ * stream, so install it alongside. `config` sets the bell's `recheckDelay`
13
+ * and the realtime tuning (`reconnectDelay`, `maxReconnectDelay`,
14
+ * `idleTimeout`) of the streams `onChange()` opens itself; `onChange()` can
15
+ * override them. A bad value throws here.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * import { Oblax } from '@oblax/core'
20
+ * import { PlatformBrowser } from '@oblax/platform-browser'
21
+ * import { Auth } from '@oblax/auth'
22
+ * import { Notifications } from '@oblax/notifications'
23
+ *
24
+ * const oblax = new Oblax({
25
+ * endpoint: 'https://api.my-app.oblax.io',
26
+ * clientId: 'my-web-app',
27
+ * modules: [PlatformBrowser(), Auth({ realm: 'webapp' }), Notifications()],
28
+ * })
29
+ *
30
+ * const bell = oblax.notifications.onChange({
31
+ * handler: async () => setBadge((await oblax.notifications.count()).count),
32
+ * })
33
+ * const { data } = await oblax.notifications.list({ unread: true })
34
+ * ```
35
+ */
36
+ export function Notifications(config = {}) {
37
+ return {
38
+ name: 'notifications',
39
+ create(ctx) {
40
+ return new NotificationsModule(ctx, config);
41
+ },
42
+ };
43
+ }
44
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAA;AAG/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAA;AAC/D,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAA;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAA;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAC3C,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAmC9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,UAAU,aAAa,CAC3B,SAA8B,EAAE;IAEhC,OAAO;QACL,IAAI,EAAE,eAAe;QACrB,MAAM,CAAC,GAAiB;YACtB,OAAO,IAAI,mBAAmB,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;QAC7C,CAAC;KACF,CAAA;AACH,CAAC"}
@@ -0,0 +1,92 @@
1
+ import type { OblaxContext } from '@oblax/core';
2
+ import { CategoriesSubmodule } from './categories.js';
3
+ import { PreferencesSubmodule } from './preferences.js';
4
+ import { SendsSubmodule } from './sends.js';
5
+ import { NotificationsWatch } from './watch.js';
6
+ import type { CountParams, CountResult, IdParams, ListNotificationsParams, NotificationPage, NotificationsConfig, OnChangeParams, ReadAllParams, ReadAllResult, SendParams, SendResult } from './types.js';
7
+ /**
8
+ * The Notifications module: the signed-in user's inbox, the bell, and sends.
9
+ *
10
+ * The inbox is on the module itself (`list`, `count`, `read`, `unread`,
11
+ * `archive`, `delete`, `readAll`), and so are `send()` (app admins) and
12
+ * `onChange()` (the bell); the rest is in sub-modules:
13
+ *
14
+ * - `preferences` — the user's settings screen: which categories they get, and how.
15
+ * - `categories` — the project's kinds of notification (writes: app admins).
16
+ * - `sends` — a send read back, and its recipients per channel (app admins).
17
+ *
18
+ * Every inbox route acts on the signed-in user: someone else's notification
19
+ * answers 404, as one that doesn't exist.
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * const bell = oblax.notifications.onChange({
24
+ * handler: async () => setBadge((await oblax.notifications.count()).count),
25
+ * })
26
+ *
27
+ * const { data, next } = await oblax.notifications.list({ limit: 20 })
28
+ * await oblax.notifications.read({ id: data[0].id })
29
+ * await oblax.notifications.readAll({ subject: { type: 'workflows.item', id: '981' } })
30
+ * ```
31
+ */
32
+ export declare class NotificationsModule {
33
+ readonly preferences: PreferencesSubmodule;
34
+ readonly categories: CategoriesSubmodule;
35
+ readonly sends: SendsSubmodule;
36
+ private readonly ctx;
37
+ private readonly recheckDelay;
38
+ /** Opens the bell's own streams, with the module's realtime tuning as their defaults. */
39
+ private readonly realtime;
40
+ constructor(ctx: OblaxContext, config: NotificationsConfig);
41
+ /**
42
+ * A page of the user's notifications, newest first. Expired ones are never
43
+ * listed; archived ones only with `archived: true`. Read from a replica.
44
+ */
45
+ list(params?: ListNotificationsParams): Promise<NotificationPage>;
46
+ /**
47
+ * The user's unread count for the badge: not archived, not expired; of one
48
+ * category with `category`. A small query: call it whenever the bell rings.
49
+ */
50
+ count(params?: CountParams): Promise<CountResult>;
51
+ /** Marks one notification read (also when it already was). Acknowledges a critical one. */
52
+ read(params: IdParams): Promise<void>;
53
+ /** Marks one notification unread. A critical one stays acknowledged. */
54
+ unread(params: IdParams): Promise<void>;
55
+ /** Hides one notification from the default list and the count. There's no un-archive. */
56
+ archive(params: IdParams): Promise<void>;
57
+ /** Deletes one notification from the user's lists; deleting it again is 404. */
58
+ delete(params: IdParams): Promise<void>;
59
+ /**
60
+ * Marks the user's unread notifications read: every one, a category's, a
61
+ * subject's, or a subject's in a category. Mark by subject when the user
62
+ * opens the thing. Answers how many it marked.
63
+ */
64
+ readAll(params?: ReadAllParams): Promise<ReadAllResult>;
65
+ /**
66
+ * Sends a notification: one per person in `to`, written before the call
67
+ * returns, and a ring on their open streams. App admins only (403
68
+ * otherwise). `data` is sent as-is. Like every POST, a send is resent only
69
+ * once, after a 401 and a successful token refresh; a 503 may still have
70
+ * written it, which a `dedupKey` makes harmless to send again.
71
+ */
72
+ send(params: SendParams): Promise<SendResult>;
73
+ /**
74
+ * Calls `handler` whenever the user's inbox may have changed, so the app
75
+ * can refetch the count: when the stream opens (the first time and every
76
+ * reconnect, as a ring may have been missed), on every
77
+ * `oblax.notifications.changed`, and once more `recheckDelay` after the
78
+ * last ring (the count is read from a replica that can lag the ring).
79
+ * Each call has a `seq`: refetches can answer out of order, so keep the
80
+ * answer of the latest one.
81
+ *
82
+ * It opens its own stream with `realtime.connect()` (tuned by the module's
83
+ * config, then by `reconnectDelay`, `maxReconnectDelay`, `idleTimeout`
84
+ * given here), or listens on the `stream` passed; tuning given with
85
+ * `stream` throws. The stream reconnects on its own; when it closes for
86
+ * good (`watch.stream.onClose`, `watch.closed`), poll the count instead.
87
+ *
88
+ * @returns the watch: `close()` it on sign-out.
89
+ */
90
+ onChange(params: OnChangeParams): NotificationsWatch;
91
+ }
92
+ //# sourceMappingURL=notifications-module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"notifications-module.d.ts","sourceRoot":"","sources":["../src/notifications-module.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAK/C,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAA;AACrD,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAA;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAC3C,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAC/C,OAAO,KAAK,EACV,WAAW,EACX,WAAW,EACX,QAAQ,EACR,uBAAuB,EACvB,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,aAAa,EACb,aAAa,EACb,UAAU,EACV,UAAU,EACX,MAAM,YAAY,CAAA;AAanB;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,qBAAa,mBAAmB;IAC9B,QAAQ,CAAC,WAAW,EAAE,oBAAoB,CAAA;IAC1C,QAAQ,CAAC,UAAU,EAAE,mBAAmB,CAAA;IACxC,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAA;IAE9B,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAc;IAClC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAQ;IACrC,yFAAyF;IACzF,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAgB;gBAE7B,GAAG,EAAE,YAAY,EAAE,MAAM,EAAE,mBAAmB;IAY1D;;;OAGG;IACG,IAAI,CAAC,MAAM,GAAE,uBAA4B,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAmB3E;;;OAGG;IACG,KAAK,CAAC,MAAM,GAAE,WAAgB,GAAG,OAAO,CAAC,WAAW,CAAC;IAI3D,2FAA2F;IACrF,IAAI,CAAC,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAI3C,wEAAwE;IAClE,MAAM,CAAC,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAI7C,yFAAyF;IACnF,OAAO,CAAC,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAI9C,gFAAgF;IAC1E,MAAM,CAAC,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAI7C;;;;OAIG;IACG,OAAO,CAAC,MAAM,GAAE,aAAkB,GAAG,OAAO,CAAC,aAAa,CAAC;IASjE;;;;;;OAMG;IACG,IAAI,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;IAmBnD;;;;;;;;;;;;;;;;OAgBG;IACH,QAAQ,CAAC,MAAM,EAAE,cAAc,GAAG,kBAAkB;CAsBrD"}