@12-apps/notifications 4.12.0 → 4.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-WZBX7YCE.js → chunk-53SH5ABN.js} +82 -34
- package/dist/chunk-53SH5ABN.js.map +1 -0
- package/dist/{chunk-PNY6S6WH.js → chunk-643HNPQJ.js} +4 -4
- package/dist/chunk-643HNPQJ.js.map +1 -0
- package/dist/{chunk-2IAHFIXS.js → chunk-AN6IX4AE.js} +4 -3
- package/dist/chunk-AN6IX4AE.js.map +1 -0
- package/dist/{chunk-CPQKKLPS.js → chunk-CSMFJJXY.js} +1 -1
- package/dist/{chunk-CPQKKLPS.js.map → chunk-CSMFJJXY.js.map} +1 -1
- package/dist/{chunk-FBBPS2LT.js → chunk-QPO6NSRR.js} +2 -2
- package/dist/{chunk-GK6GSC2J.js → chunk-XFODKRRB.js} +2 -2
- package/dist/{create-api-notifications-BTudlaSC.d.ts → create-api-notifications-cIEbFqoZ.d.ts} +121 -30
- package/dist/{create-web-notifications-2xxbKnrW.d.ts → create-web-notifications-32Myo-ww.d.ts} +31 -9
- package/dist/{generators-CQYdJfB5.d.ts → generators-GUF-Kml-.d.ts} +1 -1
- package/dist/hono/index.d.ts +5 -5
- package/dist/hono/index.js +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/{jobs-CaovU4GM.d.ts → jobs-wKoOz91Q.d.ts} +1 -1
- package/dist/manifest/server.d.ts +6 -6
- package/dist/manifest/server.js +4 -4
- package/dist/manifest/web.d.ts +3 -3
- package/dist/manifest/web.js +2 -2
- package/dist/{panel-MKI4PTNZ.js → panel-JL5RDEHY.js} +2 -2
- package/dist/{preferences-screen-S3ZHX5LB.js → preferences-screen-YRPNUZS5.js} +2 -2
- package/dist/react/index.d.ts +4 -4
- package/dist/react/index.js +2 -2
- package/dist/server/index.d.ts +7 -7
- package/dist/server/index.js +4 -4
- package/dist/{types-H_aFzLA0.d.ts → types-DPiePHJD.d.ts} +19 -1
- package/dist/web-push/index.d.ts +2 -2
- package/dist/{web-push-C6U-5JCV.d.ts → web-push-DUn_d_gj.d.ts} +12 -2
- package/dist/{wire-Bn6aA2nL.d.ts → wire-CJka1AvM.d.ts} +1 -1
- package/package.json +2 -2
- package/prisma/migrations/20260914210000_scope_push_subscriptions_per_store/migration.sql +31 -0
- package/prisma/notifications.prisma +12 -0
- package/src/react/create-web-notifications.tsx +12 -2
- package/src/react/hooks.ts +24 -4
- package/src/react/index.ts +1 -0
- package/src/server/context.ts +15 -0
- package/src/server/db.ts +50 -8
- package/src/server/dispatch.ts +9 -2
- package/src/server/inbox.ts +87 -18
- package/src/server/index.ts +2 -0
- package/src/server/push-subscriptions.ts +61 -7
- package/src/server/router.ts +5 -1
- package/src/server/routes.ts +14 -5
- package/src/server/transports/web-push.ts +15 -2
- package/src/types.ts +19 -1
- package/dist/chunk-2IAHFIXS.js.map +0 -1
- package/dist/chunk-PNY6S6WH.js.map +0 -1
- package/dist/chunk-WZBX7YCE.js.map +0 -1
- /package/dist/{chunk-FBBPS2LT.js.map → chunk-QPO6NSRR.js.map} +0 -0
- /package/dist/{chunk-GK6GSC2J.js.map → chunk-XFODKRRB.js.map} +0 -0
- /package/dist/{panel-MKI4PTNZ.js.map → panel-JL5RDEHY.js.map} +0 -0
- /package/dist/{preferences-screen-S3ZHX5LB.js.map → preferences-screen-YRPNUZS5.js.map} +0 -0
package/src/server/inbox.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type {
|
|
|
5
5
|
NotificationPageAfter,
|
|
6
6
|
NotificationsDbProvider,
|
|
7
7
|
NotificationWhere,
|
|
8
|
+
NotificationWhereBranch,
|
|
8
9
|
} from './db';
|
|
9
10
|
|
|
10
11
|
/**
|
|
@@ -15,6 +16,29 @@ import type {
|
|
|
15
16
|
* never be resurrected by mark-read.
|
|
16
17
|
*/
|
|
17
18
|
|
|
19
|
+
/**
|
|
20
|
+
* The store whose ORIGIN the caller is reading from, or absent for the platform
|
|
21
|
+
* origin.
|
|
22
|
+
*
|
|
23
|
+
* A host that installs one storefront per store as its own PWA reads this from
|
|
24
|
+
* the request's hostname; a host with one origin never sets it and every read
|
|
25
|
+
* below is exactly what it was. Set, it narrows to that store's rows PLUS the
|
|
26
|
+
* platform-wide ones (`clientId IS NULL`) — a password reset or a security
|
|
27
|
+
* notice is about the person and not about a store, so hiding it inside the
|
|
28
|
+
* only app a customer opens would be a worse failure than the leak this fixes.
|
|
29
|
+
*/
|
|
30
|
+
export type NotificationScope = string | undefined;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* `clientId IN (<scope>, NULL)`, as a filter branch — or nothing at all.
|
|
34
|
+
*
|
|
35
|
+
* A disjunction rather than an `in`, because SQL `IN` never matches NULL and
|
|
36
|
+
* the NULL rows are precisely the ones that must survive every scope.
|
|
37
|
+
*/
|
|
38
|
+
function scopeBranch(scope: NotificationScope): NotificationWhereBranch[] {
|
|
39
|
+
return scope === undefined ? [] : [{ OR: [{ clientId: scope }, { clientId: null }] }];
|
|
40
|
+
}
|
|
41
|
+
|
|
18
42
|
export interface ListNotificationsInput {
|
|
19
43
|
/** `unread` narrows to unread rows; default lists all non-deleted. */
|
|
20
44
|
filter?: 'all' | 'unread';
|
|
@@ -34,10 +58,27 @@ const DEFAULT_PAGE = 20;
|
|
|
34
58
|
const MAX_PAGE = 100;
|
|
35
59
|
|
|
36
60
|
export interface NotificationInboxStore {
|
|
37
|
-
list(
|
|
38
|
-
|
|
61
|
+
list(
|
|
62
|
+
userId: string,
|
|
63
|
+
input?: ListNotificationsInput,
|
|
64
|
+
scope?: NotificationScope,
|
|
65
|
+
): Promise<ListNotificationsResult>;
|
|
66
|
+
/** Scoped with `list`, or the badge and the list it sits over disagree. */
|
|
67
|
+
unreadCount(userId: string, scope?: NotificationScope): Promise<number>;
|
|
39
68
|
markRead(userId: string, ids: readonly string[]): Promise<number>;
|
|
40
|
-
|
|
69
|
+
/**
|
|
70
|
+
* Scoped too, and this one is a WRITE.
|
|
71
|
+
*
|
|
72
|
+
* Unscoped, "mark all as read" pressed inside store A's app clears store B's
|
|
73
|
+
* unread rows everywhere — a cross-store write from the app that exists to be
|
|
74
|
+
* isolated, and strictly worse than the read leak. `markRead(ids)` and
|
|
75
|
+
* `softDelete(ids)` need nothing: their ids come from the already-scoped list.
|
|
76
|
+
*
|
|
77
|
+
* The platform-wide rows ARE cleared from any origin, and that follows from
|
|
78
|
+
* the scope rule rather than contradicting it — those rows are one person's,
|
|
79
|
+
* not one store's.
|
|
80
|
+
*/
|
|
81
|
+
markAllRead(userId: string, scope?: NotificationScope): Promise<number>;
|
|
41
82
|
softDelete(userId: string, ids: readonly string[]): Promise<number>;
|
|
42
83
|
}
|
|
43
84
|
|
|
@@ -66,27 +107,55 @@ function pageWhere(
|
|
|
66
107
|
userId: string,
|
|
67
108
|
filter: ListNotificationsInput['filter'],
|
|
68
109
|
anchor: NotificationPageAfter | undefined,
|
|
110
|
+
scope: NotificationScope,
|
|
69
111
|
): NotificationWhere {
|
|
112
|
+
// Two DISJUNCTIONS have to hold at once — the page boundary and the store
|
|
113
|
+
// scope — so they are AND-ed rather than merged. A second `OR` key on this
|
|
114
|
+
// object literal would overwrite the first, dropping either the scope or the
|
|
115
|
+
// anchor; the anchor only from page TWO onward, which is the case a cursor
|
|
116
|
+
// exists for and the case a single-page test never reaches.
|
|
117
|
+
const clauses: NotificationWhereBranch[] = [
|
|
118
|
+
// `(createdAt, id) < (anchor.createdAt, anchor.id)`, as a portable `where`.
|
|
119
|
+
...(anchor
|
|
120
|
+
? [
|
|
121
|
+
{
|
|
122
|
+
OR: [
|
|
123
|
+
{ createdAt: { lt: anchor.createdAt } },
|
|
124
|
+
{ createdAt: anchor.createdAt, id: { lt: anchor.id } },
|
|
125
|
+
],
|
|
126
|
+
},
|
|
127
|
+
]
|
|
128
|
+
: []),
|
|
129
|
+
...scopeBranch(scope),
|
|
130
|
+
];
|
|
70
131
|
return {
|
|
71
132
|
userId,
|
|
72
133
|
deletedAt: null,
|
|
73
134
|
...(filter === 'unread' ? { readAt: null } : {}),
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
135
|
+
...(clauses.length > 0 ? { AND: clauses } : {}),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The unread rows this scope can see — READ by the badge and WRITTEN by "mark
|
|
141
|
+
* all". One filter for both on purpose: the count and the write have to agree
|
|
142
|
+
* about which rows are in scope, and two copies of the same object literal is
|
|
143
|
+
* how a badge ends up saying 3 over a list of 2.
|
|
144
|
+
*/
|
|
145
|
+
function unreadWhere(userId: string, scope: NotificationScope): NotificationWhere {
|
|
146
|
+
const scoped = scopeBranch(scope);
|
|
147
|
+
return {
|
|
148
|
+
userId,
|
|
149
|
+
deletedAt: null,
|
|
150
|
+
readAt: null,
|
|
151
|
+
...(scoped.length > 0 ? { AND: scoped } : {}),
|
|
83
152
|
};
|
|
84
153
|
}
|
|
85
154
|
|
|
86
155
|
export function createInboxStore(db: NotificationsDbProvider): NotificationInboxStore {
|
|
87
156
|
return {
|
|
88
157
|
/** The owner's inbox, newest first, keyset-paginated, deleted excluded. */
|
|
89
|
-
async list(userId, input = {}) {
|
|
158
|
+
async list(userId, input = {}, scope) {
|
|
90
159
|
const client = await db();
|
|
91
160
|
const limit = Math.min(Math.max(input.limit ?? DEFAULT_PAGE, 1), MAX_PAGE);
|
|
92
161
|
const anchor = input.cursor
|
|
@@ -94,7 +163,7 @@ export function createInboxStore(db: NotificationsDbProvider): NotificationInbox
|
|
|
94
163
|
: undefined;
|
|
95
164
|
if (input.cursor && !anchor) return { items: [], nextCursor: null };
|
|
96
165
|
const rows = await client.notification.findMany({
|
|
97
|
-
where: pageWhere(userId, input.filter, anchor),
|
|
166
|
+
where: pageWhere(userId, input.filter, anchor, scope),
|
|
98
167
|
// `id` tie-breaks equal timestamps so pages never skip/repeat.
|
|
99
168
|
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
|
100
169
|
take: limit + 1,
|
|
@@ -107,9 +176,9 @@ export function createInboxStore(db: NotificationsDbProvider): NotificationInbox
|
|
|
107
176
|
},
|
|
108
177
|
|
|
109
178
|
/** Unread badge count (non-deleted, unread). */
|
|
110
|
-
async unreadCount(userId) {
|
|
179
|
+
async unreadCount(userId, scope) {
|
|
111
180
|
const client = await db();
|
|
112
|
-
return client.notification.count({ where:
|
|
181
|
+
return client.notification.count({ where: unreadWhere(userId, scope) });
|
|
113
182
|
},
|
|
114
183
|
|
|
115
184
|
/**
|
|
@@ -128,10 +197,10 @@ export function createInboxStore(db: NotificationsDbProvider): NotificationInbox
|
|
|
128
197
|
},
|
|
129
198
|
|
|
130
199
|
/** Mark every unread notification of the owner read ("mark all"). */
|
|
131
|
-
async markAllRead(userId) {
|
|
200
|
+
async markAllRead(userId, scope) {
|
|
132
201
|
const client = await db();
|
|
133
202
|
const result = await client.notification.updateMany({
|
|
134
|
-
where:
|
|
203
|
+
where: unreadWhere(userId, scope),
|
|
135
204
|
data: { readAt: new Date() },
|
|
136
205
|
});
|
|
137
206
|
return result.count;
|
package/src/server/index.ts
CHANGED
|
@@ -34,11 +34,13 @@ export type {
|
|
|
34
34
|
NotificationPreferenceDelegate,
|
|
35
35
|
NotificationPreferenceRow,
|
|
36
36
|
NotificationWhere,
|
|
37
|
+
NotificationWhereBranch,
|
|
37
38
|
NotificationsDb,
|
|
38
39
|
NotificationsDbClient,
|
|
39
40
|
NotificationsDbProvider,
|
|
40
41
|
PushSubscriptionDelegate,
|
|
41
42
|
PushSubscriptionRow,
|
|
43
|
+
PushSubscriptionWhere,
|
|
42
44
|
} from './db';
|
|
43
45
|
|
|
44
46
|
export type { ListNotificationsInput, NotificationInboxStore } from './inbox';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { NotificationLogger } from '../types';
|
|
2
2
|
|
|
3
|
-
import type { NotificationsDbProvider } from './db';
|
|
3
|
+
import type { NotificationsDbProvider, PushSubscriptionWhere } from './db';
|
|
4
4
|
import type { WebPushSubscriptionSource } from './transports/web-push';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -16,6 +16,41 @@ export interface PushSubscriptionInput {
|
|
|
16
16
|
keys: { p256dh: string; auth: string };
|
|
17
17
|
/** Optional browser/device hint for a device list. */
|
|
18
18
|
userAgent?: string;
|
|
19
|
+
/**
|
|
20
|
+
* Which ORIGIN this browser subscribed on — the HOST's resolved
|
|
21
|
+
* value, never anything the caller sent. Absent/null = the platform origin.
|
|
22
|
+
*/
|
|
23
|
+
clientId?: string | null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Which of a user's subscriptions one notification may reach.
|
|
28
|
+
*
|
|
29
|
+
* Stated as a rule on the SUBSCRIPTION rather than as a fallback, because the
|
|
30
|
+
* fallback form ("the platform's rows only when the store's are absent")
|
|
31
|
+
* silently changes the platform origin's behaviour, and a marketplace host must
|
|
32
|
+
* be unaffected by this change:
|
|
33
|
+
*
|
|
34
|
+
* | the subscription was registered on | it receives |
|
|
35
|
+
* |---|---|
|
|
36
|
+
* | the PLATFORM origin (`client_id IS NULL`) | every notification — as today |
|
|
37
|
+
* | store X's origin | store X's, and platform-wide ones (`clientId IS NULL`) |
|
|
38
|
+
*
|
|
39
|
+
* Nothing ever reaches a subscription registered on a DIFFERENT store's origin.
|
|
40
|
+
* It follows without a special case that a store-B notification reaches a
|
|
41
|
+
* customer who installed only store A through their PLATFORM subscription, and
|
|
42
|
+
* through neither app.
|
|
43
|
+
*
|
|
44
|
+
* `notificationClientId` is the NOTIFICATION's tenant. `undefined` (nobody
|
|
45
|
+
* asked to narrow) and `null` (a platform-wide notification) both mean every
|
|
46
|
+
* row, which is why they share a branch.
|
|
47
|
+
*/
|
|
48
|
+
function reachableBy(
|
|
49
|
+
userId: string,
|
|
50
|
+
notificationClientId?: string | null,
|
|
51
|
+
): PushSubscriptionWhere {
|
|
52
|
+
if (notificationClientId === undefined || notificationClientId === null) return { userId };
|
|
53
|
+
return { userId, OR: [{ clientId: null }, { clientId: notificationClientId }] };
|
|
19
54
|
}
|
|
20
55
|
|
|
21
56
|
export interface PushSubscriptionStore extends WebPushSubscriptionSource {
|
|
@@ -34,8 +69,19 @@ export interface PushSubscriptionStore extends WebPushSubscriptionSource {
|
|
|
34
69
|
save(userId: string, input: PushSubscriptionInput): Promise<void>;
|
|
35
70
|
/** Remove one browser's subscription (owner-scoped; unknown = no-op). */
|
|
36
71
|
remove(userId: string, endpoint: string): Promise<void>;
|
|
37
|
-
/**
|
|
38
|
-
|
|
72
|
+
/**
|
|
73
|
+
* How many devices the user has registered.
|
|
74
|
+
*
|
|
75
|
+
* TWO callers with different questions. The settings screen asks unscoped —
|
|
76
|
+
* "you have 2 devices" is a fact about the PERSON — and passes nothing. The
|
|
77
|
+
* dispatch path passes the notification's tenant, because this is what
|
|
78
|
+
* `supports()` gates on: left unscoped there, the router would enqueue a
|
|
79
|
+
* WEB_PUSH delivery for a notification no reachable subscription exists for,
|
|
80
|
+
* `send` would find an empty list and throw, and the sweep would burn every
|
|
81
|
+
* attempt before writing DEAD — a FAILED row for something that was never
|
|
82
|
+
* undeliverable, only out of scope.
|
|
83
|
+
*/
|
|
84
|
+
count(userId: string, notificationClientId?: string | null): Promise<number>;
|
|
39
85
|
/**
|
|
40
86
|
* Whether THIS endpoint is currently registered to THIS user.
|
|
41
87
|
*
|
|
@@ -75,12 +121,18 @@ export function createPushSubscriptionStore(
|
|
|
75
121
|
endpoint: input.endpoint,
|
|
76
122
|
p256dh: input.keys.p256dh,
|
|
77
123
|
auth: input.keys.auth,
|
|
124
|
+
clientId: input.clientId ?? null,
|
|
78
125
|
userAgent: input.userAgent ?? null,
|
|
79
126
|
},
|
|
127
|
+
// Re-stamped on every save, so the same browser moving between a store's
|
|
128
|
+
// app and the platform corrects its own scope rather than keeping the
|
|
129
|
+
// first origin it ever subscribed from. A scope change on the SAME user
|
|
130
|
+
// is not a re-own and must not log one.
|
|
80
131
|
update: {
|
|
81
132
|
userId,
|
|
82
133
|
p256dh: input.keys.p256dh,
|
|
83
134
|
auth: input.keys.auth,
|
|
135
|
+
clientId: input.clientId ?? null,
|
|
84
136
|
userAgent: input.userAgent ?? null,
|
|
85
137
|
},
|
|
86
138
|
});
|
|
@@ -91,9 +143,9 @@ export function createPushSubscriptionStore(
|
|
|
91
143
|
await client.pushSubscription.deleteMany({ where: { userId, endpoint } });
|
|
92
144
|
},
|
|
93
145
|
|
|
94
|
-
async count(userId) {
|
|
146
|
+
async count(userId, notificationClientId) {
|
|
95
147
|
const client = await db();
|
|
96
|
-
return client.pushSubscription.count({ where:
|
|
148
|
+
return client.pushSubscription.count({ where: reachableBy(userId, notificationClientId) });
|
|
97
149
|
},
|
|
98
150
|
|
|
99
151
|
async isRegisteredTo(userId, endpoint) {
|
|
@@ -102,9 +154,11 @@ export function createPushSubscriptionStore(
|
|
|
102
154
|
return row?.userId === userId;
|
|
103
155
|
},
|
|
104
156
|
|
|
105
|
-
async list(userId) {
|
|
157
|
+
async list(userId, notificationClientId) {
|
|
106
158
|
const client = await db();
|
|
107
|
-
const rows = await client.pushSubscription.findMany({
|
|
159
|
+
const rows = await client.pushSubscription.findMany({
|
|
160
|
+
where: reachableBy(userId, notificationClientId),
|
|
161
|
+
});
|
|
108
162
|
return rows.map((row) => ({
|
|
109
163
|
id: row.id,
|
|
110
164
|
endpoint: row.endpoint,
|
package/src/server/router.ts
CHANGED
|
@@ -279,7 +279,11 @@ export function createNotificationRouter(deps: NotificationRouterDeps): Notifica
|
|
|
279
279
|
Loading first also means a notification addressed to nobody now throws
|
|
280
280
|
before any content is built, which is the cheaper order anyway.
|
|
281
281
|
*/
|
|
282
|
-
const recipient = await loadRecipient(
|
|
282
|
+
const recipient = await loadRecipient(
|
|
283
|
+
deps,
|
|
284
|
+
event.recipient.userId,
|
|
285
|
+
event.recipient.clientId ?? null,
|
|
286
|
+
);
|
|
283
287
|
if (!recipient) throw new UnknownNotificationRecipientError(event.recipient.userId);
|
|
284
288
|
|
|
285
289
|
// Forwarded exactly as the directory stated it, `undefined` included: the
|
package/src/server/routes.ts
CHANGED
|
@@ -66,12 +66,14 @@ interface NotificationRoutesDeps {
|
|
|
66
66
|
async function channelAvailability(
|
|
67
67
|
deps: NotificationRoutesDeps,
|
|
68
68
|
userId: string,
|
|
69
|
+
scopeClientId: string | null,
|
|
69
70
|
): Promise<Record<NotificationChannel, boolean>> {
|
|
70
71
|
const contact = await deps.contacts.getContact(userId);
|
|
71
72
|
const recipient = {
|
|
72
73
|
userId,
|
|
73
74
|
email: contact?.email ?? null,
|
|
74
75
|
phone: contact?.phone ?? null,
|
|
76
|
+
clientId: scopeClientId,
|
|
75
77
|
pushSubscriptionCount: 1,
|
|
76
78
|
};
|
|
77
79
|
return Object.fromEntries(
|
|
@@ -86,6 +88,7 @@ async function channelAvailability(
|
|
|
86
88
|
async function preferencesPayload(
|
|
87
89
|
deps: NotificationRoutesDeps,
|
|
88
90
|
userId: string,
|
|
91
|
+
scopeClientId: string | null,
|
|
89
92
|
): Promise<{
|
|
90
93
|
preferences: Record<string, Record<string, boolean>>;
|
|
91
94
|
availability: Record<NotificationChannel, boolean>;
|
|
@@ -93,7 +96,7 @@ async function preferencesPayload(
|
|
|
93
96
|
}> {
|
|
94
97
|
const [preferences, availability] = await Promise.all([
|
|
95
98
|
deps.preferences.get(userId),
|
|
96
|
-
channelAvailability(deps, userId),
|
|
99
|
+
channelAvailability(deps, userId, scopeClientId),
|
|
97
100
|
]);
|
|
98
101
|
// `categories` travels with the matrix so the settings screen renders the
|
|
99
102
|
// HOST's taxonomy without being told it twice (once in the api config, once
|
|
@@ -111,6 +114,7 @@ function inboxRoutes(deps: NotificationRoutesDeps): NotificationsRoute[] {
|
|
|
111
114
|
await deps.inbox.list(
|
|
112
115
|
actor.userId,
|
|
113
116
|
parseListQuery(query, messagesOf(deps, locale)),
|
|
117
|
+
actor.scopeClientId,
|
|
114
118
|
),
|
|
115
119
|
),
|
|
116
120
|
),
|
|
@@ -120,7 +124,7 @@ function inboxRoutes(deps: NotificationRoutesDeps): NotificationsRoute[] {
|
|
|
120
124
|
path: '/notifications/unread-count',
|
|
121
125
|
handle: guarded(async ({ actor }) =>
|
|
122
126
|
// Polled by the SPAs, so it stays a single indexed COUNT.
|
|
123
|
-
ok({ count: await deps.inbox.unreadCount(actor.userId) }),
|
|
127
|
+
ok({ count: await deps.inbox.unreadCount(actor.userId, actor.scopeClientId) }),
|
|
124
128
|
),
|
|
125
129
|
},
|
|
126
130
|
{
|
|
@@ -130,7 +134,7 @@ function inboxRoutes(deps: NotificationRoutesDeps): NotificationsRoute[] {
|
|
|
130
134
|
const target = parseMarkReadBody(body, messagesOf(deps, locale));
|
|
131
135
|
const updated =
|
|
132
136
|
'all' in target
|
|
133
|
-
? await deps.inbox.markAllRead(actor.userId)
|
|
137
|
+
? await deps.inbox.markAllRead(actor.userId, actor.scopeClientId)
|
|
134
138
|
: await deps.inbox.markRead(actor.userId, target.ids);
|
|
135
139
|
// Only when something actually flipped. This endpoint is idempotent, so
|
|
136
140
|
// a re-send of an already-read id reports `updated: 0` and has changed
|
|
@@ -163,7 +167,9 @@ function preferenceRoutes(deps: NotificationRoutesDeps): NotificationsRoute[] {
|
|
|
163
167
|
{
|
|
164
168
|
method: 'GET',
|
|
165
169
|
path: '/notification-preferences',
|
|
166
|
-
handle: guarded(async ({ actor }) =>
|
|
170
|
+
handle: guarded(async ({ actor }) =>
|
|
171
|
+
ok(await preferencesPayload(deps, actor.userId, actor.scopeClientId ?? null)),
|
|
172
|
+
),
|
|
167
173
|
},
|
|
168
174
|
{
|
|
169
175
|
method: 'PUT',
|
|
@@ -175,7 +181,7 @@ function preferenceRoutes(deps: NotificationRoutesDeps): NotificationsRoute[] {
|
|
|
175
181
|
actor.userId,
|
|
176
182
|
parsePreferencesBody(body, messagesOf(deps, locale)),
|
|
177
183
|
);
|
|
178
|
-
return ok(await preferencesPayload(deps, actor.userId));
|
|
184
|
+
return ok(await preferencesPayload(deps, actor.userId, actor.scopeClientId ?? null));
|
|
179
185
|
}),
|
|
180
186
|
},
|
|
181
187
|
];
|
|
@@ -208,6 +214,9 @@ function pushRoutes(deps: NotificationRoutesDeps): NotificationsRoute[] {
|
|
|
208
214
|
const input = parsePushSubscriptionBody(body, messagesOf(deps, locale));
|
|
209
215
|
const userAgent = headers?.['user-agent'];
|
|
210
216
|
await deps.pushSubscriptions.save(actor.userId, {
|
|
217
|
+
// The HOST's resolved origin, never the body's — a caller cannot
|
|
218
|
+
// choose which store's app their browser counts as.
|
|
219
|
+
clientId: actor.scopeClientId ?? null,
|
|
211
220
|
...input,
|
|
212
221
|
...(userAgent ? { userAgent } : {}),
|
|
213
222
|
});
|
|
@@ -90,7 +90,20 @@ export interface WebPushDriverDeclaration extends DriverDeclarationBase {
|
|
|
90
90
|
|
|
91
91
|
/** The subscriptions the transport reads and prunes (db-backed by the mount). */
|
|
92
92
|
export interface WebPushSubscriptionSource {
|
|
93
|
-
|
|
93
|
+
/**
|
|
94
|
+
* The subscriptions one notification may reach.
|
|
95
|
+
*
|
|
96
|
+
* `notificationClientId` is the notification's tenant — `null` for a
|
|
97
|
+
* platform-wide one, which every subscription receives. An ADOPTER with a
|
|
98
|
+
* hand-written source must honour it: a function declared with fewer
|
|
99
|
+
* parameters still type-checks, so an un-updated implementation silently
|
|
100
|
+
* ignores the scope and keeps fanning out to every origin, with nothing
|
|
101
|
+
* failing to compile to say so.
|
|
102
|
+
*/
|
|
103
|
+
list(
|
|
104
|
+
userId: string,
|
|
105
|
+
notificationClientId?: string | null,
|
|
106
|
+
): Promise<{ id: string; endpoint: string; p256dh: string; auth: string }[]>;
|
|
94
107
|
prune(id: string): Promise<void>;
|
|
95
108
|
}
|
|
96
109
|
|
|
@@ -159,7 +172,7 @@ export function webPushTransport(
|
|
|
159
172
|
supports: (recipient: TransportRecipient) => recipient.pushSubscriptionCount > 0,
|
|
160
173
|
format: formatWebPush,
|
|
161
174
|
async send(message, recipient) {
|
|
162
|
-
const rows = await subscriptions.list(recipient.userId);
|
|
175
|
+
const rows = await subscriptions.list(recipient.userId, recipient.clientId);
|
|
163
176
|
if (rows.length === 0) throw new Error('Recipient no longer has push subscriptions.');
|
|
164
177
|
const payload = JSON.stringify(message);
|
|
165
178
|
let delivered = 0;
|
package/src/types.ts
CHANGED
|
@@ -190,8 +190,26 @@ export interface TransportRecipient {
|
|
|
190
190
|
locale?: string | null;
|
|
191
191
|
/** Phone as the host stores it (transports normalize per provider rules). */
|
|
192
192
|
phone: string | null;
|
|
193
|
-
/**
|
|
193
|
+
/**
|
|
194
|
+
* How many push subscriptions this NOTIFICATION can actually reach — not how
|
|
195
|
+
* many the user holds. Scoped by {@link TransportRecipient.clientId}.
|
|
196
|
+
*/
|
|
194
197
|
pushSubscriptionCount: number;
|
|
198
|
+
/**
|
|
199
|
+
* The store this notification belongs to, or `null` for a platform-wide one
|
|
200
|
+
*.
|
|
201
|
+
*
|
|
202
|
+
* REQUIRED, and deliberately so where optional is the tempting answer. An
|
|
203
|
+
* optional field fails OPEN: a construction site that forgets it yields
|
|
204
|
+
* `undefined`, which the push scope reads as "platform notification -> every
|
|
205
|
+
* subscription" — precisely the cross-store fan-out this exists to stop.
|
|
206
|
+
* Three construction sites is the argument FOR requiring it, not against; the
|
|
207
|
+
* compiler then names them.
|
|
208
|
+
*
|
|
209
|
+
* Not a breaking change for adopters: every external use CONSUMES a recipient
|
|
210
|
+
* through `supports`/`send` below, and the only constructors are in-package.
|
|
211
|
+
*/
|
|
212
|
+
clientId: string | null;
|
|
195
213
|
}
|
|
196
214
|
|
|
197
215
|
/**
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/inbox-state.ts","../src/react/hooks.ts","../src/react/bell-icon.tsx"],"sourcesContent":["import type { InboxNotification } from '../wire';\n\nimport type { NotificationsApiClient } from './api';\n\n/**\n * The inbox's client state, as ONE store shared by the bell and the panel.\n *\n * They have to share it: marking a row read in the panel must move the badge in\n * the same tick, and an arrival must add a row to the list AND to the count.\n * the origin got that for free from a react-query cache the host had already\n * mounted; a published package cannot assume one — a query client is a host\n * decision, and requiring a particular one (or a particular version of one) is\n * the kind of dependency that keeps a package out of a host that made the other\n * choice. So the sharing is explicit and dependency-free: one subscribable\n * store, read through `useSyncExternalStore`.\n *\n * Optimistic on every write, with invalidate-on-error: the badge and the list\n * update instantly, and a failed write refetches the server truth rather than\n * leaving the screen asserting something the database does not say.\n */\n\nexport const PAGE_SIZE = 20;\n\n/** The badge's poll while nothing is pushing to us. */\nexport const BADGE_POLL_MS = 60_000;\n\n/**\n * The badge's interval while a realtime connection is live.\n *\n * Five minutes, not \"never\": this is the reconcile that catches an event the bus\n * dropped, and it costs one COUNT per open tab per five minutes. Deliberately\n * far slower than an operational screen's — a bell badge is ambient, and the\n * arrival that matters is pushed within milliseconds anyway. The poll does NOT\n * stop, which is the standing contract: a dropped event must cost latency and\n * never correctness.\n */\nexport const BADGE_RECONCILE_MS = 300_000;\n\nexport type InboxListStatus = 'idle' | 'pending' | 'ready' | 'error';\n\nexport interface InboxState {\n unread: number;\n items: InboxNotification[];\n status: InboxListStatus;\n /** A cursor means there is another page. */\n nextCursor: string | null;\n loadingMore: boolean;\n}\n\nexport interface InboxStore {\n getState(): InboxState;\n subscribe(listener: () => void): () => void;\n /** Load the first page (idempotent while one is in flight). */\n open(): void;\n /** Refetch the badge count. */\n refreshBadge(): void;\n /** Refetch both — what a realtime hint or a failed write triggers. */\n invalidate(): void;\n loadMore(): void;\n markRead(ids: readonly string[]): void;\n markAllRead(): void;\n remove(id: string): void;\n}\n\nconst EMPTY: InboxState = {\n unread: 0,\n items: [],\n status: 'idle',\n nextCursor: null,\n loadingMore: false,\n};\n\n/** The mutable cell the functions below share, so each one stays small. */\ninterface Cell {\n state: InboxState;\n listeners: Set<() => void>;\n /** Fences a stale reload: a newer one must always win. */\n request: number;\n}\n\nfunction patch(cell: Cell, next: Partial<InboxState>): void {\n cell.state = { ...cell.state, ...next };\n for (const listener of cell.listeners) listener();\n}\n\n/** Refetch the badge count. The number is always one the server just gave us. */\nfunction refreshBadge(cell: Cell, api: NotificationsApiClient): void {\n void api\n .unreadCount()\n .then((unread) => patch(cell, { unread }))\n .catch(() => undefined);\n}\n\n/**\n * Reload page one, discarding whatever the optimistic path had produced.\n * `request` fences it: a reload that started before a newer one must not land\n * after it and reinstate stale rows.\n */\nfunction reloadList(cell: Cell, api: NotificationsApiClient): void {\n const token = (cell.request += 1);\n patch(cell, { status: cell.state.items.length > 0 ? cell.state.status : 'pending' });\n void api\n .listNotifications({ limit: PAGE_SIZE })\n .then((page) => {\n if (token !== cell.request) return;\n patch(cell, { items: page.items, nextCursor: page.nextCursor, status: 'ready' });\n })\n .catch(() => {\n if (token !== cell.request) return;\n patch(cell, { status: 'error' });\n });\n}\n\nfunction invalidate(cell: Cell, api: NotificationsApiClient): void {\n refreshBadge(cell, api);\n if (cell.state.status !== 'idle') reloadList(cell, api);\n}\n\n/** Apply an optimistic edit; on failure, take the server's word instead. */\nfunction write(\n cell: Cell,\n api: NotificationsApiClient,\n apply: () => void,\n send: () => Promise<{ ok: boolean }>,\n): void {\n apply();\n void send()\n .then((result) => {\n if (!result.ok) invalidate(cell, api);\n })\n .catch(() => invalidate(cell, api));\n}\n\nfunction bumpUnread(cell: Cell, delta: number): void {\n patch(cell, { unread: Math.max(0, cell.state.unread + delta) });\n}\n\nfunction loadMore(cell: Cell, api: NotificationsApiClient): void {\n const cursor = cell.state.nextCursor;\n if (!cursor || cell.state.loadingMore) return;\n patch(cell, { loadingMore: true });\n void api\n .listNotifications({ cursor, limit: PAGE_SIZE })\n .then((page) => {\n patch(cell, {\n items: [...cell.state.items, ...page.items],\n nextCursor: page.nextCursor,\n loadingMore: false,\n });\n })\n .catch(() => patch(cell, { loadingMore: false }));\n}\n\nfunction markRead(cell: Cell, api: NotificationsApiClient, ids: readonly string[]): void {\n const readAt = new Date().toISOString();\n let flipped = 0;\n const items = cell.state.items.map((item) => {\n if (!ids.includes(item.id) || item.readAt !== null) return item;\n flipped += 1;\n return { ...item, readAt };\n });\n if (flipped === 0) return;\n write(\n cell,\n api,\n () => {\n patch(cell, { items });\n bumpUnread(cell, -flipped);\n },\n () => api.markRead(ids),\n );\n}\n\nfunction remove(cell: Cell, api: NotificationsApiClient, id: string): void {\n const target = cell.state.items.find((item) => item.id === id);\n if (!target) return;\n const items = cell.state.items.filter((item) => item.id !== id);\n write(\n cell,\n api,\n () => {\n patch(cell, { items });\n if (target.readAt === null) bumpUnread(cell, -1);\n },\n () => api.remove([id]),\n );\n}\n\nexport function createInboxStore(api: NotificationsApiClient): InboxStore {\n const cell: Cell = { state: EMPTY, listeners: new Set(), request: 0 };\n return {\n getState: () => cell.state,\n subscribe(listener) {\n cell.listeners.add(listener);\n return () => cell.listeners.delete(listener);\n },\n open() {\n if (cell.state.status === 'idle') reloadList(cell, api);\n },\n refreshBadge: () => refreshBadge(cell, api),\n invalidate: () => invalidate(cell, api),\n loadMore: () => loadMore(cell, api),\n markRead: (ids) => markRead(cell, api, ids),\n markAllRead() {\n const readAt = new Date().toISOString();\n const items = cell.state.items.map((item) => ({ ...item, readAt: item.readAt ?? readAt }));\n write(\n cell,\n api,\n () => patch(cell, { items, unread: 0 }),\n () => api.markAllRead(),\n );\n },\n remove: (id) => remove(cell, api, id),\n };\n}\n","import { useEffect, useSyncExternalStore } from 'react';\n\nimport {\n BADGE_POLL_MS,\n BADGE_RECONCILE_MS,\n type InboxState,\n type InboxStore,\n} from './inbox-state';\n\n/**\n * The two hooks the bell and the panel use, and the realtime seam between them.\n *\n * A host that has a message bus passes `subscribe`; one that has not passes\n * nothing and keeps the 60 s poll. The bell ships in this package and mounts in\n * whatever embeds it, so it must not require the host to have adopted anything.\n */\n\n/**\n * How the surface learns an inbox changed without asking.\n *\n * Called once per mounted bell with a callback that means only \"ask again\" — no\n * payload, so the number on screen is always one the server just gave us.\n * Returns its own teardown. A host wires this to whatever it already has.\n */\nexport type NotificationsSubscribe = (onHint: () => void) => () => void;\n\n/**\n * The same wiring, as a HOOK — for a host whose realtime connection lives in\n * React context rather than in a module.\n *\n * `subscribe` above is supplied at FACTORY time, which is module scope, and a\n * context-bound connection cannot be reached from there: the provider holding\n * it is inside the tree. A host in that shape (a `<UserRealtimeProvider>` and a\n * `useUserTopics` hook, which is the common one) had no way to pass anything at\n * all, and the badge simply never heard an event.\n *\n * So this is the second door, and it is the one `@12-apps/app-shell` already\n * uses for the same problem — its consent dialog takes a `useSignal` hook for\n * exactly this reason. Two packages solving one problem two ways is how an\n * adopter ends up believing the feature is unavailable to it.\n *\n * Called during render, so it may use context and hooks freely. Pass one or\n * the other; passing both runs both, which is a host's business.\n */\nexport type NotificationsSignalHook = (onHint: () => void) => void;\n\nexport function useInboxState(store: InboxStore): InboxState {\n return useSyncExternalStore(store.subscribe, store.getState, store.getState);\n}\n\n/** What both badge hooks below take, and what the bell passes them. */\nexport interface BadgeSyncOptions {\n enabled?: boolean;\n subscribe?: NotificationsSubscribe;\n useSignal?: NotificationsSignalHook;\n}\n\n/**\n * What a disabled badge reads, instead of whatever the store happens to hold.\n *\n * A CONSTANT, so `useSyncExternalStore`'s identity comparison sees no change\n * across the renders of a signed-out session.\n */\nconst NOTHING_TO_SHOW: InboxState = {\n unread: 0,\n items: [],\n status: 'idle',\n nextCursor: null,\n loadingMore: false,\n};\n\n/**\n * The badge's server state, kept fresh: pushed while a subscription is live,\n * polled otherwise.\n *\n * The whole state rather than the count, because every badge hook that layers\n * on top of it needs the poll and the subscription mounted exactly ONCE per\n * bell — read through two hooks, a bell that showed both a number and a tone\n * would open two of everything.\n *\n * ## `enabled` gates the ANSWER, not only the fetching\n *\n * It gates the poll and the subscription, which is the obvious half. It also\n * blanks the returned state, which is the half that was missing and matters\n * more: the store is per FACTORY and a host builds one at module scope for the\n * whole app, so signing out does not empty it — `refreshBadge` swallows the 401\n * and leaves the last number in place. Without this, a hook told there is\n * nobody signed in hands back the PREVIOUS reader's unread count and their\n * inbox rows.\n *\n * Deliberately here rather than at each caller. It was at each caller, three\n * times, in three shapes, and two of them were dead weight no test could reach\n * — which is what an invariant looks like just before one copy of it goes\n * missing.\n *\n * INTERNAL. Not exported from `./index`: it hands back rows as well as a count,\n * and a host wanting a number has `useUnreadCount` or the factory's\n * `useBellBadge`.\n */\nexport function useBadgeState(store: InboxStore, options: BadgeSyncOptions = {}): InboxState {\n const enabled = options.enabled ?? true;\n const subscribe = options.subscribe;\n const live = useInboxState(store);\n const state = enabled ? live : NOTHING_TO_SHOW;\n\n // Called unconditionally — it is a hook, so it cannot sit behind `enabled`.\n // The host's own hook decides what to do when there is nothing to hear.\n options.useSignal?.(() => {\n if (enabled) store.invalidate();\n });\n\n useEffect(() => {\n if (!enabled) return;\n store.refreshBadge();\n const unsubscribe = subscribe?.(() => store.invalidate());\n // A live subscription relaxes the poll to the reconcile interval; without\n // one it stays the 60 s poll.\n const interval = setInterval(\n () => store.refreshBadge(),\n subscribe ? BADGE_RECONCILE_MS : BADGE_POLL_MS,\n );\n const onFocus = (): void => store.refreshBadge();\n globalThis.addEventListener?.('focus', onFocus);\n return () => {\n clearInterval(interval);\n globalThis.removeEventListener?.('focus', onFocus);\n unsubscribe?.();\n };\n }, [store, enabled, subscribe]);\n\n return state;\n}\n\n/**\n * The bell badge number, for a host with its own trigger chrome.\n *\n * A host that also publishes live activities wants `useBellBadge` from the\n * factory instead — this one counts inbox rows and knows nothing about what is\n * happening right now.\n */\nexport function useUnreadCount(store: InboxStore, options: BadgeSyncOptions = {}): number {\n return useBadgeState(store, options).unread;\n}\n\n/** The panel's list — only fetches while the panel is open. */\nexport function useInboxList(store: InboxStore, open: boolean): InboxState {\n const state = useInboxState(store);\n useEffect(() => {\n if (open) store.open();\n }, [store, open]);\n return state;\n}\n","/** Inline SVG bell (no icon-library dependency in this package). */\nimport type { JSX } from 'react';\n\nimport { Box } from '@12-apps/ui/mui/Box';\n\nexport function BellIcon({\n size = 28,\n dim = false,\n}: {\n size?: number;\n dim?: boolean;\n}): JSX.Element {\n return (\n <Box\n component=\"svg\"\n viewBox=\"0 0 24 24\"\n aria-hidden\n sx={{\n width: size,\n height: size,\n fill: 'none',\n stroke: 'currentColor',\n opacity: dim ? 0.4 : 1,\n }}\n strokeWidth={1.8}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M6 9a6 6 0 0 1 12 0c0 5 2 6 2 6H4s2-1 2-6\" />\n <path d=\"M10 20a2 2 0 0 0 4 0\" />\n </Box>\n );\n}\n"],"mappings":";;;;;AAqBO,IAAM,YAAY;AAGlB,IAAM,gBAAgB;AAYtB,IAAM,qBAAqB;AA4BlC,IAAM,QAAoB;AAAA,EACxB,QAAQ;AAAA,EACR,OAAO,CAAC;AAAA,EACR,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,aAAa;AACf;AAUA,SAAS,MAAM,MAAY,MAAiC;AAC1D,OAAK,QAAQ,EAAE,GAAG,KAAK,OAAO,GAAG,KAAK;AACtC,aAAW,YAAY,KAAK,UAAW,UAAS;AAClD;AAHS;AAMT,SAAS,aAAa,MAAY,KAAmC;AACnE,OAAK,IACF,YAAY,EACZ,KAAK,CAAC,WAAW,MAAM,MAAM,EAAE,OAAO,CAAC,CAAC,EACxC,MAAM,MAAM,MAAS;AAC1B;AALS;AAYT,SAAS,WAAW,MAAY,KAAmC;AACjE,QAAM,QAAS,KAAK,WAAW;AAC/B,QAAM,MAAM,EAAE,QAAQ,KAAK,MAAM,MAAM,SAAS,IAAI,KAAK,MAAM,SAAS,UAAU,CAAC;AACnF,OAAK,IACF,kBAAkB,EAAE,OAAO,UAAU,CAAC,EACtC,KAAK,CAAC,SAAS;AACd,QAAI,UAAU,KAAK,QAAS;AAC5B,UAAM,MAAM,EAAE,OAAO,KAAK,OAAO,YAAY,KAAK,YAAY,QAAQ,QAAQ,CAAC;AAAA,EACjF,CAAC,EACA,MAAM,MAAM;AACX,QA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AAW,sBAAsB,SAAS,OAAO;AACjD,oBAAc;AAAA,IAChB;AAAA,EACF,GAAG,CAAC,OAAO,SAAS,SAAS,CAAC;AAE9B,SAAO;AACT;AAhCgB;AAyCT,SAAS,eAAe,OAAmB,UAA4B,CAAC,GAAW;AACxF,SAAO,cAAc,OAAO,OAAO,EAAE;AACvC;AAFgB;AAKT,SAAS,aAAa,OAAmB,MAA2B;AACzE,QAAM,QAAQ,cAAc,KAAK;AACjC,YAAU,MAAM;AACd,QAAI,KAAM,OAAM,KAAK;AAAA,EACvB,GAAG,CAAC,OAAO,IAAI,CAAC;AAChB,SAAO;AACT;AANgB;;;AC9IhB,SAAS,WAAW;AAUhB,SAeE,KAfF;AARG,SAAS,SAAS;AAAA,EACvB,OAAO;AAAA,EACP,MAAM;AACR,GAGgB;AACd,SACE;AAAA,IAAC;AAAA;AAAA,MACC,WAAU;AAAA,MACV,SAAQ;AAAA,MACR,eAAW;AAAA,MACX,IAAI;AAAA,QACF,OAAO;AAAA,QACP,QAAQ;AAAA,QACR,MAAM;AAAA,QACN,QAAQ;AAAA,QACR,SAAS,MAAM,MAAM;AAAA,MACvB;AAAA,MACA,aAAa;AAAA,MACb,eAAc;AAAA,MACd,gBAAe;AAAA,MAEf;AAAA,4BAAC,UAAK,GAAE,6CAA4C;AAAA,QACpD,oBAAC,UAAK,GAAE,wBAAuB;AAAA;AAAA;AAAA,EACjC;AAEJ;AA3BgB;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/api.ts","../src/react/transport.ts","../src/react/create-web-notifications.tsx","../src/react/bell-badge.ts","../src/react/live-seen.ts","../src/react/bell-button.tsx","../src/react/panel-lazy.tsx","../src/react/page-lazy.tsx"],"sourcesContent":["import type { ChannelRow } from '../preferences-core';\nimport type { NotificationChannel } from '../types';\nimport type { ListNotificationsResult } from '../wire';\n\nimport type { NotificationsResult, NotificationsTransport } from './transport';\n\n/**\n * The wire client, bound to one mount (12-15).\n *\n * Every path this package's screens can call, in one place — which is what\n * makes the api half's route table and the web half's URLs one contract instead\n * of two lists that drift.\n */\n\n/** `GET <mount>/notification-preferences` and the PUT's answer. */\nexport interface PreferencesPayload {\n preferences: Record<string, ChannelRow>;\n availability: Record<NotificationChannel, boolean>;\n /** The host's taxonomy, so the screen renders it without being told twice. */\n categories: string[];\n}\n\n/** `GET <mount>/push-subscriptions`. */\nexport interface PushRegistrationPayload {\n /** null = web push is not configured on this deployment. */\n vapidPublicKey: string | null;\n count: number;\n /**\n * Whether the endpoint asked about is still registered to the caller. Present\n * only when one was passed — see {@link NotificationsApiClient.getPushRegistration}.\n */\n registered?: boolean;\n}\n\nexport interface NotificationsApiClient {\n listNotifications(input: {\n cursor?: string | null;\n limit?: number;\n filter?: 'all' | 'unread';\n }): Promise<ListNotificationsResult>;\n unreadCount(): Promise<number>;\n markRead(ids: readonly string[]): Promise<NotificationsResult<{ updated: number }>>;\n markAllRead(): Promise<NotificationsResult<{ updated: number }>>;\n remove(ids: readonly string[]): Promise<NotificationsResult<{ deleted: number }>>;\n getPreferences(): Promise<PreferencesPayload>;\n savePreference(\n category: string,\n channel: NotificationChannel,\n enabled: boolean,\n ): Promise<NotificationsResult<PreferencesPayload>>;\n /**\n * The deployment's VAPID key and the caller's device count — and, when an\n * `endpoint` is passed, whether the SERVER still has that exact subscription\n * under the caller's id. The browser holding a subscription object is not\n * evidence of that: a re-own or a 404/410 prune drops the row and leaves the\n * browser's object in place.\n */\n getPushRegistration(input?: { endpoint?: string }): Promise<PushRegistrationPayload>;\n savePushSubscription(input: {\n endpoint: string;\n keys: { p256dh: string; auth: string };\n }): Promise<NotificationsResult<{ count: number }>>;\n removePushSubscription(endpoint: string): Promise<NotificationsResult<{ count: number }>>;\n}\n\nexport function createNotificationsApiClient(\n apiBase: string,\n transport: NotificationsTransport,\n): NotificationsApiClient {\n const base = apiBase.replace(/\\/$/, '');\n const url = (path: string): string => `${base}${path}`;\n\n return {\n listNotifications({ cursor, limit, filter }) {\n const params = new URLSearchParams();\n if (limit !== undefined) params.set('limit', String(limit));\n if (cursor) params.set('cursor', cursor);\n if (filter) params.set('filter', filter);\n const query = params.toString();\n return transport.get<ListNotificationsResult>(\n url(`/notifications${query ? `?${query}` : ''}`),\n );\n },\n async unreadCount() {\n const { count } = await transport.get<{ count: number }>(\n url('/notifications/unread-count'),\n );\n return count;\n },\n markRead: (ids) =>\n transport.send(url('/notifications/mark-read'), 'POST', { ids: [...ids] }),\n markAllRead: () => transport.send(url('/notifications/mark-read'), 'POST', { all: true }),\n remove: (ids) => transport.send(url('/notifications/delete'), 'POST', { ids: [...ids] }),\n getPreferences: () => transport.get<PreferencesPayload>(url('/notification-preferences')),\n savePreference: (category, channel, enabled) =>\n transport.send(url('/notification-preferences'), 'PUT', {\n [category]: { [channel]: enabled },\n }),\n getPushRegistration: ({ endpoint } = {}) =>\n transport.get<PushRegistrationPayload>(\n url(\n endpoint\n ? `/push-subscriptions?endpoint=${encodeURIComponent(endpoint)}`\n : '/push-subscriptions',\n ),\n ),\n savePushSubscription: (input) => transport.send(url('/push-subscriptions'), 'POST', input),\n removePushSubscription: (endpoint) =>\n transport.send(url('/push-subscriptions'), 'DELETE', { endpoint }),\n };\n}\n","/**\n * How the notification screens reach their data (12-15) — the report-builder\n * transport doctrine: this is the ONLY way the surface performs I/O, so a\n * caller supplying one has substituted the entire backend without stubbing a\n * global. The default is same-origin `fetch` riding the browser's cookies.\n */\n\n/** A write outcome the screens branch on — never a thrown mutation. */\nexport type NotificationsResult<T> = { ok: true; data: T } | { ok: false; error: string };\n\n/** A failed read, carrying the status the screens branch on (401 = signed out). */\nexport class NotificationsHttpError extends Error {\n readonly status: number;\n constructor(status: number, message: string) {\n super(message);\n this.name = 'NotificationsHttpError';\n this.status = status;\n Object.setPrototypeOf(this, NotificationsHttpError.prototype);\n }\n}\n\nexport interface NotificationsTransport {\n /** A read. Returns the payload INSIDE the `{ data }` envelope. */\n get<T>(path: string): Promise<T>;\n /** A write. Returns a {@link NotificationsResult} rather than rejecting. */\n send<T>(path: string, method: string, body?: unknown): Promise<NotificationsResult<T>>;\n}\n\n/**\n * @param fallbackError What a failed write says when the server sent no\n * sentence of its own — REQUIRED, the host's words. `createWebNotifications`\n * already passes its (equally required) `messages.operationFailed`; only a\n * host constructing the transport directly writes it here. The old default\n * was one application's Portuguese, and the only string in this package the\n * required-messages port did not cover.\n */\nexport function httpNotificationsTransport(fallbackError: string): NotificationsTransport {\n return {\n async get<T>(path: string): Promise<T> {\n const response = await fetch(path, {\n credentials: 'same-origin',\n headers: { Accept: 'application/json' },\n });\n const payload = (await response.json().catch(() => null)) as\n | { data?: T; error?: string }\n | null;\n if (!response.ok) {\n throw new NotificationsHttpError(\n response.status,\n payload?.error ?? `HTTP ${response.status} for ${path}`,\n );\n }\n return (payload?.data ?? payload) as T;\n },\n\n async send<T>(path: string, method: string, body?: unknown): Promise<NotificationsResult<T>> {\n try {\n const response = await fetch(path, {\n method,\n credentials: 'same-origin',\n headers: {\n Accept: 'application/json',\n ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n if (response.status === 204) return { ok: true, data: undefined as T };\n const payload = (await response.json().catch(() => null)) as\n | { data?: T; error?: string }\n | null;\n if (!response.ok) return { ok: false, error: payload?.error ?? fallbackError };\n return { ok: true, data: (payload?.data ?? payload) as T };\n } catch {\n return { ok: false, error: fallbackError };\n }\n },\n };\n}\n","import { useState, type ComponentType, type JSX } from 'react';\n\nimport { messagesOf, type NotificationMessages } from '../messages';\n\nimport { createNotificationsApiClient, type NotificationsApiClient } from './api';\nimport { useInboxBellBadge, useLiveBellBadge, type BellBadge } from './bell-badge';\nimport { BellButton, LiveBellButton, type BellButtonProps } from './bell-button';\nimport {\n useUnreadCount,\n type NotificationsSignalHook,\n type NotificationsSubscribe,\n} from './hooks';\nimport { createInboxStore, type InboxStore } from './inbox-state';\nimport type { LiveActivitiesConfig } from './live-config';\nimport { createLiveSeenStore, type LiveSeenStore } from './live-seen';\nimport { lazyNotificationsPanel } from './panel-lazy';\nimport type { NotificationsPanelProps } from './panel';\nimport { lazyPreferencesPage } from './page-lazy';\nimport type { PreferencesScreenProps } from './preferences-screen';\nimport { httpNotificationsTransport, type NotificationsTransport } from './transport';\nimport type { WebPushSetupConfig } from './web-push-setup';\n\n/**\n * The one thing this package exposes to a FRONTEND host (12-15).\n *\n * Everything the notification centre IS — the bell with its live badge, the\n * slide-over inbox with its optimistic mark-read / delete / mark-all and its\n * cursor pager, the preferences matrix with its availability hints and the\n * per-browser push enable step, and every wire call between them — lives inside\n * this package. The host names where the API is mounted, and that is the whole\n * wiring.\n *\n * `page` is the standalone surface (the preferences screen), which is the one\n * thing a host routes to. The bell and the panel are a PAIR a host drops into\n * its own chrome, and they share one store, so a read in the panel moves the\n * badge in the same tick.\n */\n\nexport interface NotificationsWebConfig {\n /** The account mount the routes live under, e.g. `/api/account`. */\n apiBase: string;\n /** How the surface reaches its data. Default: same-origin fetch. */\n transport?: NotificationsTransport;\n /** User-facing copy overrides (pt-BR product copy by default). */\n messages: NotificationMessages;\n /**\n * How the surface learns an inbox changed without asking — the host's message\n * bus. Without it the badge keeps its 60 s poll, which is the standing\n * contract rather than a fallback: a dropped event must cost latency, never\n * correctness.\n */\n subscribe?: NotificationsSubscribe;\n /**\n * The same wiring as a HOOK, for a host whose realtime connection lives in\n * React context — see `NotificationsSignalHook`. `subscribe` is read at\n * factory time, which such a host cannot reach.\n */\n useSignal?: NotificationsSignalHook;\n /** The browser push enable step's host seams (SW path, platform hint). */\n webPush?: WebPushSetupConfig;\n /**\n * LIVE ACTIVITIES — the ongoing-state entries pinned above the inbox list.\n *\n * Opt-in, and absent means absent: a host that passes nothing gets the panel\n * it had, with no section, no heading and no reserved space. See\n * `./live-config` for the two things a host has to supply (where they come\n * from, and what the section says) and `../live` for what one IS.\n */\n liveActivities?: LiveActivitiesConfig;\n}\n\nexport interface WebNotifications {\n /**\n * The routed surface: the preferences screen.\n *\n * Loaded on demand — see `page-lazy.tsx`. A host that mounts only the bell and\n * the panel never downloads it, and a host that routes to it fetches it while\n * entering that route.\n */\n page: ComponentType<PreferencesScreenProps>;\n /** The bell, already bound to the shared store. */\n BellButton: ComponentType<BellButtonProps>;\n /**\n * The inbox slide-over, sharing that store.\n *\n * Loaded the first time it is opened — see `panel-lazy.tsx`. Until then a\n * host's chrome carries the bell and nothing else.\n */\n Panel: ComponentType<NotificationsPanelProps>;\n /**\n * Bell + panel as ONE element, for a host that just wants the feature in its\n * header and does not want to own the open/closed state.\n */\n BellWithPanel: ComponentType<{\n enabled?: boolean;\n onNavigate?: (link: string) => void;\n }>;\n /**\n * The unread INBOX count.\n *\n * For a host with its own trigger chrome only when that host configured no\n * live activities — otherwise it is a bell that ignores everything happening\n * right now, and `useBellBadge` below is the door. Still the right hook for\n * anything that genuinely wants \"how many unread rows\".\n */\n useUnreadCount: (options?: { enabled?: boolean }) => number;\n /**\n * The badge's NUMBER AND TONE, for a host with its own trigger chrome.\n *\n * What `useUnreadCount` should have been for a host that also configured live\n * activities, and the reason it is a second door rather than a change to that\n * one: a count alone cannot express a bell, because a live entry is present\n * without being news (see `./bell-badge`). A host that renders\n * `useUnreadCount` in its own chrome gets a badge that ignores everything\n * happening right now — which is not a subtle wrongness, it is the pinned\n * pedido on screen going uncounted.\n *\n * Identical to what this package's own `BellButton` draws, because it is the\n * hook that bell uses. Without live activities configured it is\n * `useUnreadCount` plus `hasNew: count > 0`.\n */\n useBellBadge: (options?: { enabled?: boolean }) => BellBadge;\n /** The shared client state, for host glue. */\n store: InboxStore;\n /** The bound wire client. */\n api: NotificationsApiClient;\n /** The copy in force, so a host's own chrome can reuse a sentence. */\n messages: NotificationMessages;\n}\n\n/** What the factory passes both badge hooks: whatever realtime wiring it has. */\ntype SubscribeOption = {\n subscribe?: NotificationsSubscribe;\n useSignal?: NotificationsSignalHook;\n};\n\n/**\n * The two badge hooks, bound to this factory's store.\n *\n * `useBellBadge` is chosen ONCE here, the same way `Bell` is below and for the\n * same reason: `live.useActivities` is a hook, so which implementation runs\n * must not be a per-render decision.\n */\nfunction bindBadgeHooks(\n store: InboxStore,\n subscribeOption: SubscribeOption,\n liveSeen: LiveSeenStore,\n live: LiveActivitiesConfig | undefined,\n): Pick<WebNotifications, 'useUnreadCount' | 'useBellBadge'> {\n return {\n useUnreadCount: (options = {}) => useUnreadCount(store, { ...options, ...subscribeOption }),\n useBellBadge: live\n ? (options = {}) => useLiveBellBadge(store, live, liveSeen, { ...options, ...subscribeOption })\n : (options = {}) => useInboxBellBadge(store, { ...options, ...subscribeOption }),\n };\n}\n\nexport function createWebNotifications(config: NotificationsWebConfig): WebNotifications {\n const messages = messagesOf(config);\n const api = createNotificationsApiClient(\n config.apiBase,\n config.transport ?? httpNotificationsTransport(messages.operationFailed),\n );\n const store = createInboxStore(api);\n const webPush = config.webPush ?? {};\n const subscribe = config.subscribe;\n const subscribeOption = {\n ...(subscribe ? { subscribe } : {}),\n ...(config.useSignal ? { useSignal: config.useSignal } : {}),\n };\n\n // One store per factory, shared by the bell that READS it and the panel that\n // WRITES it — the same arrangement as the inbox store above, and for the same\n // reason: two independent copies would disagree about what the reader saw.\n const liveSeen = createLiveSeenStore();\n\n // Chosen ONCE, here, because `useActivities` is a hook and the choice must\n // not be made per render: a bell that read an optional config inside itself\n // would be calling a hook conditionally.\n const live = config.liveActivities;\n const Bell: ComponentType<BellButtonProps> = live\n ? (props) => (\n <LiveBellButton\n {...props}\n store={store}\n messages={messages}\n live={live}\n seen={liveSeen}\n {...subscribeOption}\n />\n )\n : (props) => (\n <BellButton {...props} store={store} messages={messages} {...subscribeOption} />\n );\n const Panel = lazyNotificationsPanel({\n store,\n messages,\n ...(live ? { live, liveSeen } : {}),\n });\n\n const badgeHooks = bindBadgeHooks(store, subscribeOption, liveSeen, live);\n\n function BellWithPanel({\n enabled = true,\n onNavigate,\n }: {\n enabled?: boolean;\n onNavigate?: (link: string) => void;\n }): JSX.Element {\n const [open, setOpen] = useState(false);\n return (\n <>\n <Bell enabled={enabled} onClick={() => setOpen(true)} />\n <Panel\n open={open}\n onClose={() => setOpen(false)}\n {...(onNavigate ? { onNavigate } : {})}\n />\n </>\n );\n }\n\n return {\n page: lazyPreferencesPage({ api, messages, webPush }),\n BellButton: Bell,\n Panel,\n BellWithPanel,\n ...badgeHooks,\n store,\n api,\n messages,\n };\n}\n","/**\n * What the bell shows: ONE number, and whether any of it is news.\n *\n * The badge answers two different questions with one glyph, and keeping them\n * apart is the whole design:\n *\n * - the COUNT is how many things the centre is holding for the reader;\n * - the TONE is whether any of them has happened since they last looked.\n *\n * An inbox row makes those the same question — an unread row is by definition\n * both present and unseen — which is why the distinction did not exist before\n * live activities did. A live activity separates them: a pedido that has been\n * `Preparo` for ten minutes is still worth a `1`, and shouting about it every\n * render is how a badge teaches people to stop reading it.\n *\n * ## This is here so a host can DRAW it\n *\n * The numbers were already correct inside this package's own `BellButton`, and\n * unreachable from a host that cannot take that component — a header whose cart\n * and search buttons are one styled icon-button is importing a second trigger\n * style the moment it does. Such a host had `useUnreadCount` and nothing else,\n * so its bell showed NOTHING while a pinned pedido sat inside the panel it\n * opens. Both bells now read these hooks, so a host cannot drift from what this\n * package renders.\n *\n * ## What it does NOT yet do\n *\n * A live subject usually also writes inbox rows as it moves, and this counts\n * both: a pedido with one unread row about it reads `2`. Subtracting the double\n * needs the server to say which unread rows name which subject, and that was\n * built, reviewed and pulled — for reasons about the CONTRACT rather than the\n * arithmetic, and worth recording so the next attempt starts past them:\n *\n * - it added a field to `GET /notifications/unread-count`, and at least one\n * adopter publishes that response as a closed schema to LLM clients. An\n * additive field is a breaking change against `additionalProperties: false`.\n * - the scan is per READER, so every host paid it — including the two SPAs in\n * that adopter that share one factory and configure no live activities at\n * all, and read the count through `useUnreadCount`, which never sees the\n * breakdown.\n * - it narrowed `NotificationsApiClient.unreadCount()` from `Promise<number>`,\n * which is a breaking change on a commit the release rules cut as a minor.\n *\n * The way through is an opt-in the surface asks for — a host with no live\n * activities then sends nothing different and receives nothing different.\n *\n * (An earlier revision of this docblock blamed a missing index instead. That\n * was wrong: `[userId, deletedAt, readAt]` is a full equality prefix over the\n * filter, and the `ORDER BY` the scan carried was not load-bearing, since a\n * tally does not care what order it counts in.)\n */\nimport { useMemo, useSyncExternalStore } from 'react';\n\nimport { useBadgeState, type BadgeSyncOptions } from './hooks';\nimport type { InboxStore } from './inbox-state';\nimport type { LiveActivitiesConfig } from './live-config';\nimport { hasUnseenActivity, type LiveSeenStore } from './live-seen';\n\n/** The bell's whole state — see the file docblock for what each half means. */\nexport interface BellBadge {\n /** What the badge shows. `0` renders no badge at all. */\n count: number;\n /**\n * Whether any of it has arrived or moved since the reader last looked.\n *\n * The trigger paints this as its accent colour; a host with its own chrome\n * decides how to say it, but it should be a difference somebody notices.\n */\n hasNew: boolean;\n}\n\n/**\n * The badge for a host with no live activities: unread rows, and that is all.\n *\n * `hasNew` is `count > 0` here, and not as a simplification — an UNREAD row is\n * one the reader has not seen, so for this host presence and novelty really are\n * the same fact.\n */\nexport function useInboxBellBadge(store: InboxStore, options: BadgeSyncOptions = {}): BellBadge {\n // `useBadgeState` already blanks itself when disabled — the gate lives there,\n // once, rather than at each of the three hooks that layer on it.\n const { unread } = useBadgeState(store, options);\n // MEMOISED, unlike the number `useUnreadCount` returns. `useSyncExternalStore`\n // re-renders on every `patch` and `patch` always allocates, so a poll that\n // comes back with an unchanged count would otherwise hand a host a new object\n // every 60 s — enough to re-fire a `useEffect` keyed on it, or defeat a\n // `React.memo` on the trigger, forever.\n return useMemo(() => ({ count: unread, hasNew: unread > 0 }), [unread]);\n}\n\n/**\n * The badge for a host that configured live activities.\n *\n * A SECOND hook rather than a flag on the one above, for the reason the bell\n * itself is two components: `live.useActivities` is a hook, so a single hook\n * reading an optional config would be calling one conditionally — which React\n * reports as a crash somewhere else entirely. The factory knows statically\n * which host it is building for and binds one.\n *\n * ## `enabled` is enforced HERE, not taken on trust\n *\n * A host is explicitly allowed to ignore the `active` hint and always answer —\n * `./live-config` calls that \"behaving correctly and merely paying for it\" — so\n * a signed-out header, which still MOUNTS the bell, can be handed a list of\n * somebody's pedidos. The guard below is the only thing between that and a\n * badge counting them.\n *\n * Defensive against the CONTRACT, not against an observed adopter: today's one\n * honours the hint on every lever it has. That is exactly why the guard needs\n * saying — nothing about the current tree would fail if it went, and the case\n * that covers it has to build the ignoring host itself.\n *\n * ## What it costs the host, stated plainly\n *\n * The bell is mounted for as long as the app is, so unlike the panel's copy of\n * this hook there is no \"nobody is looking\" state to stand down in — `active`\n * is simply `enabled`. A host that answers by polling therefore polls for every\n * signed-in reader whether or not they ever open the centre. That is the price\n * of a badge that knows about live activities at all, and the reason to answer\n * this hook from a pushed cache rather than from an interval.\n */\nexport function useLiveBellBadge(\n store: InboxStore,\n live: LiveActivitiesConfig,\n seen: LiveSeenStore,\n options: BadgeSyncOptions = {},\n): BellBadge {\n const enabled = options.enabled ?? true;\n const { unread } = useBadgeState(store, options);\n const activities = live.useActivities({ active: enabled });\n const seenAt = useSyncExternalStore(seen.subscribe, seen.read, seen.read);\n // The store's own half is already blanked by `useBadgeState`; the `enabled`\n // guard here is for the ACTIVITIES half, which comes from a host hook that\n // may have ignored the hint.\n //\n // A live entry COUNTS. It is a notification — it is the one the reader most\n // wants to know about — and the panel it opens lists it.\n const count = enabled ? unread + activities.length : 0;\n const hasNew = enabled && (unread > 0 || hasUnseenActivity(activities, seenAt));\n // Memoised on the two RESULTS, not on `activities`. A host's hook returns a\n // fresh array every render — the storefront's maps its query's rows, so\n // structural sharing keeps the DATA identical and the array new — so an\n // `activities` dependency would invalidate on every render and the memo would\n // buy nothing at all. `hasUnseenActivity` runs unmemoised in front of it,\n // which is a `.some()` over the handful of things happening at once.\n return useMemo(() => ({ count, hasNew }), [count, hasNew]);\n}\n","/**\n * What the reader has already been shown, so the bell can say NEW rather than\n * merely PRESENT.\n *\n * A live activity is unlike an inbox row in the one way that matters here: it\n * stays on the panel for as long as the thing is happening, so its presence\n * cannot mean \"you have not seen this\". A pedido that has been `Preparo` for\n * ten minutes is still live and still worth counting, but nothing has happened\n * — and a badge that shouts for a subject the reader has already looked at is a\n * badge people stop reading.\n *\n * So presence and novelty are answered separately: the COUNT comes from how\n * many are live, and the TONE comes from this. The panel writes it — being on\n * screen is what seen means — and the bell reads it.\n *\n * ## Per subject, not one watermark\n *\n * A single \"newest instant already seen\" is smaller and was the first cut, and\n * it is wrong in a way that shows up in normal use: a pedido placed ten minutes\n * ago but only now reaching the client arrives with an `updatedAt` BEHIND the\n * watermark, and would be silently marked as already seen. The reader has never\n * laid eyes on it. Keyed by subject, an id that has not been recorded is new\n * whatever its clock says.\n *\n * Bounded by pruning rather than by expiry: every write keeps only the subjects\n * that are live at that moment, so the record can never outgrow the number of\n * things happening at once. A subject that finishes and later comes back is\n * news again, which is correct — it is a different occurrence.\n */\nimport type { LiveActivity } from '../live';\n\nconst STORAGE_KEY = '12a.notifications.live-seen';\n\n/** id -> the `updatedAt` that was on screen. */\ntype SeenMap = Readonly<Record<string, string>>;\n\nconst EMPTY: SeenMap = {};\n\n/** ms since epoch, or `null` for an absent or unparseable stamp. */\nfunction instant(iso: string | undefined): number | null {\n if (iso === undefined) return null;\n const ms = Date.parse(iso);\n return Number.isNaN(ms) ? null : ms;\n}\n\n/**\n * Read/write through `try`, every time.\n *\n * `localStorage` is not merely absent in SSR and in a worker — the ACCESSOR\n * itself throws in a browser set to block site data. A notification bell that\n * cannot render because storage is blocked is a worse failure than one that\n * forgets what was seen, and forgetting degrades in the safe direction: towards\n * saying something is happening.\n */\nfunction readStored(): SeenMap {\n try {\n const raw = globalThis.localStorage?.getItem(STORAGE_KEY);\n if (!raw) return EMPTY;\n const parsed: unknown = JSON.parse(raw);\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return EMPTY;\n // Anything can be in storage — another version of this package, or a person\n // with the devtools open. Keep only what has the shape this reads.\n const clean: Record<string, string> = {};\n for (const [id, value] of Object.entries(parsed)) {\n if (typeof value === 'string') clean[id] = value;\n }\n return clean;\n } catch {\n return EMPTY;\n }\n}\n\nfunction writeStored(value: SeenMap): void {\n try {\n globalThis.localStorage?.setItem(STORAGE_KEY, JSON.stringify(value));\n } catch {\n // Blocked or full. The badge stays new a while longer; nothing else breaks.\n }\n}\n\nexport interface LiveSeenStore {\n /** What has been shown, keyed by subject id. */\n read: () => SeenMap;\n /** Record that exactly these are on screen now, forgetting subjects that are not. */\n mark: (activities: readonly LiveActivity[]) => void;\n subscribe: (listener: () => void) => () => void;\n}\n\nexport function createLiveSeenStore(): LiveSeenStore {\n // Mirrored in memory as well as in storage: `useSyncExternalStore` compares\n // snapshots by IDENTITY and calls `read` on every render, so parsing storage\n // there would hand it a fresh object each time and re-render for ever.\n let current = readStored();\n const listeners = new Set<() => void>();\n\n return {\n read: () => current,\n mark: (activities) => {\n const next: Record<string, string> = {};\n for (const activity of activities) next[activity.id] = activity.updatedAt;\n // Identity is the snapshot, so an unchanged map must not become a new\n // object — see `read` above.\n const ids = Object.keys(next);\n const same =\n ids.length === Object.keys(current).length &&\n ids.every((id) => current[id] === next[id]);\n if (same) return;\n current = next;\n writeStored(next);\n for (const listener of listeners) listener();\n },\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n\n/**\n * Whether any of these has moved, or arrived, since the reader last looked.\n *\n * An id with nothing recorded is new — that is the case the per-subject record\n * exists for. An unparseable stamp is treated as new too: the alternative is\n * silently never alerting for a host whose clock format this does not read.\n */\nexport function hasUnseenActivity(\n activities: readonly LiveActivity[],\n seen: SeenMap,\n): boolean {\n return activities.some((activity) => {\n const shown = instant(seen[activity.id]);\n if (shown === null) return true;\n const now = instant(activity.updatedAt);\n return now === null || now > shown;\n });\n}\n","/**\n * Bare bell trigger with the live unread badge — for hosts that do not already\n * have a styled icon-button slot.\n *\n * A host with its own trigger chrome uses `useBellBadge` + `Panel` directly,\n * and NOT `useUnreadCount`, which is what this sentence used to say. That\n * advice was taken, verbatim and by name, by a storefront whose header needed\n * its own trigger — and it gave that storefront a bell showing nothing at all\n * while a live pedido sat in the panel it opens, because `useUnreadCount`\n * counts inbox rows and knows nothing about what is happening right now.\n */\nimport type { JSX } from 'react';\n\nimport { Badge } from '@12-apps/ui/data-display/Badge';\nimport { Box } from '@12-apps/ui/mui/Box';\n\nimport type { NotificationMessages } from '../messages';\n\nimport { useInboxBellBadge, useLiveBellBadge } from './bell-badge';\nimport { BellIcon } from './bell-icon';\nimport type { NotificationsSignalHook, NotificationsSubscribe } from './hooks';\nimport type { LiveActivitiesConfig } from './live-config';\nimport type { LiveSeenStore } from './live-seen';\nimport type { InboxStore } from './inbox-state';\n\nconst triggerSx = {\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n p: 0.5,\n border: 'none',\n background: 'none',\n cursor: 'pointer',\n color: 'text.primary',\n lineHeight: 0,\n '& *': { cursor: 'pointer' },\n '&:hover': { color: 'primary.main' },\n '&:focus-visible': {\n outline: '2px solid',\n outlineColor: 'primary.main',\n outlineOffset: '2px',\n borderRadius: '50%',\n },\n} as const;\n\nexport interface BellButtonProps {\n onClick: () => void;\n /** Signed-out hosts still mount the bell; `false` silences it. */\n enabled?: boolean;\n}\n\n/**\n * The trigger itself, given a count and whether any of it is NEW.\n *\n * Presentational, and shared by both bells below, so the two can never drift on\n * what the badge looks like — only on where the number comes from.\n *\n * ## The two tones\n *\n * `primary` says *something happened*; `neutral` says *something is present*. A\n * live activity is the reason that distinction has to exist: it stays on the\n * panel for as long as the thing is happening, so a bell that painted every\n * live entry as new would be permanently red for a pedido the reader already\n * looked at, and a bell that ignored them would say nothing at all while one\n * was running. Grey keeps the count honest without spending attention twice.\n */\nfunction BellTrigger({\n onClick,\n count,\n hasNew,\n messages,\n}: {\n onClick: () => void;\n count: number;\n hasNew: boolean;\n messages: NotificationMessages;\n}): JSX.Element {\n return (\n <Box\n component=\"button\"\n type=\"button\"\n onClick={onClick}\n // `openBellWithUnread` rather than a new message, and not for want of\n // precision: `NotificationMessages` is REQUIRED of every host, so adding\n // a field is a breaking change to a package several apps already mount.\n // The sentence a host wrote for \"you have N\" is the sentence this wants.\n aria-label={count > 0 ? messages.openBellWithUnread(count) : messages.openBell}\n data-testid=\"notifications-bell\"\n sx={triggerSx}\n >\n <Badge\n content={count > 0 ? count : undefined}\n color={hasNew ? 'primary' : 'neutral'}\n variant=\"count\"\n max={99}\n data-testid=\"notifications-badge\"\n // The tone is carried by a colour, and a colour is not something a\n // test can read — nor, on its own, a signal every reader can. This is\n // what the tests assert on.\n data-tone={hasNew ? 'new' : 'seen'}\n >\n <BellIcon size={28} />\n </Badge>\n </Box>\n );\n}\n\nexport function BellButton({\n onClick,\n enabled = true,\n store,\n messages,\n subscribe,\n useSignal,\n}: BellButtonProps & {\n store: InboxStore;\n messages: NotificationMessages;\n subscribe?: NotificationsSubscribe;\n useSignal?: NotificationsSignalHook;\n}): JSX.Element {\n const badge = useInboxBellBadge(store, {\n enabled,\n ...(subscribe ? { subscribe } : {}),\n ...(useSignal ? { useSignal } : {}),\n });\n return <BellTrigger onClick={onClick} {...badge} messages={messages} />;\n}\n\n/**\n * The bell for a host that configured live activities.\n *\n * A SECOND component rather than a flag on the one above, because the host's\n * `useActivities` is a hook: reading an optional config inside one component\n * would mean calling it conditionally, which React reports as a crash in some\n * unrelated component rather than here. The factory knows statically which host\n * it is building for and picks one.\n *\n * What the number MEANS, and what it costs the host, is `bell-badge.ts` — the\n * same hook a host with its own trigger chrome reaches through the factory's\n * `useBellBadge`, so the two bells can never disagree about the count.\n */\nexport function LiveBellButton({\n onClick,\n enabled = true,\n store,\n messages,\n subscribe,\n useSignal,\n live,\n seen,\n}: BellButtonProps & {\n store: InboxStore;\n messages: NotificationMessages;\n subscribe?: NotificationsSubscribe;\n useSignal?: NotificationsSignalHook;\n live: LiveActivitiesConfig;\n seen: LiveSeenStore;\n}): JSX.Element {\n const badge = useLiveBellBadge(store, live, seen, {\n enabled,\n ...(subscribe ? { subscribe } : {}),\n ...(useSignal ? { useSignal } : {}),\n });\n return <BellTrigger onClick={onClick} {...badge} messages={messages} />;\n}\n","/**\n * The inbox slide-over, fetched the first time somebody opens it.\n *\n * The bell and the panel are a PAIR a host drops into its chrome, and that is\n * still true — but only the BELL is on screen when a page paints. The panel is\n * behind a tap, and a static import made every host pay for it up front: the\n * design-system `Drawer` and, through it, MUI's `SwipeableDrawer`, `Modal`,\n * `Slide` and the focus trap, plus the row, the empty state and the pager. On a\n * storefront that is a slide-over most visits never open, parsed before the\n * first screen can render.\n *\n * ## Why the gate is \"ever opened\" rather than `open`\n *\n * `lazy` fetches when a component first RENDERS, so a boundary that still\n * rendered the panel while closed would fetch immediately and buy nothing. This\n * renders `null` until the panel has been open once, which is what actually\n * defers the download to the tap.\n *\n * And once opened it STAYS mounted. Unmounting on close would throw away the\n * drawer's transition state, so the panel would vanish instead of sliding out,\n * and the entrance animation would re-run on every reopen — which someone\n * working through an inbox does repeatedly. The fetch happens once.\n *\n * The initial state reads `open` rather than starting at `false`, so a host that\n * mounts the panel already open renders it in the same commit instead of a frame\n * later.\n *\n * ## Why `null` for the fallback\n *\n * The only frame this can show anything is the one right after the tap, where a\n * spinner reads as a stall rather than as progress. The chunk is small and\n * same-origin.\n */\nimport { Suspense, lazy, useEffect, useState, type ComponentType, type JSX } from 'react';\n\nimport type { NotificationMessages } from '../messages';\n\nimport type { InboxStore } from './inbox-state';\nimport type { LiveActivitiesConfig } from './live-config';\nimport type { LiveSeenStore } from './live-seen';\nimport type { NotificationsPanelProps } from './panel';\n\n/** What the factory binds into the panel, and the host never passes. */\ninterface PanelParts {\n store: InboxStore;\n messages: NotificationMessages;\n /** Absent unless the host turned live activities on — see `./live-config`. */\n live?: LiveActivitiesConfig;\n /** Travels with `live`: where the panel records what the reader has seen. */\n liveSeen?: LiveSeenStore;\n}\n\nexport function lazyNotificationsPanel(\n parts: PanelParts,\n): ComponentType<NotificationsPanelProps> {\n const Bound = lazy(async () => {\n const { NotificationsPanel } = await import('./panel');\n return {\n default: (props: NotificationsPanelProps): JSX.Element => (\n <NotificationsPanel {...props} {...parts} />\n ),\n };\n });\n\n return function NotificationsPanelSlot(props: NotificationsPanelProps): JSX.Element | null {\n const [everOpened, setEverOpened] = useState(props.open);\n\n useEffect(() => {\n if (props.open) setEverOpened(true);\n }, [props.open]);\n\n if (!everOpened) return null;\n\n return (\n <Suspense fallback={null}>\n <Bound {...props} />\n </Suspense>\n );\n };\n}\n","/**\n * The routed preferences screen, fetched when a host actually routes to it.\n *\n * `createWebNotifications` returns two different KINDS of thing, and its own\n * docstring says so: `page` is \"the standalone surface … the one thing a host\n * routes to\", while the bell and the panel \"are a PAIR a host drops into its own\n * chrome\". Chrome is on screen from the first paint; a routed surface is not.\n *\n * A static import made that distinction invisible to a bundler. Every host that\n * put the bell in its header also shipped the preferences matrix — its channel\n * toggles, the per-browser push enable step, and the design-system `Switch`\n * behind them — in the same chunk as the header. A storefront paid for a\n * settings screen a shopper never opens, before its first screen could render;\n * a host that renders its OWN preferences page paid for this one twice.\n *\n * So `page` now loads on demand. Nothing else moves: the bell, the panel and\n * `BellWithPanel` stay exactly as eager as the chrome they belong to, because\n * that is what they are.\n *\n * NO PREFETCH, deliberately, and this is the opposite call from a surface a\n * host opens from chrome it already has. A routed surface is reached by\n * NAVIGATION, and every host here already code-splits its routes — so the\n * fetch happens while the route is being entered, which is the moment a\n * prefetch would have been trying to anticipate. Warming it at factory time\n * would put the screen back on the boot path of every app, which is the whole\n * cost this removes.\n */\nimport { Suspense, lazy, type ComponentType, type JSX } from 'react';\n\nimport type { NotificationMessages } from '../messages';\n\nimport type { NotificationsApiClient } from './api';\nimport type { PreferencesScreenProps } from './preferences-screen';\nimport type { WebPushSetupConfig } from './web-push-setup';\n\n/** What the factory binds into the screen, and the host never passes. */\ninterface PreferencesPageParts {\n api: NotificationsApiClient;\n messages: NotificationMessages;\n webPush: WebPushSetupConfig;\n}\n\n/**\n * The routed screen, bound and loaded on first render.\n *\n * `lazy` memoises its factory, so the binding below happens once however many\n * times a host mounts the page — the same guarantee the direct call gave.\n *\n * The fallback is `null` because a host routes to this: whatever it renders\n * around the route is already on screen, and a second spinner inside it would\n * be one more thing appearing and disappearing during a navigation the host is\n * already indicating.\n */\nexport function lazyPreferencesPage(\n parts: PreferencesPageParts,\n): ComponentType<PreferencesScreenProps> {\n const Bound = lazy(async () => {\n const { PreferencesScreen } = await import('./preferences-screen');\n return {\n default: (props: PreferencesScreenProps): JSX.Element => (\n <PreferencesScreen {...props} {...parts} />\n ),\n };\n });\n\n return function NotificationsPreferencesPage(props: PreferencesScreenProps): JSX.Element {\n return (\n <Suspense fallback={null}>\n <Bound {...props} />\n </Suspense>\n );\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAiEO,SAAS,6BACd,SACA,WACwB;AACxB,QAAM,OAAO,QAAQ,QAAQ,OAAO,EAAE;AACtC,QAAM,MAAM,wBAAC,SAAyB,GAAG,IAAI,GAAG,IAAI,IAAxC;AAEZ,SAAO;AAAA,IACL,kBAAkB,EAAE,QAAQ,OAAO,OAAO,GAAG;AAC3C,YAAM,SAAS,IAAI,gBAAgB;AACnC,UAAI,UAAU,OAAW,QAAO,IAAI,SAAS,OAAO,KAAK,CAAC;AAC1D,UAAI,OAAQ,QAAO,IAAI,UAAU,MAAM;AACvC,UAAI,OAAQ,QAAO,IAAI,UAAU,MAAM;AACvC,YAAM,QAAQ,OAAO,SAAS;AAC9B,aAAO,UAAU;AAAA,QACf,IAAI,iBAAiB,QAAQ,IAAI,KAAK,KAAK,EAAE,EAAE;AAAA,MACjD;AAAA,IACF;AAAA,IACA,MAAM,cAAc;AAClB,YAAM,EAAE,MAAM,IAAI,MAAM,UAAU;AAAA,QAChC,IAAI,6BAA6B;AAAA,MACnC;AACA,aAAO;AAAA,IACT;AAAA,IACA,UAAU,wBAAC,QACT,UAAU,KAAK,IAAI,0BAA0B,GAAG,QAAQ,EAAE,KAAK,CAAC,GAAG,GAAG,EAAE,CAAC,GADjE;AAAA,IAEV,aAAa,6B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