@rpcbase/server 0.562.0 → 0.564.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/{handler-VRU-2kj6.js → handler-BTtU7fJq.js} +211 -1
- package/dist/handler-BTtU7fJq.js.map +1 -0
- package/dist/notifications/api/notifications/handler.d.ts.map +1 -1
- package/dist/notifications/api/notifications/index.d.ts +25 -0
- package/dist/notifications/api/notifications/index.d.ts.map +1 -1
- package/dist/notifications/createNotification.d.ts +5 -0
- package/dist/notifications/createNotification.d.ts.map +1 -1
- package/dist/notifications/digest.d.ts.map +1 -1
- package/dist/notifications.js +79 -8
- package/dist/notifications.js.map +1 -1
- package/package.json +1 -1
- package/dist/handler-VRU-2kj6.js.map +0 -1
|
@@ -22,6 +22,7 @@ const getSessionUser = (ctx) => {
|
|
|
22
22
|
const ListRoute = "/api/rb/notifications";
|
|
23
23
|
const CreateRoute = "/api/rb/notifications/create";
|
|
24
24
|
const MarkReadRoute = "/api/rb/notifications/:notificationId/read";
|
|
25
|
+
const MarkReadByUrlRoute = "/api/rb/notifications/mark-read-by-url";
|
|
25
26
|
const ArchiveRoute = "/api/rb/notifications/:notificationId/archive";
|
|
26
27
|
const MarkAllReadRoute = "/api/rb/notifications/mark-all-read";
|
|
27
28
|
const SettingsRoute = "/api/rb/notifications/settings";
|
|
@@ -40,6 +41,7 @@ const notificationPlatformPayloadSchema = object({
|
|
|
40
41
|
apns: record(string(), unknown()).optional()
|
|
41
42
|
}).passthrough();
|
|
42
43
|
const createRequestStringSchema = string().trim();
|
|
44
|
+
const notificationUrlModeSchema = _enum(["navigate", "merge_current_search"]);
|
|
43
45
|
const notificationContentFieldsSchema = object({
|
|
44
46
|
title: string().min(1),
|
|
45
47
|
body: string().optional(),
|
|
@@ -50,9 +52,37 @@ const createRequestSchema = object({
|
|
|
50
52
|
title: createRequestStringSchema.min(1),
|
|
51
53
|
body: createRequestStringSchema.optional(),
|
|
52
54
|
image: createRequestStringSchema.optional(),
|
|
55
|
+
url: createRequestStringSchema.min(1).optional(),
|
|
56
|
+
urlMode: notificationUrlModeSchema.optional(),
|
|
57
|
+
metadata: record(string(), unknown()).optional(),
|
|
53
58
|
data: notificationDataSchema.optional(),
|
|
54
59
|
platform: notificationPlatformPayloadSchema.optional()
|
|
55
60
|
});
|
|
61
|
+
const normalizeNotificationActionUrl = (url, origin) => {
|
|
62
|
+
const raw = url.trim();
|
|
63
|
+
if (!raw) return null;
|
|
64
|
+
try {
|
|
65
|
+
const base = new URL(origin);
|
|
66
|
+
const parsed = new URL(raw, base);
|
|
67
|
+
if (parsed.origin !== base.origin) return null;
|
|
68
|
+
return `${parsed.pathname}${parsed.search}`;
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
const normalizeNotificationActionLink = (url, origin, urlMode = "navigate") => {
|
|
74
|
+
const raw = url.trim();
|
|
75
|
+
if (!raw) return null;
|
|
76
|
+
try {
|
|
77
|
+
const base = new URL(origin);
|
|
78
|
+
const parsed = new URL(raw, base);
|
|
79
|
+
if (parsed.origin !== base.origin) return null;
|
|
80
|
+
if (urlMode === "navigate") return `${parsed.pathname}${parsed.search}${parsed.hash}`;
|
|
81
|
+
return `${parsed.search}${parsed.hash}` || null;
|
|
82
|
+
} catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
56
86
|
const notificationSchema = object({
|
|
57
87
|
id: string(),
|
|
58
88
|
topic: string().optional(),
|
|
@@ -82,6 +112,15 @@ object({
|
|
|
82
112
|
ok: boolean(),
|
|
83
113
|
error: string().optional()
|
|
84
114
|
});
|
|
115
|
+
const markReadByUrlRequestSchema = object({
|
|
116
|
+
url: string().trim().min(1)
|
|
117
|
+
});
|
|
118
|
+
const markReadByUrlResponseSchema = object({
|
|
119
|
+
ok: boolean(),
|
|
120
|
+
error: string().optional(),
|
|
121
|
+
matchedCount: number().int().min(0).optional(),
|
|
122
|
+
modifiedCount: number().int().min(0).optional()
|
|
123
|
+
});
|
|
85
124
|
object({
|
|
86
125
|
ok: boolean(),
|
|
87
126
|
error: string().optional()
|
|
@@ -132,6 +171,58 @@ const toStringMap = (value) => {
|
|
|
132
171
|
const entries = Object.entries(value).filter((entry) => typeof entry[1] === "string");
|
|
133
172
|
return entries.length > 0 ? Object.fromEntries(entries) : void 0;
|
|
134
173
|
};
|
|
174
|
+
const getForwardedHeaderValue = (value) => {
|
|
175
|
+
const raw = Array.isArray(value) ? value[0] : value;
|
|
176
|
+
if (typeof raw !== "string") return void 0;
|
|
177
|
+
return raw.split(",")[0]?.trim() || void 0;
|
|
178
|
+
};
|
|
179
|
+
const getRequestOrigin = (ctx) => {
|
|
180
|
+
const protocol = getForwardedHeaderValue(ctx.req.headers["x-forwarded-proto"]) ?? ctx.req.protocol;
|
|
181
|
+
const host = getForwardedHeaderValue(ctx.req.headers["x-forwarded-host"]) ?? ctx.req.get("host");
|
|
182
|
+
return protocol && host ? `${protocol}://${host}` : "";
|
|
183
|
+
};
|
|
184
|
+
const getNotificationActionLinks = (notification) => {
|
|
185
|
+
const links = [];
|
|
186
|
+
if (typeof notification.data?.link === "string") {
|
|
187
|
+
links.push({
|
|
188
|
+
link: notification.data.link,
|
|
189
|
+
urlMode: notification.data.linkMode === "merge_current_search" ? "merge_current_search" : "navigate"
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
const platformWebpush = notification.platform?.webpush;
|
|
193
|
+
if (platformWebpush && typeof platformWebpush === "object" && !Array.isArray(platformWebpush)) {
|
|
194
|
+
const fcmOptions = platformWebpush.fcmOptions;
|
|
195
|
+
if (fcmOptions && typeof fcmOptions === "object" && !Array.isArray(fcmOptions)) {
|
|
196
|
+
const link = fcmOptions.link;
|
|
197
|
+
if (typeof link === "string") {
|
|
198
|
+
links.push({
|
|
199
|
+
link,
|
|
200
|
+
urlMode: "navigate"
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return links;
|
|
206
|
+
};
|
|
207
|
+
const actionSearchParamsMatchTargetUrl = (actionUrl, targetUrl, origin) => {
|
|
208
|
+
try {
|
|
209
|
+
const base = new URL(origin);
|
|
210
|
+
const action = new URL(actionUrl, base);
|
|
211
|
+
const target = new URL(targetUrl, base);
|
|
212
|
+
for (const [key, value] of action.searchParams) {
|
|
213
|
+
if (target.searchParams.get(key) !== value) return false;
|
|
214
|
+
}
|
|
215
|
+
return Array.from(action.searchParams.keys()).length > 0;
|
|
216
|
+
} catch {
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
const notificationActionLinkMatchesUrl = (action, targetUrl, origin) => {
|
|
221
|
+
if (action.urlMode === "merge_current_search") {
|
|
222
|
+
return actionSearchParamsMatchTargetUrl(action.link, targetUrl, origin);
|
|
223
|
+
}
|
|
224
|
+
return normalizeNotificationActionUrl(action.link, origin) === targetUrl;
|
|
225
|
+
};
|
|
135
226
|
const buildDisabledTopics = (settings, key) => {
|
|
136
227
|
const raw = settings?.topicPreferences;
|
|
137
228
|
if (!Array.isArray(raw) || raw.length === 0) return [];
|
|
@@ -306,12 +397,24 @@ const createNotificationForCurrentUser = async (payload, ctx) => {
|
|
|
306
397
|
error: "invalid_payload"
|
|
307
398
|
};
|
|
308
399
|
}
|
|
400
|
+
const origin = getRequestOrigin(ctx);
|
|
401
|
+
const actionLink = parsed.data.url ? normalizeNotificationActionLink(parsed.data.url, origin, parsed.data.urlMode) ?? void 0 : void 0;
|
|
402
|
+
if (parsed.data.url && !actionLink) {
|
|
403
|
+
ctx.res.status(400);
|
|
404
|
+
return {
|
|
405
|
+
ok: false,
|
|
406
|
+
error: "invalid_payload"
|
|
407
|
+
};
|
|
408
|
+
}
|
|
309
409
|
const created = await createNotification(ctx, {
|
|
310
410
|
userId: session.userId,
|
|
311
411
|
topic: parsed.data.topic,
|
|
312
412
|
title: parsed.data.title,
|
|
313
413
|
body: parsed.data.body,
|
|
314
414
|
image: parsed.data.image,
|
|
415
|
+
url: actionLink,
|
|
416
|
+
urlMode: parsed.data.urlMode,
|
|
417
|
+
metadata: parsed.data.metadata,
|
|
315
418
|
data: parsed.data.data,
|
|
316
419
|
platform: parsed.data.platform
|
|
317
420
|
}, ability);
|
|
@@ -378,6 +481,112 @@ const markRead = async (_payload, ctx) => {
|
|
|
378
481
|
ok: true
|
|
379
482
|
};
|
|
380
483
|
};
|
|
484
|
+
const markReadByUrl = async (payload, ctx) => {
|
|
485
|
+
const session = getSessionUser(ctx);
|
|
486
|
+
if (!session) {
|
|
487
|
+
return {
|
|
488
|
+
ok: false,
|
|
489
|
+
error: "unauthorized"
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
const ability = buildAbilityFromSession({
|
|
493
|
+
tenantId: session.tenantId,
|
|
494
|
+
session: ctx.req.session
|
|
495
|
+
});
|
|
496
|
+
if (!ability.can("update", "RBNotification")) {
|
|
497
|
+
ctx.res.status(403);
|
|
498
|
+
return {
|
|
499
|
+
ok: false,
|
|
500
|
+
error: "forbidden"
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
const parsed = markReadByUrlRequestSchema.safeParse(payload);
|
|
504
|
+
if (!parsed.success) {
|
|
505
|
+
ctx.res.status(400);
|
|
506
|
+
return {
|
|
507
|
+
ok: false,
|
|
508
|
+
error: "invalid_payload"
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
const origin = getRequestOrigin(ctx);
|
|
512
|
+
const targetUrl = normalizeNotificationActionUrl(parsed.data.url, origin);
|
|
513
|
+
if (!targetUrl) {
|
|
514
|
+
ctx.res.status(400);
|
|
515
|
+
return {
|
|
516
|
+
ok: false,
|
|
517
|
+
error: "invalid_payload"
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
const NotificationModel = await models.get("RBNotification", {
|
|
521
|
+
req: ctx.req,
|
|
522
|
+
ability
|
|
523
|
+
});
|
|
524
|
+
const query = {
|
|
525
|
+
$and: [{
|
|
526
|
+
userId: session.userId
|
|
527
|
+
}, {
|
|
528
|
+
archivedAt: {
|
|
529
|
+
$exists: false
|
|
530
|
+
}
|
|
531
|
+
}, {
|
|
532
|
+
readAt: {
|
|
533
|
+
$exists: false
|
|
534
|
+
}
|
|
535
|
+
}, {
|
|
536
|
+
$or: [{
|
|
537
|
+
"data.link": {
|
|
538
|
+
$type: "string"
|
|
539
|
+
}
|
|
540
|
+
}, {
|
|
541
|
+
"platform.webpush.fcmOptions.link": {
|
|
542
|
+
$type: "string"
|
|
543
|
+
}
|
|
544
|
+
}]
|
|
545
|
+
}, getAccessibleByQuery(ability, "update", "RBNotification")]
|
|
546
|
+
};
|
|
547
|
+
const candidates = await NotificationModel.find(query).select({
|
|
548
|
+
_id: 1,
|
|
549
|
+
data: 1,
|
|
550
|
+
platform: 1
|
|
551
|
+
}).lean();
|
|
552
|
+
const matchingIds = candidates.filter((notification) => getNotificationActionLinks(notification).some((action) => notificationActionLinkMatchesUrl(action, targetUrl, origin))).map((notification) => notification._id);
|
|
553
|
+
if (matchingIds.length === 0) {
|
|
554
|
+
return markReadByUrlResponseSchema.parse({
|
|
555
|
+
ok: true,
|
|
556
|
+
matchedCount: 0,
|
|
557
|
+
modifiedCount: 0
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
const now = /* @__PURE__ */ new Date();
|
|
561
|
+
const result = await NotificationModel.updateMany({
|
|
562
|
+
$and: [{
|
|
563
|
+
_id: {
|
|
564
|
+
$in: matchingIds
|
|
565
|
+
}
|
|
566
|
+
}, {
|
|
567
|
+
userId: session.userId
|
|
568
|
+
}, {
|
|
569
|
+
archivedAt: {
|
|
570
|
+
$exists: false
|
|
571
|
+
}
|
|
572
|
+
}, {
|
|
573
|
+
readAt: {
|
|
574
|
+
$exists: false
|
|
575
|
+
}
|
|
576
|
+
}, getAccessibleByQuery(ability, "update", "RBNotification")]
|
|
577
|
+
}, {
|
|
578
|
+
$set: {
|
|
579
|
+
readAt: now,
|
|
580
|
+
seenAt: now
|
|
581
|
+
}
|
|
582
|
+
});
|
|
583
|
+
const modifiedCount = typeof result.modifiedCount === "number" ? result.modifiedCount : matchingIds.length;
|
|
584
|
+
return markReadByUrlResponseSchema.parse({
|
|
585
|
+
ok: true,
|
|
586
|
+
matchedCount: matchingIds.length,
|
|
587
|
+
modifiedCount
|
|
588
|
+
});
|
|
589
|
+
};
|
|
381
590
|
const markAllRead = async (_payload, ctx) => {
|
|
382
591
|
const session = getSessionUser(ctx);
|
|
383
592
|
if (!session) {
|
|
@@ -674,6 +883,7 @@ const handler = (api) => {
|
|
|
674
883
|
api.post(ListRoute, listNotifications);
|
|
675
884
|
api.post(CreateRoute, createNotificationForCurrentUser);
|
|
676
885
|
api.post(MarkReadRoute, markRead);
|
|
886
|
+
api.post(MarkReadByUrlRoute, markReadByUrl);
|
|
677
887
|
api.post(MarkAllReadRoute, markAllRead);
|
|
678
888
|
api.post(ArchiveRoute, archiveNotification);
|
|
679
889
|
api.get(SettingsRoute, getSettings);
|
|
@@ -683,4 +893,4 @@ const handler = (api) => {
|
|
|
683
893
|
export {
|
|
684
894
|
handler as default
|
|
685
895
|
};
|
|
686
|
-
//# sourceMappingURL=handler-
|
|
896
|
+
//# sourceMappingURL=handler-BTtU7fJq.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handler-BTtU7fJq.js","sources":["../src/notifications/api/notifications/shared.ts","../src/notifications/api/notifications/index.ts","../src/notifications/api/notifications/handler.ts"],"sourcesContent":["import type { Ctx } from \"@rpcbase/api\"\n\n\ntype NotificationSessionUser = {\n id?: unknown\n currentTenantId?: unknown\n}\n\nexport const getSessionUser = (ctx: Ctx) => {\n const rawSessionUser = (ctx.req.session as { user?: NotificationSessionUser } | null | undefined)?.user\n const userId = typeof rawSessionUser?.id === \"string\" ? rawSessionUser.id.trim() : \"\"\n const tenantId = typeof rawSessionUser?.currentTenantId === \"string\" ? rawSessionUser.currentTenantId.trim() : \"\"\n\n if (!userId) {\n ctx.res.status(401)\n return null\n }\n\n if (!tenantId) {\n ctx.res.status(400)\n return null\n }\n\n return { userId, tenantId }\n}\n\n","import { z } from \"zod\"\n\n\nexport const ListRoute = \"/api/rb/notifications\"\nexport const CreateRoute = \"/api/rb/notifications/create\"\nexport const MarkReadRoute = \"/api/rb/notifications/:notificationId/read\"\nexport const MarkReadByUrlRoute = \"/api/rb/notifications/mark-read-by-url\"\nexport const ArchiveRoute = \"/api/rb/notifications/:notificationId/archive\"\nexport const MarkAllReadRoute = \"/api/rb/notifications/mark-all-read\"\nexport const SettingsRoute = \"/api/rb/notifications/settings\"\nexport const DigestRunRoute = \"/api/rb/notifications/digest/run\"\n\nexport const listRequestSchema = z.object({\n includeArchived: z.boolean().optional(),\n unreadOnly: z.boolean().optional(),\n limit: z.number().int().min(1).max(200).optional(),\n markSeen: z.boolean().optional(),\n})\n\nexport type ListRequestPayload = z.infer<typeof listRequestSchema>\n\nexport const notificationDataSchema = z.record(z.string(), z.string())\n\nexport const notificationPlatformPayloadSchema = z.object({\n webpush: z.record(z.string(), z.unknown()).optional(),\n fcmOptions: z.record(z.string(), z.unknown()).optional(),\n android: z.record(z.string(), z.unknown()).optional(),\n apns: z.record(z.string(), z.unknown()).optional(),\n}).passthrough()\n\nexport type NotificationPlatformPayload = z.infer<typeof notificationPlatformPayloadSchema>\n\nconst createRequestStringSchema = z.string().trim()\nconst notificationUrlModeSchema = z.enum([\"navigate\", \"merge_current_search\"])\n\nexport const notificationContentFieldsSchema = z.object({\n title: z.string().min(1),\n body: z.string().optional(),\n image: z.string().optional(),\n})\n\nexport const createRequestSchema = z.object({\n topic: createRequestStringSchema.min(1).optional(),\n title: createRequestStringSchema.min(1),\n body: createRequestStringSchema.optional(),\n image: createRequestStringSchema.optional(),\n url: createRequestStringSchema.min(1).optional(),\n urlMode: notificationUrlModeSchema.optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n data: notificationDataSchema.optional(),\n platform: notificationPlatformPayloadSchema.optional(),\n})\n\nexport type CreateRequestPayload = z.infer<typeof createRequestSchema>\n\nexport const normalizeNotificationActionUrl = (url: string, origin: string): string | null => {\n const raw = url.trim()\n if (!raw) return null\n\n try {\n const base = new URL(origin)\n const parsed = new URL(raw, base)\n if (parsed.origin !== base.origin) return null\n return `${parsed.pathname}${parsed.search}`\n } catch {\n return null\n }\n}\n\nexport const normalizeNotificationActionLink = (\n url: string,\n origin: string,\n urlMode: z.infer<typeof notificationUrlModeSchema> = \"navigate\",\n): string | null => {\n const raw = url.trim()\n if (!raw) return null\n\n try {\n const base = new URL(origin)\n const parsed = new URL(raw, base)\n if (parsed.origin !== base.origin) return null\n if (urlMode === \"navigate\") return `${parsed.pathname}${parsed.search}${parsed.hash}`\n return `${parsed.search}${parsed.hash}` || null\n } catch {\n return null\n }\n}\n\nexport const notificationSchema = z.object({\n id: z.string(),\n topic: z.string().optional(),\n title: notificationContentFieldsSchema.shape.title,\n body: notificationContentFieldsSchema.shape.body,\n image: notificationContentFieldsSchema.shape.image,\n data: notificationDataSchema.optional(),\n platform: notificationPlatformPayloadSchema.optional(),\n createdAt: z.string(),\n seenAt: z.string().optional(),\n readAt: z.string().optional(),\n archivedAt: z.string().optional(),\n})\n\nexport type NotificationPayload = z.infer<typeof notificationSchema>\n\nexport const listResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n notifications: z.array(notificationSchema).optional(),\n unreadCount: z.number().int().min(0).optional(),\n unseenCount: z.number().int().min(0).optional(),\n})\n\nexport type ListResponsePayload = z.infer<typeof listResponseSchema>\n\nexport const createResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n id: z.string().optional(),\n})\n\nexport type CreateResponsePayload = z.infer<typeof createResponseSchema>\n\nexport const markReadResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n})\n\nexport type MarkReadResponsePayload = z.infer<typeof markReadResponseSchema>\n\nexport const markReadByUrlRequestSchema = z.object({\n url: z.string().trim().min(1),\n})\n\nexport type MarkReadByUrlRequestPayload = z.infer<typeof markReadByUrlRequestSchema>\n\nexport const markReadByUrlResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n matchedCount: z.number().int().min(0).optional(),\n modifiedCount: z.number().int().min(0).optional(),\n})\n\nexport type MarkReadByUrlResponsePayload = z.infer<typeof markReadByUrlResponseSchema>\n\nexport const archiveResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n})\n\nexport type ArchiveResponsePayload = z.infer<typeof archiveResponseSchema>\n\nexport const markAllReadResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n})\n\nexport type MarkAllReadResponsePayload = z.infer<typeof markAllReadResponseSchema>\n\nexport const digestFrequencySchema = z.enum([\"off\", \"daily\", \"weekly\"])\n\nexport type DigestFrequency = z.infer<typeof digestFrequencySchema>\n\nexport const topicPreferenceSchema = z.object({\n topic: z.string(),\n inApp: z.boolean(),\n emailDigest: z.boolean(),\n push: z.boolean(),\n})\n\nexport type TopicPreferencePayload = z.infer<typeof topicPreferenceSchema>\n\nexport const settingsSchema = z.object({\n digestFrequency: digestFrequencySchema,\n topicPreferences: z.array(topicPreferenceSchema),\n lastDigestSentAt: z.string().optional(),\n})\n\nexport type SettingsPayload = z.infer<typeof settingsSchema>\n\nexport const settingsResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n settings: settingsSchema.optional(),\n})\n\nexport type SettingsResponsePayload = z.infer<typeof settingsResponseSchema>\n\nexport const updateSettingsRequestSchema = z.object({\n digestFrequency: digestFrequencySchema.optional(),\n topicPreferences: z.array(topicPreferenceSchema).optional(),\n})\n\nexport type UpdateSettingsRequestPayload = z.infer<typeof updateSettingsRequestSchema>\n\nexport const updateSettingsResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n settings: settingsSchema.optional(),\n})\n\nexport type UpdateSettingsResponsePayload = z.infer<typeof updateSettingsResponseSchema>\n\nexport const digestRunRequestSchema = z.object({\n force: z.boolean().optional(),\n})\n\nexport type DigestRunRequestPayload = z.infer<typeof digestRunRequestSchema>\n\nexport const digestRunResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n sent: z.boolean().optional(),\n skippedReason: z.string().optional(),\n})\n\nexport type DigestRunResponsePayload = z.infer<typeof digestRunResponseSchema>\n","import { Api, type ApiHandler, type Ctx } from \"@rpcbase/api\"\nimport { models, type IRBNotification, type IRBNotificationSettings } from \"@rpcbase/db\"\nimport { buildAbilityFromSession, getAccessibleByQuery } from \"@rpcbase/db/acl\"\n\nimport { createNotification } from \"../../createNotification\"\nimport { sendNotificationsDigestForUser } from \"../../digest\"\nimport { getSessionUser } from \"./shared\"\n\nimport * as Notifications from \"./index\"\n\n\ntype NotificationDoc = IRBNotification & { _id: unknown }\ntype NotificationActionDoc = Pick<NotificationDoc, \"_id\" | \"data\" | \"platform\">\ntype SettingsDoc = IRBNotificationSettings & { _id: unknown }\ntype NotificationActionLink = {\n link: string\n urlMode: \"navigate\" | \"merge_current_search\"\n}\n\nconst toIso = (value: unknown): string | undefined => (value instanceof Date ? value.toISOString() : undefined)\nconst isRecord = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === \"object\" && !Array.isArray(value)\n\nconst toStringMap = (value: unknown): Record<string, string> | undefined => {\n if (!isRecord(value)) return undefined\n const entries = Object.entries(value)\n .filter((entry): entry is [string, string] => typeof entry[1] === \"string\")\n return entries.length > 0 ? Object.fromEntries(entries) : undefined\n}\n\nconst getForwardedHeaderValue = (value: unknown): string | undefined => {\n const raw = Array.isArray(value) ? value[0] : value\n if (typeof raw !== \"string\") return undefined\n return raw.split(\",\")[0]?.trim() || undefined\n}\n\nconst getRequestOrigin = (ctx: Ctx): string => {\n const protocol = getForwardedHeaderValue(ctx.req.headers[\"x-forwarded-proto\"]) ?? ctx.req.protocol\n const host = getForwardedHeaderValue(ctx.req.headers[\"x-forwarded-host\"]) ?? ctx.req.get(\"host\")\n\n return protocol && host ? `${protocol}://${host}` : \"\"\n}\n\nconst getNotificationActionLinks = (notification: NotificationActionDoc): NotificationActionLink[] => {\n const links: NotificationActionLink[] = []\n\n if (typeof notification.data?.link === \"string\") {\n links.push({\n link: notification.data.link,\n urlMode: notification.data.linkMode === \"merge_current_search\" ? \"merge_current_search\" : \"navigate\",\n })\n }\n\n const platformWebpush = notification.platform?.webpush\n if (platformWebpush && typeof platformWebpush === \"object\" && !Array.isArray(platformWebpush)) {\n const fcmOptions = (platformWebpush as { fcmOptions?: unknown }).fcmOptions\n if (fcmOptions && typeof fcmOptions === \"object\" && !Array.isArray(fcmOptions)) {\n const link = (fcmOptions as { link?: unknown }).link\n if (typeof link === \"string\") {\n links.push({ link, urlMode: \"navigate\" })\n }\n }\n }\n\n return links\n}\n\nconst actionSearchParamsMatchTargetUrl = (actionUrl: string, targetUrl: string, origin: string): boolean => {\n try {\n const base = new URL(origin)\n const action = new URL(actionUrl, base)\n const target = new URL(targetUrl, base)\n for (const [key, value] of action.searchParams) {\n if (target.searchParams.get(key) !== value) return false\n }\n return Array.from(action.searchParams.keys()).length > 0\n } catch {\n return false\n }\n}\n\nconst notificationActionLinkMatchesUrl = (\n action: NotificationActionLink,\n targetUrl: string,\n origin: string,\n): boolean => {\n if (action.urlMode === \"merge_current_search\") {\n return actionSearchParamsMatchTargetUrl(action.link, targetUrl, origin)\n }\n\n return Notifications.normalizeNotificationActionUrl(action.link, origin) === targetUrl\n}\n\nconst buildDisabledTopics = (\n settings: SettingsDoc | null,\n key: \"inApp\" | \"emailDigest\",\n): string[] => {\n const raw = settings?.topicPreferences\n if (!Array.isArray(raw) || raw.length === 0) return []\n\n return raw\n .map((pref) => {\n if (!pref || typeof pref !== \"object\") return null\n const topic = typeof (pref as { topic?: unknown }).topic === \"string\" ? (pref as { topic: string }).topic.trim() : \"\"\n if (!topic) return null\n const enabled = (pref as Record<string, unknown>)[key] === true\n return enabled ? null : topic\n })\n .filter((topic): topic is string => Boolean(topic))\n}\n\nconst listNotifications: ApiHandler<Notifications.ListRequestPayload, Notifications.ListResponsePayload> = async(\n payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"read\", \"RBNotification\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const parsed = Notifications.listRequestSchema.safeParse(payload)\n if (!parsed.success) {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_payload\" }\n }\n\n const { userId } = session\n const includeArchived = parsed.data.includeArchived === true\n const unreadOnly = parsed.data.unreadOnly === true\n const limit = parsed.data.limit ?? 50\n const markSeen = parsed.data.markSeen === true\n\n const SettingsModel = await models.get(\"RBNotificationSettings\", { req: ctx.req, ability })\n const settings = (await SettingsModel.findOne({ userId }).lean()) as SettingsDoc | null\n const disabledTopics = buildDisabledTopics(settings, \"inApp\")\n\n const NotificationModel = await models.get(\"RBNotification\", { req: ctx.req, ability })\n\n const queryFilters: Record<string, unknown>[] = [\n { userId },\n getAccessibleByQuery(ability, \"read\", \"RBNotification\"),\n ]\n if (!includeArchived) queryFilters.push({ archivedAt: { $exists: false } })\n if (unreadOnly) queryFilters.push({ readAt: { $exists: false } })\n if (disabledTopics.length > 0) queryFilters.push({ topic: { $nin: disabledTopics } })\n const query: Record<string, unknown> = { $and: queryFilters }\n\n const notifications = (await NotificationModel.find(query)\n .sort({ createdAt: -1 })\n .limit(limit)\n .lean()) as NotificationDoc[]\n\n const unseenQueryFilters: Record<string, unknown>[] = [\n { userId },\n { archivedAt: { $exists: false } },\n { seenAt: { $exists: false } },\n getAccessibleByQuery(ability, \"read\", \"RBNotification\"),\n ]\n if (disabledTopics.length > 0) unseenQueryFilters.push({ topic: { $nin: disabledTopics } })\n const unseenQuery: Record<string, unknown> = { $and: unseenQueryFilters }\n\n const unreadQueryFilters: Record<string, unknown>[] = [\n { userId },\n { archivedAt: { $exists: false } },\n { readAt: { $exists: false } },\n getAccessibleByQuery(ability, \"read\", \"RBNotification\"),\n ]\n if (disabledTopics.length > 0) unreadQueryFilters.push({ topic: { $nin: disabledTopics } })\n const unreadQuery: Record<string, unknown> = { $and: unreadQueryFilters }\n\n const [unreadCount, unseenCount] = await Promise.all([\n NotificationModel.countDocuments(unreadQuery),\n NotificationModel.countDocuments(unseenQuery),\n ])\n\n const now = markSeen ? new Date() : null\n if (now && unseenCount > 0) {\n await NotificationModel.updateMany(unseenQuery, { $set: { seenAt: now } })\n }\n\n return Notifications.listResponseSchema.parse({\n ok: true,\n notifications: notifications.map((n) => ({\n id: String(n._id),\n topic: typeof n.topic === \"string\" ? n.topic : undefined,\n title: typeof n.title === \"string\" ? n.title : \"\",\n body: typeof n.body === \"string\" ? n.body : undefined,\n image: typeof n.image === \"string\" ? n.image : undefined,\n data: toStringMap(n.data),\n platform: isRecord(n.platform) ? n.platform : undefined,\n createdAt: toIso(n.createdAt) ?? new Date().toISOString(),\n seenAt: toIso(n.seenAt) ?? (now && !n.archivedAt && !n.seenAt ? now.toISOString() : undefined),\n readAt: toIso(n.readAt),\n archivedAt: toIso(n.archivedAt),\n })),\n unreadCount,\n unseenCount: now ? 0 : unseenCount,\n })\n}\n\nconst createNotificationForCurrentUser: ApiHandler<Notifications.CreateRequestPayload, Notifications.CreateResponsePayload> = async(\n payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"create\", \"RBNotification\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const parsed = Notifications.createRequestSchema.safeParse(payload)\n if (!parsed.success) {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_payload\" }\n }\n\n const origin = getRequestOrigin(ctx)\n const actionLink = parsed.data.url\n ? Notifications.normalizeNotificationActionLink(parsed.data.url, origin, parsed.data.urlMode) ?? undefined\n : undefined\n if (parsed.data.url && !actionLink) {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_payload\" }\n }\n\n const created = await createNotification(ctx, {\n userId: session.userId,\n topic: parsed.data.topic,\n title: parsed.data.title,\n body: parsed.data.body,\n image: parsed.data.image,\n url: actionLink,\n urlMode: parsed.data.urlMode,\n metadata: parsed.data.metadata,\n data: parsed.data.data,\n platform: parsed.data.platform,\n }, ability)\n\n return Notifications.createResponseSchema.parse({ ok: true, id: created.id })\n}\n\nconst markRead: ApiHandler<unknown, Notifications.MarkReadResponsePayload> = async(\n _payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"update\", \"RBNotification\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const notificationId = typeof ctx.req.params.notificationId === \"string\" ? ctx.req.params.notificationId.trim() : \"\"\n if (!notificationId) {\n ctx.res.status(400)\n return { ok: false, error: \"missing_notification_id\" }\n }\n\n const NotificationModel = await models.get(\"RBNotification\", { req: ctx.req, ability })\n const now = new Date()\n\n try {\n await NotificationModel.updateOne(\n { $and: [{ _id: notificationId }, { archivedAt: { $exists: false } }, getAccessibleByQuery(ability, \"update\", \"RBNotification\")] },\n { $set: { readAt: now, seenAt: now } },\n )\n } catch {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_notification_id\" }\n }\n\n return { ok: true }\n}\n\nconst markReadByUrl: ApiHandler<Notifications.MarkReadByUrlRequestPayload, Notifications.MarkReadByUrlResponsePayload> = async(\n payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"update\", \"RBNotification\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const parsed = Notifications.markReadByUrlRequestSchema.safeParse(payload)\n if (!parsed.success) {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_payload\" }\n }\n\n const origin = getRequestOrigin(ctx)\n const targetUrl = Notifications.normalizeNotificationActionUrl(parsed.data.url, origin)\n if (!targetUrl) {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_payload\" }\n }\n\n const NotificationModel = await models.get(\"RBNotification\", { req: ctx.req, ability })\n const query: Record<string, unknown> = {\n $and: [\n { userId: session.userId },\n { archivedAt: { $exists: false } },\n { readAt: { $exists: false } },\n {\n $or: [\n { \"data.link\": { $type: \"string\" } },\n { \"platform.webpush.fcmOptions.link\": { $type: \"string\" } },\n ],\n },\n getAccessibleByQuery(ability, \"update\", \"RBNotification\"),\n ],\n }\n\n const candidates = (await NotificationModel.find(query)\n .select({ _id: 1, data: 1, platform: 1 })\n .lean()) as NotificationActionDoc[]\n\n const matchingIds = candidates\n .filter((notification) =>\n getNotificationActionLinks(notification).some((action) =>\n notificationActionLinkMatchesUrl(action, targetUrl, origin),\n ),\n )\n .map((notification) => notification._id)\n\n if (matchingIds.length === 0) {\n return Notifications.markReadByUrlResponseSchema.parse({\n ok: true,\n matchedCount: 0,\n modifiedCount: 0,\n })\n }\n\n const now = new Date()\n const result = await NotificationModel.updateMany(\n {\n $and: [\n { _id: { $in: matchingIds } },\n { userId: session.userId },\n { archivedAt: { $exists: false } },\n { readAt: { $exists: false } },\n getAccessibleByQuery(ability, \"update\", \"RBNotification\"),\n ],\n },\n { $set: { readAt: now, seenAt: now } },\n )\n\n const modifiedCount = typeof result.modifiedCount === \"number\" ? result.modifiedCount : matchingIds.length\n\n return Notifications.markReadByUrlResponseSchema.parse({\n ok: true,\n matchedCount: matchingIds.length,\n modifiedCount,\n })\n}\n\nconst markAllRead: ApiHandler<unknown, Notifications.MarkAllReadResponsePayload> = async(\n _payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"update\", \"RBNotification\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const SettingsModel = await models.get(\"RBNotificationSettings\", { req: ctx.req, ability })\n const settings = (await SettingsModel.findOne({ userId: session.userId }).lean()) as SettingsDoc | null\n const disabledTopics = buildDisabledTopics(settings, \"inApp\")\n\n const NotificationModel = await models.get(\"RBNotification\", { req: ctx.req, ability })\n\n const queryFilters: Record<string, unknown>[] = [\n { userId: session.userId },\n { archivedAt: { $exists: false } },\n { readAt: { $exists: false } },\n getAccessibleByQuery(ability, \"update\", \"RBNotification\"),\n ]\n if (disabledTopics.length > 0) queryFilters.push({ topic: { $nin: disabledTopics } })\n const query: Record<string, unknown> = { $and: queryFilters }\n\n const now = new Date()\n await NotificationModel.updateMany(query, { $set: { readAt: now, seenAt: now } })\n\n return { ok: true }\n}\n\nconst archiveNotification: ApiHandler<unknown, Notifications.ArchiveResponsePayload> = async(\n _payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"update\", \"RBNotification\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const notificationId = typeof ctx.req.params.notificationId === \"string\" ? ctx.req.params.notificationId.trim() : \"\"\n if (!notificationId) {\n ctx.res.status(400)\n return { ok: false, error: \"missing_notification_id\" }\n }\n\n const NotificationModel = await models.get(\"RBNotification\", { req: ctx.req, ability })\n\n try {\n await NotificationModel.updateOne(\n { $and: [{ _id: notificationId }, { archivedAt: { $exists: false } }, getAccessibleByQuery(ability, \"update\", \"RBNotification\")] },\n { $set: { archivedAt: new Date() } },\n )\n } catch {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_notification_id\" }\n }\n\n return { ok: true }\n}\n\nconst getSettings: ApiHandler<unknown, Notifications.SettingsResponsePayload> = async(\n _payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"read\", \"RBNotificationSettings\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const SettingsModel = await models.get(\"RBNotificationSettings\", { req: ctx.req, ability })\n const settings = (await SettingsModel.findOne(\n { $and: [{ userId: session.userId }, getAccessibleByQuery(ability, \"read\", \"RBNotificationSettings\")] },\n ).lean()) as SettingsDoc | null\n\n const digestFrequencyRaw = typeof settings?.digestFrequency === \"string\" ? settings.digestFrequency : \"weekly\"\n const digestFrequency: Notifications.DigestFrequency =\n digestFrequencyRaw === \"off\" || digestFrequencyRaw === \"daily\" || digestFrequencyRaw === \"weekly\"\n ? digestFrequencyRaw\n : \"weekly\"\n\n const topicPreferences = Array.isArray(settings?.topicPreferences)\n ? settings!.topicPreferences.map((pref) => ({\n topic: typeof pref.topic === \"string\" ? pref.topic : \"\",\n inApp: pref.inApp === true,\n emailDigest: pref.emailDigest === true,\n push: pref.push === true,\n })).filter((pref) => pref.topic.length > 0)\n : []\n\n return Notifications.settingsResponseSchema.parse({\n ok: true,\n settings: {\n digestFrequency,\n topicPreferences,\n lastDigestSentAt: toIso(settings?.lastDigestSentAt),\n },\n })\n}\n\nconst updateSettings: ApiHandler<Notifications.UpdateSettingsRequestPayload, Notifications.UpdateSettingsResponsePayload> = async(\n payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"update\", \"RBNotificationSettings\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const parsed = Notifications.updateSettingsRequestSchema.safeParse(payload)\n if (!parsed.success) {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_payload\" }\n }\n\n const SettingsModel = await models.get(\"RBNotificationSettings\", { req: ctx.req, ability })\n const nextValues: Record<string, unknown> = {}\n\n if (parsed.data.digestFrequency) {\n nextValues.digestFrequency = parsed.data.digestFrequency\n }\n\n if (parsed.data.topicPreferences) {\n const seen = new Set<string>()\n const next = parsed.data.topicPreferences\n .map((pref) => ({\n topic: pref.topic.trim(),\n inApp: pref.inApp,\n emailDigest: pref.emailDigest,\n push: pref.push,\n }))\n .filter((pref) => pref.topic.length > 0)\n .filter((pref) => {\n if (seen.has(pref.topic)) return false\n seen.add(pref.topic)\n return true\n })\n\n nextValues.topicPreferences = next\n }\n\n const ops: Record<string, unknown> = {\n $setOnInsert: { userId: session.userId },\n }\n\n if (Object.keys(nextValues).length > 0) {\n ops.$set = nextValues\n }\n\n const settings = (await SettingsModel.findOneAndUpdate(\n { $and: [{ userId: session.userId }, getAccessibleByQuery(ability, \"update\", \"RBNotificationSettings\")] },\n ops,\n { upsert: true, returnDocument: \"after\", setDefaultsOnInsert: true },\n ).lean()) as SettingsDoc | null\n\n const digestFrequencyRaw = typeof settings?.digestFrequency === \"string\" ? settings.digestFrequency : \"weekly\"\n const digestFrequency: Notifications.DigestFrequency =\n digestFrequencyRaw === \"off\" || digestFrequencyRaw === \"daily\" || digestFrequencyRaw === \"weekly\"\n ? digestFrequencyRaw\n : \"weekly\"\n\n const topicPreferences = Array.isArray(settings?.topicPreferences)\n ? settings!.topicPreferences.map((pref) => ({\n topic: typeof pref.topic === \"string\" ? pref.topic : \"\",\n inApp: pref.inApp === true,\n emailDigest: pref.emailDigest === true,\n push: pref.push === true,\n })).filter((pref) => pref.topic.length > 0)\n : []\n\n return Notifications.updateSettingsResponseSchema.parse({\n ok: true,\n settings: {\n digestFrequency,\n topicPreferences,\n lastDigestSentAt: toIso(settings?.lastDigestSentAt),\n },\n })\n}\n\nconst runDigest: ApiHandler<Notifications.DigestRunRequestPayload, Notifications.DigestRunResponsePayload> = async(\n payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"read\", \"RBNotification\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const parsed = Notifications.digestRunRequestSchema.safeParse(payload)\n if (!parsed.success) {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_payload\" }\n }\n\n const result = await sendNotificationsDigestForUser(ctx, {\n userId: session.userId,\n ability,\n force: parsed.data.force === true,\n })\n\n if (!result.ok) {\n ctx.res.status(500)\n return { ok: false, error: result.error }\n }\n\n return {\n ok: true,\n sent: result.sent,\n ...(result.skippedReason ? { skippedReason: result.skippedReason } : {}),\n }\n}\n\nexport default (api: Api) => {\n api.post(Notifications.ListRoute, listNotifications)\n api.post(Notifications.CreateRoute, createNotificationForCurrentUser)\n api.post(Notifications.MarkReadRoute, markRead)\n api.post(Notifications.MarkReadByUrlRoute, markReadByUrl)\n api.post(Notifications.MarkAllReadRoute, markAllRead)\n api.post(Notifications.ArchiveRoute, archiveNotification)\n api.get(Notifications.SettingsRoute, getSettings)\n api.put(Notifications.SettingsRoute, updateSettings)\n api.post(Notifications.DigestRunRoute, runDigest)\n}\n"],"names":["getSessionUser","ctx","rawSessionUser","req","session","user","userId","id","trim","tenantId","currentTenantId","res","status","ListRoute","CreateRoute","MarkReadRoute","MarkReadByUrlRoute","ArchiveRoute","MarkAllReadRoute","SettingsRoute","DigestRunRoute","listRequestSchema","z","includeArchived","boolean","optional","unreadOnly","limit","int","min","max","markSeen","notificationDataSchema","notificationPlatformPayloadSchema","webpush","string","unknown","fcmOptions","android","apns","passthrough","createRequestStringSchema","notificationUrlModeSchema","notificationContentFieldsSchema","title","body","image","createRequestSchema","topic","url","urlMode","metadata","data","platform","normalizeNotificationActionUrl","origin","raw","base","URL","parsed","pathname","search","normalizeNotificationActionLink","hash","notificationSchema","shape","createdAt","seenAt","readAt","archivedAt","listResponseSchema","ok","error","notifications","unreadCount","number","unseenCount","createResponseSchema","markReadByUrlRequestSchema","markReadByUrlResponseSchema","matchedCount","modifiedCount","digestFrequencySchema","topicPreferenceSchema","inApp","emailDigest","push","settingsSchema","digestFrequency","topicPreferences","lastDigestSentAt","settingsResponseSchema","settings","updateSettingsRequestSchema","updateSettingsResponseSchema","digestRunRequestSchema","force","sent","skippedReason","toIso","value","Date","toISOString","undefined","isRecord","Boolean","Array","isArray","toStringMap","entries","Object","filter","entry","length","fromEntries","getForwardedHeaderValue","split","getRequestOrigin","protocol","headers","host","get","getNotificationActionLinks","notification","links","link","linkMode","platformWebpush","actionSearchParamsMatchTargetUrl","actionUrl","targetUrl","action","target","key","searchParams","from","keys","notificationActionLinkMatchesUrl","Notifications","buildDisabledTopics","map","pref","enabled","listNotifications","payload","ability","buildAbilityFromSession","can","safeParse","success","SettingsModel","models","findOne","lean","disabledTopics","NotificationModel","queryFilters","getAccessibleByQuery","$exists","$nin","query","$and","find","sort","unseenQueryFilters","unseenQuery","unreadQueryFilters","unreadQuery","Promise","all","countDocuments","now","updateMany","$set","parse","n","String","_id","createNotificationForCurrentUser","actionLink","created","createNotification","markRead","_payload","notificationId","params","updateOne","markReadByUrl","$or","$type","candidates","select","matchingIds","some","result","$in","markAllRead","archiveNotification","getSettings","digestFrequencyRaw","updateSettings","nextValues","seen","Set","next","has","add","ops","$setOnInsert","findOneAndUpdate","upsert","returnDocument","setDefaultsOnInsert","runDigest","sendNotificationsDigestForUser","api","post","put"],"mappings":";;;;AAQO,MAAMA,iBAAiBA,CAACC,QAAa;AAC1C,QAAMC,iBAAkBD,IAAIE,IAAIC,SAAmEC;AACnG,QAAMC,SAAS,OAAOJ,gBAAgBK,OAAO,WAAWL,eAAeK,GAAGC,SAAS;AACnF,QAAMC,WAAW,OAAOP,gBAAgBQ,oBAAoB,WAAWR,eAAeQ,gBAAgBF,SAAS;AAE/G,MAAI,CAACF,QAAQ;AACXL,QAAIU,IAAIC,OAAO,GAAG;AAClB,WAAO;AAAA,EACT;AAEA,MA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E1E;AAEA,MAAA,UAAe,CAACqH,QAAa;AAC3BA,MAAIC,KAAK9E,WAAyBK,iBAAiB;AACnDwE,MAAIC,KAAK9E,aAA2BwC,gCAAgC;AACpEqC,MAAIC,KAAK9E,eAA6B4C,QAAQ;AAC9CiC,MAAIC,KAAK9E,oBAAkCiD,aAAa;AACxD4B,MAAIC,KAAK9E,kBAAgC0D,WAAW;AACpDmB,MAAIC,KAAK9E,cAA4B2D,mBAAmB;AACxDkB,MAAI9F,IAAIiB,eAA6B4D,WAAW;AAChDiB,MAAIE,IAAI/E,eAA6B8D,cAAc;AACnDe,MAAIC,KAAK9E,gBAA8B2E,SAAS;AAClD;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../../../src/notifications/api/notifications/handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,
|
|
1
|
+
{"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../../../src/notifications/api/notifications/handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAA6B,MAAM,cAAc,CAAA;yBAymB7C,KAAK,GAAG;AAAxB,wBAUC"}
|
|
@@ -2,6 +2,7 @@ import { z } from 'zod';
|
|
|
2
2
|
export declare const ListRoute = "/api/rb/notifications";
|
|
3
3
|
export declare const CreateRoute = "/api/rb/notifications/create";
|
|
4
4
|
export declare const MarkReadRoute = "/api/rb/notifications/:notificationId/read";
|
|
5
|
+
export declare const MarkReadByUrlRoute = "/api/rb/notifications/mark-read-by-url";
|
|
5
6
|
export declare const ArchiveRoute = "/api/rb/notifications/:notificationId/archive";
|
|
6
7
|
export declare const MarkAllReadRoute = "/api/rb/notifications/mark-all-read";
|
|
7
8
|
export declare const SettingsRoute = "/api/rb/notifications/settings";
|
|
@@ -21,6 +22,10 @@ export declare const notificationPlatformPayloadSchema: z.ZodObject<{
|
|
|
21
22
|
apns: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
22
23
|
}, z.core.$loose>;
|
|
23
24
|
export type NotificationPlatformPayload = z.infer<typeof notificationPlatformPayloadSchema>;
|
|
25
|
+
declare const notificationUrlModeSchema: z.ZodEnum<{
|
|
26
|
+
navigate: "navigate";
|
|
27
|
+
merge_current_search: "merge_current_search";
|
|
28
|
+
}>;
|
|
24
29
|
export declare const notificationContentFieldsSchema: z.ZodObject<{
|
|
25
30
|
title: z.ZodString;
|
|
26
31
|
body: z.ZodOptional<z.ZodString>;
|
|
@@ -31,6 +36,12 @@ export declare const createRequestSchema: z.ZodObject<{
|
|
|
31
36
|
title: z.ZodString;
|
|
32
37
|
body: z.ZodOptional<z.ZodString>;
|
|
33
38
|
image: z.ZodOptional<z.ZodString>;
|
|
39
|
+
url: z.ZodOptional<z.ZodString>;
|
|
40
|
+
urlMode: z.ZodOptional<z.ZodEnum<{
|
|
41
|
+
navigate: "navigate";
|
|
42
|
+
merge_current_search: "merge_current_search";
|
|
43
|
+
}>>;
|
|
44
|
+
metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
34
45
|
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
35
46
|
platform: z.ZodOptional<z.ZodObject<{
|
|
36
47
|
webpush: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
@@ -40,6 +51,8 @@ export declare const createRequestSchema: z.ZodObject<{
|
|
|
40
51
|
}, z.core.$loose>>;
|
|
41
52
|
}, z.core.$strip>;
|
|
42
53
|
export type CreateRequestPayload = z.infer<typeof createRequestSchema>;
|
|
54
|
+
export declare const normalizeNotificationActionUrl: (url: string, origin: string) => string | null;
|
|
55
|
+
export declare const normalizeNotificationActionLink: (url: string, origin: string, urlMode?: z.infer<typeof notificationUrlModeSchema>) => string | null;
|
|
43
56
|
export declare const notificationSchema: z.ZodObject<{
|
|
44
57
|
id: z.ZodString;
|
|
45
58
|
topic: z.ZodOptional<z.ZodString>;
|
|
@@ -95,6 +108,17 @@ export declare const markReadResponseSchema: z.ZodObject<{
|
|
|
95
108
|
error: z.ZodOptional<z.ZodString>;
|
|
96
109
|
}, z.core.$strip>;
|
|
97
110
|
export type MarkReadResponsePayload = z.infer<typeof markReadResponseSchema>;
|
|
111
|
+
export declare const markReadByUrlRequestSchema: z.ZodObject<{
|
|
112
|
+
url: z.ZodString;
|
|
113
|
+
}, z.core.$strip>;
|
|
114
|
+
export type MarkReadByUrlRequestPayload = z.infer<typeof markReadByUrlRequestSchema>;
|
|
115
|
+
export declare const markReadByUrlResponseSchema: z.ZodObject<{
|
|
116
|
+
ok: z.ZodBoolean;
|
|
117
|
+
error: z.ZodOptional<z.ZodString>;
|
|
118
|
+
matchedCount: z.ZodOptional<z.ZodNumber>;
|
|
119
|
+
modifiedCount: z.ZodOptional<z.ZodNumber>;
|
|
120
|
+
}, z.core.$strip>;
|
|
121
|
+
export type MarkReadByUrlResponsePayload = z.infer<typeof markReadByUrlResponseSchema>;
|
|
98
122
|
export declare const archiveResponseSchema: z.ZodObject<{
|
|
99
123
|
ok: z.ZodBoolean;
|
|
100
124
|
error: z.ZodOptional<z.ZodString>;
|
|
@@ -196,4 +220,5 @@ export declare const digestRunResponseSchema: z.ZodObject<{
|
|
|
196
220
|
skippedReason: z.ZodOptional<z.ZodString>;
|
|
197
221
|
}, z.core.$strip>;
|
|
198
222
|
export type DigestRunResponsePayload = z.infer<typeof digestRunResponseSchema>;
|
|
223
|
+
export {};
|
|
199
224
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/notifications/api/notifications/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAGvB,eAAO,MAAM,SAAS,0BAA0B,CAAA;AAChD,eAAO,MAAM,WAAW,iCAAiC,CAAA;AACzD,eAAO,MAAM,aAAa,+CAA+C,CAAA;AACzE,eAAO,MAAM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,uBAAuB;;;;;iBAKlC,CAAA;AAEF,MAAM,MAAM,wBAAwB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAA"}
|
|
@@ -2,13 +2,18 @@ import { Ctx } from '@rpcbase/api';
|
|
|
2
2
|
import { IRBNotificationPlatformPayload } from '@rpcbase/db';
|
|
3
3
|
import { AppAbility } from '@rpcbase/db/acl';
|
|
4
4
|
export type NotificationDataPayload = Record<string, string>;
|
|
5
|
+
export type NotificationMetadataPayload = Record<string, unknown>;
|
|
5
6
|
export type NotificationPlatformPayload = IRBNotificationPlatformPayload;
|
|
7
|
+
export type NotificationUrlMode = "navigate" | "merge_current_search";
|
|
6
8
|
export type CreateNotificationInput = {
|
|
7
9
|
userId: string;
|
|
8
10
|
topic?: string;
|
|
9
11
|
title: string;
|
|
10
12
|
body?: string;
|
|
11
13
|
image?: string;
|
|
14
|
+
url?: string;
|
|
15
|
+
urlMode?: NotificationUrlMode;
|
|
16
|
+
metadata?: NotificationMetadataPayload;
|
|
12
17
|
data?: NotificationDataPayload;
|
|
13
18
|
platform?: NotificationPlatformPayload;
|
|
14
19
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createNotification.d.ts","sourceRoot":"","sources":["../../src/notifications/createNotification.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;AACvC,OAAO,EAAU,KAAK,8BAA8B,EAAE,MAAM,aAAa,CAAA;AACzE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAGjD,MAAM,MAAM,uBAAuB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAC5D,MAAM,MAAM,2BAA2B,GAAG,8BAA8B,CAAA;
|
|
1
|
+
{"version":3,"file":"createNotification.d.ts","sourceRoot":"","sources":["../../src/notifications/createNotification.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MA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AAE,GAAG,EAAE,MAAM,EAAE,CAAA;CAAE,CAmB3B,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"digest.d.ts","sourceRoot":"","sources":["../../src/notifications/digest.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;AAEvC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;
|
|
1
|
+
{"version":3,"file":"digest.d.ts","sourceRoot":"","sources":["../../src/notifications/digest.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;AAEvC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAoDjD,eAAO,MAAM,8BAA8B,GACzC,KAAK,GAAG,EACR,6BAIG;IACD,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,UAAU,CAAA;IACnB,KAAK,CAAC,EAAE,OAAO,CAAA;CAChB,KACA,OAAO,CAAC;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,OAAO,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CA2F5F,CAAA"}
|
package/dist/notifications.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { models } from "@rpcbase/db";
|
|
2
2
|
import { s as sendEmail } from "./email-BbPlSkbt.js";
|
|
3
3
|
const routes = Object.entries({
|
|
4
|
-
.../* @__PURE__ */ Object.assign({ "./api/notifications/handler.ts": () => import("./handler-
|
|
4
|
+
.../* @__PURE__ */ Object.assign({ "./api/notifications/handler.ts": () => import("./handler-BTtU7fJq.js") })
|
|
5
5
|
}).reduce((acc, [path, mod]) => {
|
|
6
6
|
acc[path.replace("./api/", "@rpcbase/server/notifications/api/")] = mod;
|
|
7
7
|
return acc;
|
|
@@ -17,12 +17,81 @@ const normalizeOptionalString = (value) => {
|
|
|
17
17
|
const normalized = typeof value === "string" ? value.trim() : "";
|
|
18
18
|
return normalized || void 0;
|
|
19
19
|
};
|
|
20
|
+
const normalizeUrlMode = (value) => {
|
|
21
|
+
return value === "merge_current_search" ? "merge_current_search" : "navigate";
|
|
22
|
+
};
|
|
23
|
+
const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
24
|
+
const toNotificationDataString = (value) => {
|
|
25
|
+
if (typeof value === "string") {
|
|
26
|
+
const trimmed = value.trim();
|
|
27
|
+
return trimmed || void 0;
|
|
28
|
+
}
|
|
29
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
30
|
+
if (typeof value === "boolean") return String(value);
|
|
31
|
+
if (typeof value === "bigint") return value.toString();
|
|
32
|
+
if (value instanceof Date && Number.isFinite(value.getTime())) return value.toISOString();
|
|
33
|
+
return void 0;
|
|
34
|
+
};
|
|
35
|
+
const normalizeNotificationActionLink = (url, urlMode) => {
|
|
36
|
+
const normalizedUrl = normalizeOptionalString(url);
|
|
37
|
+
if (!normalizedUrl) return void 0;
|
|
38
|
+
if (urlMode === "navigate") return normalizedUrl;
|
|
39
|
+
try {
|
|
40
|
+
const parsed = new URL(normalizedUrl, "https://rpcbase.local/");
|
|
41
|
+
return `${parsed.search}${parsed.hash}` || void 0;
|
|
42
|
+
} catch {
|
|
43
|
+
return normalizedUrl.startsWith("?") ? normalizedUrl : void 0;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const buildNotificationData = (input) => {
|
|
47
|
+
const data = {};
|
|
48
|
+
for (const [key, value] of Object.entries(input.metadata ?? {})) {
|
|
49
|
+
const normalized = toNotificationDataString(value);
|
|
50
|
+
if (normalized) {
|
|
51
|
+
data[key] = normalized;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (input.data) {
|
|
55
|
+
Object.assign(data, input.data);
|
|
56
|
+
}
|
|
57
|
+
if (input.link) {
|
|
58
|
+
data.link = input.link;
|
|
59
|
+
if (input.urlMode !== "navigate") {
|
|
60
|
+
data.linkMode = input.urlMode;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return Object.keys(data).length > 0 ? data : void 0;
|
|
64
|
+
};
|
|
65
|
+
const buildNotificationPlatform = (platform, link) => {
|
|
66
|
+
if (!link) return platform;
|
|
67
|
+
const webpush = isRecord(platform?.webpush) ? platform.webpush : {};
|
|
68
|
+
const fcmOptions = isRecord(webpush.fcmOptions) ? webpush.fcmOptions : {};
|
|
69
|
+
return {
|
|
70
|
+
...platform,
|
|
71
|
+
webpush: {
|
|
72
|
+
...webpush,
|
|
73
|
+
fcmOptions: {
|
|
74
|
+
...fcmOptions,
|
|
75
|
+
link
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
};
|
|
20
80
|
const createNotificationDocument = (input) => {
|
|
21
81
|
const userId = normalizeRequiredString(input.userId, "createNotification: userId");
|
|
22
82
|
const title = normalizeRequiredString(input.title, "createNotification: title");
|
|
23
83
|
const topic = normalizeOptionalString(input.topic);
|
|
24
84
|
const body = normalizeOptionalString(input.body);
|
|
25
85
|
const image = normalizeOptionalString(input.image);
|
|
86
|
+
const urlMode = normalizeUrlMode(input.urlMode);
|
|
87
|
+
const link = normalizeNotificationActionLink(input.url, urlMode);
|
|
88
|
+
const data = buildNotificationData({
|
|
89
|
+
data: input.data,
|
|
90
|
+
metadata: input.metadata,
|
|
91
|
+
link,
|
|
92
|
+
urlMode
|
|
93
|
+
});
|
|
94
|
+
const platform = buildNotificationPlatform(input.platform, link);
|
|
26
95
|
return {
|
|
27
96
|
userId,
|
|
28
97
|
...topic ? {
|
|
@@ -35,11 +104,11 @@ const createNotificationDocument = (input) => {
|
|
|
35
104
|
...image ? {
|
|
36
105
|
image
|
|
37
106
|
} : {},
|
|
38
|
-
...
|
|
39
|
-
data
|
|
107
|
+
...data ? {
|
|
108
|
+
data
|
|
40
109
|
} : {},
|
|
41
|
-
...
|
|
42
|
-
platform
|
|
110
|
+
...platform ? {
|
|
111
|
+
platform
|
|
43
112
|
} : {}
|
|
44
113
|
};
|
|
45
114
|
};
|
|
@@ -91,7 +160,9 @@ const formatIso = (value) => {
|
|
|
91
160
|
if (!(value instanceof Date)) return void 0;
|
|
92
161
|
return value.toISOString();
|
|
93
162
|
};
|
|
94
|
-
const
|
|
163
|
+
const getNotificationLink = (notification) => {
|
|
164
|
+
const dataLink = notification.data?.link?.trim();
|
|
165
|
+
if (dataLink) return dataLink;
|
|
95
166
|
const platform = notification.platform;
|
|
96
167
|
if (!platform || typeof platform !== "object" || Array.isArray(platform)) return "";
|
|
97
168
|
const webpush = platform.webpush;
|
|
@@ -99,7 +170,7 @@ const getWebpushLink = (notification) => {
|
|
|
99
170
|
const fcmOptions = webpush.fcmOptions;
|
|
100
171
|
if (!fcmOptions || typeof fcmOptions !== "object" || Array.isArray(fcmOptions)) return "";
|
|
101
172
|
const link = fcmOptions.link;
|
|
102
|
-
return typeof link === "string" ? link : "";
|
|
173
|
+
return typeof link === "string" ? link.trim() : "";
|
|
103
174
|
};
|
|
104
175
|
const buildPreferencesByTopic = (settings) => {
|
|
105
176
|
const record = {};
|
|
@@ -208,7 +279,7 @@ const sendNotificationsDigestForUser = async (ctx, {
|
|
|
208
279
|
const rows = notifications.map((n) => {
|
|
209
280
|
const title = typeof n.title === "string" ? n.title : "";
|
|
210
281
|
const body = typeof n.body === "string" ? n.body : "";
|
|
211
|
-
const url =
|
|
282
|
+
const url = getNotificationLink(n);
|
|
212
283
|
const createdAt = formatIso(n.createdAt) ?? "";
|
|
213
284
|
const line = url ? `<li><strong>${title}</strong><br>${body}<br><a href="${url}">${url}</a><br><small>${createdAt}</small></li>` : `<li><strong>${title}</strong><br>${body}<br><small>${createdAt}</small></li>`;
|
|
214
285
|
return line;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"notifications.js","sources":["../src/notifications/routes.ts","../src/notifications/createNotification.ts","../src/notifications/digest.ts"],"sourcesContent":["export const routes = Object.entries({\n ...import.meta.glob(\"./api/**/handler.ts\"),\n}).reduce<Record<string, unknown>>((acc, [path, mod]) => {\n acc[path.replace(\"./api/\", \"@rpcbase/server/notifications/api/\")] = mod\n return acc\n}, {})\n\n","import type { Ctx } from \"@rpcbase/api\"\nimport { models, type IRBNotificationPlatformPayload } from \"@rpcbase/db\"\nimport type { AppAbility } from \"@rpcbase/db/acl\"\n\n\nexport type NotificationDataPayload = Record<string, string>\nexport type NotificationPlatformPayload = IRBNotificationPlatformPayload\n\nexport type CreateNotificationInput = {\n userId: string\n topic?: string\n title: string\n body?: string\n image?: string\n data?: NotificationDataPayload\n platform?: NotificationPlatformPayload\n}\n\nexport type CreateNotificationForUserInput = Omit<CreateNotificationInput, \"userId\">\n\nexport type CreateNotificationsForUserInput = {\n userId: string\n notifications: CreateNotificationForUserInput[]\n}\n\nconst normalizeRequiredString = (value: unknown, name: string): string => {\n const normalized = typeof value === \"string\" ? value.trim() : \"\"\n if (!normalized) {\n throw new Error(`${name} is required`)\n }\n return normalized\n}\n\nconst normalizeOptionalString = (value: string | undefined): string | undefined => {\n const normalized = typeof value === \"string\" ? value.trim() : \"\"\n return normalized || undefined\n}\n\nconst createNotificationDocument = (input: CreateNotificationInput) => {\n const userId = normalizeRequiredString(input.userId, \"createNotification: userId\")\n const title = normalizeRequiredString(input.title, \"createNotification: title\")\n const topic = normalizeOptionalString(input.topic)\n const body = normalizeOptionalString(input.body)\n const image = normalizeOptionalString(input.image)\n\n return {\n userId,\n ...(topic ? { topic } : {}),\n title,\n ...(body ? { body } : {}),\n ...(image ? { image } : {}),\n ...(input.data ? { data: input.data } : {}),\n ...(input.platform ? { platform: input.platform } : {}),\n }\n}\n\nconst assertCreateNotificationsForUserInput = (input: CreateNotificationsForUserInput): void => {\n if (typeof input.userId !== \"string\" || input.userId.trim().length === 0) {\n throw new Error(\"createNotificationsForUser: userId is required\")\n }\n if (!Array.isArray(input.notifications)) {\n throw new Error(\"createNotificationsForUser: notifications must be an array\")\n }\n}\n\nexport const createNotification = async (\n ctx: Ctx,\n input: CreateNotificationInput,\n ability: AppAbility,\n): Promise<{ id: string }> => {\n const NotificationModel = await models.get(\"RBNotification\", { req: ctx.req, ability })\n const doc = await NotificationModel.create(createNotificationDocument(input))\n\n return { id: doc._id.toString() }\n}\n\nexport const createNotificationsForUser = async (\n ctx: Ctx,\n input: CreateNotificationsForUserInput,\n ability: AppAbility,\n): Promise<{ ids: string[] }> => {\n assertCreateNotificationsForUserInput(input)\n if (input.notifications.length === 0) {\n return { ids: [] }\n }\n\n const NotificationModel = await models.get(\"RBNotification\", { req: ctx.req, ability })\n const docs = await NotificationModel.create(\n input.notifications.map((notification) =>\n createNotificationDocument({\n ...notification,\n userId: input.userId,\n }),\n ),\n )\n\n return {\n ids: (docs as Array<{ _id: { toString: () => string } }>).map((doc) => doc._id.toString()),\n }\n}\n","import type { Ctx } from \"@rpcbase/api\"\nimport { models, type IRBNotification, type IRBNotificationSettings } from \"@rpcbase/db\"\nimport type { AppAbility } from \"@rpcbase/db/acl\"\n\nimport { sendEmail } from \"../email\"\n\n\nconst DAY_MS = 24 * 60 * 60 * 1000\nconst WEEK_MS = 7 * DAY_MS\n\ntype DigestFrequency = \"off\" | \"daily\" | \"weekly\"\n\ntype NotificationDoc = IRBNotification & { _id: unknown }\ntype SettingsDoc = IRBNotificationSettings & { _id: unknown }\n\nconst getDigestWindowMs = (frequency: DigestFrequency): number => {\n if (frequency === \"daily\") return DAY_MS\n if (frequency === \"weekly\") return WEEK_MS\n return 0\n}\n\nconst formatIso = (value: unknown): string | undefined => {\n if (!(value instanceof Date)) return undefined\n return value.toISOString()\n}\n\nconst getWebpushLink = (notification: NotificationDoc): string => {\n const platform = notification.platform\n if (!platform || typeof platform !== \"object\" || Array.isArray(platform)) return \"\"\n const webpush = (platform as { webpush?: unknown }).webpush\n if (!webpush || typeof webpush !== \"object\" || Array.isArray(webpush)) return \"\"\n const fcmOptions = (webpush as { fcmOptions?: unknown }).fcmOptions\n if (!fcmOptions || typeof fcmOptions !== \"object\" || Array.isArray(fcmOptions)) return \"\"\n const link = (fcmOptions as { link?: unknown }).link\n return typeof link === \"string\" ? link : \"\"\n}\n\nconst buildPreferencesByTopic = (settings: SettingsDoc | null): Record<string, { emailDigest: boolean }> => {\n const record: Record<string, { emailDigest: boolean }> = {}\n const raw = settings?.topicPreferences\n if (!Array.isArray(raw)) return record\n for (const pref of raw) {\n if (!pref || typeof pref !== \"object\") continue\n const topic = typeof (pref as { topic?: unknown }).topic === \"string\" ? (pref as { topic: string }).topic.trim() : \"\"\n if (!topic) continue\n const emailDigest = (pref as { emailDigest?: unknown }).emailDigest\n record[topic] = { emailDigest: emailDigest === true }\n }\n return record\n}\n\nexport const sendNotificationsDigestForUser = async (\n ctx: Ctx,\n {\n userId,\n ability,\n force = false,\n }: {\n userId: string\n ability: AppAbility\n force?: boolean\n },\n): Promise<{ ok: true; sent: boolean; skippedReason?: string } | { ok: false; error: string }> => {\n const modelCtx = { req: ctx.req, ability }\n const SettingsModel = await models.get(\"RBNotificationSettings\", modelCtx)\n const NotificationModel = await models.get(\"RBNotification\", modelCtx)\n\n const settings = (await SettingsModel.findOne({ userId }).lean()) as SettingsDoc | null\n\n const digestFrequencyRaw = typeof settings?.digestFrequency === \"string\" ? settings.digestFrequency : \"weekly\"\n const digestFrequency: DigestFrequency =\n digestFrequencyRaw === \"daily\" || digestFrequencyRaw === \"weekly\" || digestFrequencyRaw === \"off\"\n ? digestFrequencyRaw\n : \"weekly\"\n\n if (digestFrequency === \"off\") {\n return { ok: true, sent: false, skippedReason: \"digest_off\" }\n }\n\n const now = new Date()\n const windowMs = getDigestWindowMs(digestFrequency)\n const lastSentAt = settings?.lastDigestSentAt instanceof Date ? settings.lastDigestSentAt : null\n const since = lastSentAt ?? new Date(now.getTime() - windowMs)\n\n if (!force && lastSentAt && now.getTime() - lastSentAt.getTime() < windowMs) {\n return { ok: true, sent: false, skippedReason: \"not_due\" }\n }\n\n const preferencesByTopic = buildPreferencesByTopic(settings)\n const disabledTopics = Object.entries(preferencesByTopic)\n .filter(([, pref]) => pref.emailDigest === false)\n .map(([topic]) => topic)\n\n const query: Record<string, unknown> = {\n userId,\n archivedAt: { $exists: false },\n readAt: { $exists: false },\n createdAt: { $gt: since },\n }\n\n if (disabledTopics.length > 0) {\n query.topic = { $nin: disabledTopics }\n }\n\n const notifications = (await NotificationModel.find(query)\n .sort({ createdAt: -1 })\n .limit(50)\n .lean()) as NotificationDoc[]\n\n if (!notifications.length) {\n await SettingsModel.updateOne(\n { userId },\n { $set: { lastDigestSentAt: now }, $setOnInsert: { userId, digestFrequency: \"weekly\" } },\n { upsert: true },\n )\n return { ok: true, sent: false, skippedReason: \"empty\" }\n }\n\n const UserModel = await models.getGlobal(\"RBUser\", ctx)\n const user = (await UserModel.findById(userId, { email: 1 }).lean()) as { email?: unknown } | null\n const email = typeof user?.email === \"string\" ? user.email.trim() : \"\"\n if (!email) {\n return { ok: true, sent: false, skippedReason: \"missing_email\" }\n }\n\n const subject = \"Notifications digest\"\n const rows = notifications\n .map((n) => {\n const title = typeof n.title === \"string\" ? n.title : \"\"\n const body = typeof n.body === \"string\" ? n.body : \"\"\n const url = getWebpushLink(n)\n const createdAt = formatIso(n.createdAt) ?? \"\"\n const line = url\n ? `<li><strong>${title}</strong><br>${body}<br><a href=\"${url}\">${url}</a><br><small>${createdAt}</small></li>`\n : `<li><strong>${title}</strong><br>${body}<br><small>${createdAt}</small></li>`\n return line\n })\n .join(\"\")\n\n const html = `<div><p>Here is your notifications digest:</p><ul>${rows}</ul></div>`\n\n const emailResult = await sendEmail({ to: email, subject, html })\n if (emailResult.error) {\n return { ok: false, error: emailResult.error }\n }\n\n await SettingsModel.updateOne(\n { userId },\n { $set: { lastDigestSentAt: now }, $setOnInsert: { userId, digestFrequency: \"weekly\" } },\n { upsert: true },\n )\n\n return { ok: true, sent: emailResult.skipped !== true, ...(emailResult.skipped ? { skippedReason: \"email_skipped\" } : {}) }\n}\n"],"names":["routes","Object","entries","import","reduce","acc","path","mod","replace","normalizeRequiredString","value","name","normalized","trim","Error","normalizeOptionalString","undefined","createNotificationDocument","input","userId","title","topic","body","image","data","platform","assertCreateNotificationsForUserInput","length","Array","isArray","notifications","createNotification","ctx","ability","NotificationModel","models","get","req","doc","create","id","_id","toString","createNotificationsForUser","ids","docs","map","notification","DAY_MS","WEEK_MS","getDigestWindowMs","frequency","formatIso","Date","toISOString","getWebpushLink","webpush","fcmOptions","link","buildPreferencesByTopic","settings","record","raw","topicPreferences","pref","emailDigest","sendNotificationsDigestForUser","force","modelCtx","SettingsModel","findOne","lean","digestFrequencyRaw","digestFrequency","ok","sent","skippedReason","now","windowMs","lastSentAt","lastDigestSentAt","since","getTime","preferencesByTopic","disabledTopics","filter","query","archivedAt","$exists","readAt","createdAt","$gt","$nin","find","sort","limit","updateOne","$set","$setOnInsert","upsert","UserModel","getGlobal","user","findById","email","subject","rows","n","url","line","join","html","emailResult","sendEmail","to","error","skipped"],"mappings":";;AAAO,MAAMA,SAASC,OAAOC,QAAQ;AAAA,EACnC,GAAGC,uBAAAA,OAAAA,EAAAA,kCAAAA,MAAAA,OAAAA,uBAAAA,EAAAA,CAAAA;AACL,CAAC,EAAEC,OAAgC,CAACC,KAAK,CAACC,MAAMC,GAAG,MAAM;AACvDF,MAAIC,KAAKE,QAAQ,UAAU,oCAAoC,CAAC,IAAID;AACpE,SAAOF;AACT,GAAG,CAAA,CAAE;ACoBL,MAAMI,0BAA0BA,CAACC,OAAgBC,SAAyB;AACxE,QAAMC,aAAa,OAAOF,UAAU,WAAWA,MAAMG,SAAS;AAC9D,MAAI,CAACD,YAAY;AACf,UAAM,IAAIE,MAAM,GAAGH,IAAI,cAAc;AAAA,EACvC;AACA,SAAOC;AACT;AAEA,MAAMG,0BAA0BA,CAACL,UAAkD;AACjF,QAAME,aAAa,OAAOF,UAAU,WAAWA,MAAMG,SAAS;AAC9D,SAAOD,cAAcI;AACvB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G;AAAAA,IAAAA;AAAAA,EACzC;AAEA,QAAM9C,cAAc2B,UAClB;AAAA,IAAE7E;AAAAA,EAAAA,GACF;AAAA,IAAE8E,MAAM;AAAA,MAAEjB,kBAAkBH;AAAAA,IAAAA;AAAAA,IAAOqB,cAAc;AAAA,MAAE/E;AAAAA,MAAQsD,iBAAiB;AAAA,IAAA;AAAA,EAAS,GACrF;AAAA,IAAE0B,QAAQ;AAAA,EAAA,CACZ;AAEA,SAAO;AAAA,IAAEzB,IAAI;AAAA,IAAMC,MAAMqC,YAAYI,YAAY;AAAA,IAAM,GAAIJ,YAAYI,UAAU;AAAA,MAAExC,eAAe;AAAA,IAAA,IAAoB,CAAA;AAAA,EAAC;AACzH;"}
|
|
1
|
+
{"version":3,"file":"notifications.js","sources":["../src/notifications/routes.ts","../src/notifications/createNotification.ts","../src/notifications/digest.ts"],"sourcesContent":["export const routes = Object.entries({\n ...import.meta.glob(\"./api/**/handler.ts\"),\n}).reduce<Record<string, unknown>>((acc, [path, mod]) => {\n acc[path.replace(\"./api/\", \"@rpcbase/server/notifications/api/\")] = mod\n return acc\n}, {})\n\n","import type { Ctx } from \"@rpcbase/api\"\nimport { models, type IRBNotificationPlatformPayload } from \"@rpcbase/db\"\nimport type { AppAbility } from \"@rpcbase/db/acl\"\n\n\nexport type NotificationDataPayload = Record<string, string>\nexport type NotificationMetadataPayload = Record<string, unknown>\nexport type NotificationPlatformPayload = IRBNotificationPlatformPayload\nexport type NotificationUrlMode = \"navigate\" | \"merge_current_search\"\n\nexport type CreateNotificationInput = {\n userId: string\n topic?: string\n title: string\n body?: string\n image?: string\n url?: string\n urlMode?: NotificationUrlMode\n metadata?: NotificationMetadataPayload\n data?: NotificationDataPayload\n platform?: NotificationPlatformPayload\n}\n\nexport type CreateNotificationForUserInput = Omit<CreateNotificationInput, \"userId\">\n\nexport type CreateNotificationsForUserInput = {\n userId: string\n notifications: CreateNotificationForUserInput[]\n}\n\nconst normalizeRequiredString = (value: unknown, name: string): string => {\n const normalized = typeof value === \"string\" ? value.trim() : \"\"\n if (!normalized) {\n throw new Error(`${name} is required`)\n }\n return normalized\n}\n\nconst normalizeOptionalString = (value: string | undefined): string | undefined => {\n const normalized = typeof value === \"string\" ? value.trim() : \"\"\n return normalized || undefined\n}\n\nconst normalizeUrlMode = (value: unknown): NotificationUrlMode => {\n return value === \"merge_current_search\" ? \"merge_current_search\" : \"navigate\"\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value)\n\nconst toNotificationDataString = (value: unknown): string | undefined => {\n if (typeof value === \"string\") {\n const trimmed = value.trim()\n return trimmed || undefined\n }\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value)\n if (typeof value === \"boolean\") return String(value)\n if (typeof value === \"bigint\") return value.toString()\n if (value instanceof Date && Number.isFinite(value.getTime())) return value.toISOString()\n return undefined\n}\n\nconst normalizeNotificationActionLink = (url: string | undefined, urlMode: NotificationUrlMode): string | undefined => {\n const normalizedUrl = normalizeOptionalString(url)\n if (!normalizedUrl) return undefined\n if (urlMode === \"navigate\") return normalizedUrl\n\n try {\n const parsed = new URL(normalizedUrl, \"https://rpcbase.local/\")\n return `${parsed.search}${parsed.hash}` || undefined\n } catch {\n return normalizedUrl.startsWith(\"?\") ? normalizedUrl : undefined\n }\n}\n\nconst buildNotificationData = (\n input: Pick<CreateNotificationInput, \"data\" | \"metadata\"> & { link?: string; urlMode: NotificationUrlMode },\n): NotificationDataPayload | undefined => {\n const data: NotificationDataPayload = {}\n\n for (const [key, value] of Object.entries(input.metadata ?? {})) {\n const normalized = toNotificationDataString(value)\n if (normalized) {\n data[key] = normalized\n }\n }\n\n if (input.data) {\n Object.assign(data, input.data)\n }\n\n if (input.link) {\n data.link = input.link\n if (input.urlMode !== \"navigate\") {\n data.linkMode = input.urlMode\n }\n }\n\n return Object.keys(data).length > 0 ? data : undefined\n}\n\nconst buildNotificationPlatform = (\n platform: NotificationPlatformPayload | undefined,\n link: string | undefined,\n): NotificationPlatformPayload | undefined => {\n if (!link) return platform\n\n const webpush = isRecord(platform?.webpush) ? platform.webpush : {}\n const fcmOptions = isRecord(webpush.fcmOptions) ? webpush.fcmOptions : {}\n\n return {\n ...platform,\n webpush: {\n ...webpush,\n fcmOptions: {\n ...fcmOptions,\n link,\n },\n },\n }\n}\n\nconst createNotificationDocument = (input: CreateNotificationInput) => {\n const userId = normalizeRequiredString(input.userId, \"createNotification: userId\")\n const title = normalizeRequiredString(input.title, \"createNotification: title\")\n const topic = normalizeOptionalString(input.topic)\n const body = normalizeOptionalString(input.body)\n const image = normalizeOptionalString(input.image)\n const urlMode = normalizeUrlMode(input.urlMode)\n const link = normalizeNotificationActionLink(input.url, urlMode)\n const data = buildNotificationData({ data: input.data, metadata: input.metadata, link, urlMode })\n const platform = buildNotificationPlatform(input.platform, link)\n\n return {\n userId,\n ...(topic ? { topic } : {}),\n title,\n ...(body ? { body } : {}),\n ...(image ? { image } : {}),\n ...(data ? { data } : {}),\n ...(platform ? { platform } : {}),\n }\n}\n\nconst assertCreateNotificationsForUserInput = (input: CreateNotificationsForUserInput): void => {\n if (typeof input.userId !== \"string\" || input.userId.trim().length === 0) {\n throw new Error(\"createNotificationsForUser: userId is required\")\n }\n if (!Array.isArray(input.notifications)) {\n throw new Error(\"createNotificationsForUser: notifications must be an array\")\n }\n}\n\nexport const createNotification = async (\n ctx: Ctx,\n input: CreateNotificationInput,\n ability: AppAbility,\n): Promise<{ id: string }> => {\n const NotificationModel = await models.get(\"RBNotification\", { req: ctx.req, ability })\n const doc = await NotificationModel.create(createNotificationDocument(input))\n\n return { id: doc._id.toString() }\n}\n\nexport const createNotificationsForUser = async (\n ctx: Ctx,\n input: CreateNotificationsForUserInput,\n ability: AppAbility,\n): Promise<{ ids: string[] }> => {\n assertCreateNotificationsForUserInput(input)\n if (input.notifications.length === 0) {\n return { ids: [] }\n }\n\n const NotificationModel = await models.get(\"RBNotification\", { req: ctx.req, ability })\n const docs = await NotificationModel.create(\n input.notifications.map((notification) =>\n createNotificationDocument({\n ...notification,\n userId: input.userId,\n }),\n ),\n )\n\n return {\n ids: (docs as Array<{ _id: { toString: () => string } }>).map((doc) => doc._id.toString()),\n }\n}\n","import type { Ctx } from \"@rpcbase/api\"\nimport { models, type IRBNotification, type IRBNotificationSettings } from \"@rpcbase/db\"\nimport type { AppAbility } from \"@rpcbase/db/acl\"\n\nimport { sendEmail } from \"../email\"\n\n\nconst DAY_MS = 24 * 60 * 60 * 1000\nconst WEEK_MS = 7 * DAY_MS\n\ntype DigestFrequency = \"off\" | \"daily\" | \"weekly\"\n\ntype NotificationDoc = IRBNotification & { _id: unknown }\ntype SettingsDoc = IRBNotificationSettings & { _id: unknown }\n\nconst getDigestWindowMs = (frequency: DigestFrequency): number => {\n if (frequency === \"daily\") return DAY_MS\n if (frequency === \"weekly\") return WEEK_MS\n return 0\n}\n\nconst formatIso = (value: unknown): string | undefined => {\n if (!(value instanceof Date)) return undefined\n return value.toISOString()\n}\n\nconst getNotificationLink = (notification: NotificationDoc): string => {\n const dataLink = notification.data?.link?.trim()\n if (dataLink) return dataLink\n\n const platform = notification.platform\n if (!platform || typeof platform !== \"object\" || Array.isArray(platform)) return \"\"\n const webpush = (platform as { webpush?: unknown }).webpush\n if (!webpush || typeof webpush !== \"object\" || Array.isArray(webpush)) return \"\"\n const fcmOptions = (webpush as { fcmOptions?: unknown }).fcmOptions\n if (!fcmOptions || typeof fcmOptions !== \"object\" || Array.isArray(fcmOptions)) return \"\"\n const link = (fcmOptions as { link?: unknown }).link\n return typeof link === \"string\" ? link.trim() : \"\"\n}\n\nconst buildPreferencesByTopic = (settings: SettingsDoc | null): Record<string, { emailDigest: boolean }> => {\n const record: Record<string, { emailDigest: boolean }> = {}\n const raw = settings?.topicPreferences\n if (!Array.isArray(raw)) return record\n for (const pref of raw) {\n if (!pref || typeof pref !== \"object\") continue\n const topic = typeof (pref as { topic?: unknown }).topic === \"string\" ? (pref as { topic: string }).topic.trim() : \"\"\n if (!topic) continue\n const emailDigest = (pref as { emailDigest?: unknown }).emailDigest\n record[topic] = { emailDigest: emailDigest === true }\n }\n return record\n}\n\nexport const sendNotificationsDigestForUser = async (\n ctx: Ctx,\n {\n userId,\n ability,\n force = false,\n }: {\n userId: string\n ability: AppAbility\n force?: boolean\n },\n): Promise<{ ok: true; sent: boolean; skippedReason?: string } | { ok: false; error: string }> => {\n const modelCtx = { req: ctx.req, ability }\n const SettingsModel = await models.get(\"RBNotificationSettings\", modelCtx)\n const NotificationModel = await models.get(\"RBNotification\", modelCtx)\n\n const settings = (await SettingsModel.findOne({ userId }).lean()) as SettingsDoc | null\n\n const digestFrequencyRaw = typeof settings?.digestFrequency === \"string\" ? settings.digestFrequency : \"weekly\"\n const digestFrequency: DigestFrequency =\n digestFrequencyRaw === \"daily\" || digestFrequencyRaw === \"weekly\" || digestFrequencyRaw === \"off\"\n ? digestFrequencyRaw\n : \"weekly\"\n\n if (digestFrequency === \"off\") {\n return { ok: true, sent: false, skippedReason: \"digest_off\" }\n }\n\n const now = new Date()\n const windowMs = getDigestWindowMs(digestFrequency)\n const lastSentAt = settings?.lastDigestSentAt instanceof Date ? settings.lastDigestSentAt : null\n const since = lastSentAt ?? new Date(now.getTime() - windowMs)\n\n if (!force && lastSentAt && now.getTime() - lastSentAt.getTime() < windowMs) {\n return { ok: true, sent: false, skippedReason: \"not_due\" }\n }\n\n const preferencesByTopic = buildPreferencesByTopic(settings)\n const disabledTopics = Object.entries(preferencesByTopic)\n .filter(([, pref]) => pref.emailDigest === false)\n .map(([topic]) => topic)\n\n const query: Record<string, unknown> = {\n userId,\n archivedAt: { $exists: false },\n readAt: { $exists: false },\n createdAt: { $gt: since },\n }\n\n if (disabledTopics.length > 0) {\n query.topic = { $nin: disabledTopics }\n }\n\n const notifications = (await NotificationModel.find(query)\n .sort({ createdAt: -1 })\n .limit(50)\n .lean()) as NotificationDoc[]\n\n if (!notifications.length) {\n await SettingsModel.updateOne(\n { userId },\n { $set: { lastDigestSentAt: now }, $setOnInsert: { userId, digestFrequency: \"weekly\" } },\n { upsert: true },\n )\n return { ok: true, sent: false, skippedReason: \"empty\" }\n }\n\n const UserModel = await models.getGlobal(\"RBUser\", ctx)\n const user = (await UserModel.findById(userId, { email: 1 }).lean()) as { email?: unknown } | null\n const email = typeof user?.email === \"string\" ? user.email.trim() : \"\"\n if (!email) {\n return { ok: true, sent: false, skippedReason: \"missing_email\" }\n }\n\n const subject = \"Notifications digest\"\n const rows = notifications\n .map((n) => {\n const title = typeof n.title === \"string\" ? n.title : \"\"\n const body = typeof n.body === \"string\" ? n.body : \"\"\n const url = getNotificationLink(n)\n const createdAt = formatIso(n.createdAt) ?? \"\"\n const line = url\n ? `<li><strong>${title}</strong><br>${body}<br><a href=\"${url}\">${url}</a><br><small>${createdAt}</small></li>`\n : `<li><strong>${title}</strong><br>${body}<br><small>${createdAt}</small></li>`\n return line\n })\n .join(\"\")\n\n const html = `<div><p>Here is your notifications digest:</p><ul>${rows}</ul></div>`\n\n const emailResult = await sendEmail({ to: email, subject, html })\n if (emailResult.error) {\n return { ok: false, error: emailResult.error }\n }\n\n await SettingsModel.updateOne(\n { userId },\n { $set: { lastDigestSentAt: now }, $setOnInsert: { userId, digestFrequency: \"weekly\" } },\n { upsert: true },\n )\n\n return { ok: true, sent: emailResult.skipped !== true, ...(emailResult.skipped ? { skippedReason: \"email_skipped\" } : {}) }\n}\n"],"names":["routes","Object","entries","import","reduce","acc","path","mod","replace","normalizeRequiredString","value","name","normalized","trim","Error","normalizeOptionalString","undefined","normalizeUrlMode","isRecord","Boolean","Array","isArray","toNotificationDataString","trimmed","Number","isFinite","String","toString","Date","getTime","toISOString","normalizeNotificationActionLink","url","urlMode","normalizedUrl","parsed","URL","search","hash","startsWith","buildNotificationData","input","data","key","metadata","assign","link","linkMode","keys","length","buildNotificationPlatform","platform","webpush","fcmOptions","createNotificationDocument","userId","title","topic","body","image","assertCreateNotificationsForUserInput","notifications","createNotification","ctx","ability","NotificationModel","models","get","req","doc","create","id","_id","createNotificationsForUser","ids","docs","map","notification","DAY_MS","WEEK_MS","getDigestWindowMs","frequency","formatIso","getNotificationLink","dataLink","buildPreferencesByTopic","settings","record","raw","topicPreferences","pref","emailDigest","sendNotificationsDigestForUser","force","modelCtx","SettingsModel","findOne","lean","digestFrequencyRaw","digestFrequency","ok","sent","skippedReason","now","windowMs","lastSentAt","lastDigestSentAt","since","preferencesByTopic","disabledTopics","filter","query","archivedAt","$exists","readAt","createdAt","$gt","$nin","find","sort","limit","updateOne","$set","$setOnInsert","upsert","UserModel","getGlobal","user","findById","email","subject","rows","n","line","join","html","emailResult","sendEmail","to","error","skipped"],"mappings":";;AAAO,MAAMA,SAASC,OAAOC,QAAQ;AAAA,EACnC,GAAGC,uBAAAA,OAAAA,EAAAA,kCAAAA,MAAAA,OAAAA,uBAAAA,EAAAA,CAAAA;AACL,CAAC,EAAEC,OAAgC,CAACC,KAAK,CAACC,MAAMC,GAAG,MAAM;AACvDF,MAAIC,KAAKE,QAAQ,UAAU,oCAAoC,CAAC,IAAID;AACpE,SAAOF;AACT,GAAG,CAAA,CAAE;ACyBL,MAAMI,0BAA0BA,CAACC,OAAgBC,SAAyB;AACxE,QAAMC,aAAa,OAAOF,UAAU,WAAWA,MAAMG,SAAS;AAC9D,MAAI,CAACD,YAAY;AACf,UAAM,IAAIE,MAAM,GAAGH,IAAI,cAAc;AAAA,EACvC;AACA,SAAOC;AACT;AAEA,MAAMG,0BAA0BA,CAACL,UAAkD;AACjF,QAAME,aAAa,OAAOF,UAAU,WAAWA,MAAMG,SAAS;AAC9D,SAAOD,cAAcI;AACvB;AAEA,MAAMC,mBAAmBA,CAACP,UAAwC;AAChE,SAAOA,UAAU,yBAAyB,yBAAyB;AACrE;AAEA,MAAMQ,WAAWA,CAACR,UAChBS,QAAQT,KAAK,KAAK,OAAOA,UAAU,YAAY,CAACU,MAAMC,QAAQX,KAAK;AAErE,MAAMY,2BAA2BA,CAACZ,UAAuC;AACvE,MAAI,OAA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AAe;AAAA,IAAA,IAAoB,CAAA;AAAA,EAAC;AACzH;"}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"handler-VRU-2kj6.js","sources":["../src/notifications/api/notifications/shared.ts","../src/notifications/api/notifications/index.ts","../src/notifications/api/notifications/handler.ts"],"sourcesContent":["import type { Ctx } from \"@rpcbase/api\"\n\n\ntype NotificationSessionUser = {\n id?: unknown\n currentTenantId?: unknown\n}\n\nexport const getSessionUser = (ctx: Ctx) => {\n const rawSessionUser = (ctx.req.session as { user?: NotificationSessionUser } | null | undefined)?.user\n const userId = typeof rawSessionUser?.id === \"string\" ? rawSessionUser.id.trim() : \"\"\n const tenantId = typeof rawSessionUser?.currentTenantId === \"string\" ? rawSessionUser.currentTenantId.trim() : \"\"\n\n if (!userId) {\n ctx.res.status(401)\n return null\n }\n\n if (!tenantId) {\n ctx.res.status(400)\n return null\n }\n\n return { userId, tenantId }\n}\n\n","import { z } from \"zod\"\n\n\nexport const ListRoute = \"/api/rb/notifications\"\nexport const CreateRoute = \"/api/rb/notifications/create\"\nexport const MarkReadRoute = \"/api/rb/notifications/:notificationId/read\"\nexport const ArchiveRoute = \"/api/rb/notifications/:notificationId/archive\"\nexport const MarkAllReadRoute = \"/api/rb/notifications/mark-all-read\"\nexport const SettingsRoute = \"/api/rb/notifications/settings\"\nexport const DigestRunRoute = \"/api/rb/notifications/digest/run\"\n\nexport const listRequestSchema = z.object({\n includeArchived: z.boolean().optional(),\n unreadOnly: z.boolean().optional(),\n limit: z.number().int().min(1).max(200).optional(),\n markSeen: z.boolean().optional(),\n})\n\nexport type ListRequestPayload = z.infer<typeof listRequestSchema>\n\nexport const notificationDataSchema = z.record(z.string(), z.string())\n\nexport const notificationPlatformPayloadSchema = z.object({\n webpush: z.record(z.string(), z.unknown()).optional(),\n fcmOptions: z.record(z.string(), z.unknown()).optional(),\n android: z.record(z.string(), z.unknown()).optional(),\n apns: z.record(z.string(), z.unknown()).optional(),\n}).passthrough()\n\nexport type NotificationPlatformPayload = z.infer<typeof notificationPlatformPayloadSchema>\n\nconst createRequestStringSchema = z.string().trim()\n\nexport const notificationContentFieldsSchema = z.object({\n title: z.string().min(1),\n body: z.string().optional(),\n image: z.string().optional(),\n})\n\nexport const createRequestSchema = z.object({\n topic: createRequestStringSchema.min(1).optional(),\n title: createRequestStringSchema.min(1),\n body: createRequestStringSchema.optional(),\n image: createRequestStringSchema.optional(),\n data: notificationDataSchema.optional(),\n platform: notificationPlatformPayloadSchema.optional(),\n})\n\nexport type CreateRequestPayload = z.infer<typeof createRequestSchema>\n\nexport const notificationSchema = z.object({\n id: z.string(),\n topic: z.string().optional(),\n title: notificationContentFieldsSchema.shape.title,\n body: notificationContentFieldsSchema.shape.body,\n image: notificationContentFieldsSchema.shape.image,\n data: notificationDataSchema.optional(),\n platform: notificationPlatformPayloadSchema.optional(),\n createdAt: z.string(),\n seenAt: z.string().optional(),\n readAt: z.string().optional(),\n archivedAt: z.string().optional(),\n})\n\nexport type NotificationPayload = z.infer<typeof notificationSchema>\n\nexport const listResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n notifications: z.array(notificationSchema).optional(),\n unreadCount: z.number().int().min(0).optional(),\n unseenCount: z.number().int().min(0).optional(),\n})\n\nexport type ListResponsePayload = z.infer<typeof listResponseSchema>\n\nexport const createResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n id: z.string().optional(),\n})\n\nexport type CreateResponsePayload = z.infer<typeof createResponseSchema>\n\nexport const markReadResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n})\n\nexport type MarkReadResponsePayload = z.infer<typeof markReadResponseSchema>\n\nexport const archiveResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n})\n\nexport type ArchiveResponsePayload = z.infer<typeof archiveResponseSchema>\n\nexport const markAllReadResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n})\n\nexport type MarkAllReadResponsePayload = z.infer<typeof markAllReadResponseSchema>\n\nexport const digestFrequencySchema = z.enum([\"off\", \"daily\", \"weekly\"])\n\nexport type DigestFrequency = z.infer<typeof digestFrequencySchema>\n\nexport const topicPreferenceSchema = z.object({\n topic: z.string(),\n inApp: z.boolean(),\n emailDigest: z.boolean(),\n push: z.boolean(),\n})\n\nexport type TopicPreferencePayload = z.infer<typeof topicPreferenceSchema>\n\nexport const settingsSchema = z.object({\n digestFrequency: digestFrequencySchema,\n topicPreferences: z.array(topicPreferenceSchema),\n lastDigestSentAt: z.string().optional(),\n})\n\nexport type SettingsPayload = z.infer<typeof settingsSchema>\n\nexport const settingsResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n settings: settingsSchema.optional(),\n})\n\nexport type SettingsResponsePayload = z.infer<typeof settingsResponseSchema>\n\nexport const updateSettingsRequestSchema = z.object({\n digestFrequency: digestFrequencySchema.optional(),\n topicPreferences: z.array(topicPreferenceSchema).optional(),\n})\n\nexport type UpdateSettingsRequestPayload = z.infer<typeof updateSettingsRequestSchema>\n\nexport const updateSettingsResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n settings: settingsSchema.optional(),\n})\n\nexport type UpdateSettingsResponsePayload = z.infer<typeof updateSettingsResponseSchema>\n\nexport const digestRunRequestSchema = z.object({\n force: z.boolean().optional(),\n})\n\nexport type DigestRunRequestPayload = z.infer<typeof digestRunRequestSchema>\n\nexport const digestRunResponseSchema = z.object({\n ok: z.boolean(),\n error: z.string().optional(),\n sent: z.boolean().optional(),\n skippedReason: z.string().optional(),\n})\n\nexport type DigestRunResponsePayload = z.infer<typeof digestRunResponseSchema>\n","import { Api, type ApiHandler } from \"@rpcbase/api\"\nimport { models, type IRBNotification, type IRBNotificationSettings } from \"@rpcbase/db\"\nimport { buildAbilityFromSession, getAccessibleByQuery } from \"@rpcbase/db/acl\"\n\nimport { createNotification } from \"../../createNotification\"\nimport { sendNotificationsDigestForUser } from \"../../digest\"\nimport { getSessionUser } from \"./shared\"\n\nimport * as Notifications from \"./index\"\n\n\ntype NotificationDoc = IRBNotification & { _id: unknown }\ntype SettingsDoc = IRBNotificationSettings & { _id: unknown }\n\nconst toIso = (value: unknown): string | undefined => (value instanceof Date ? value.toISOString() : undefined)\nconst isRecord = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === \"object\" && !Array.isArray(value)\n\nconst toStringMap = (value: unknown): Record<string, string> | undefined => {\n if (!isRecord(value)) return undefined\n const entries = Object.entries(value)\n .filter((entry): entry is [string, string] => typeof entry[1] === \"string\")\n return entries.length > 0 ? Object.fromEntries(entries) : undefined\n}\n\nconst buildDisabledTopics = (\n settings: SettingsDoc | null,\n key: \"inApp\" | \"emailDigest\",\n): string[] => {\n const raw = settings?.topicPreferences\n if (!Array.isArray(raw) || raw.length === 0) return []\n\n return raw\n .map((pref) => {\n if (!pref || typeof pref !== \"object\") return null\n const topic = typeof (pref as { topic?: unknown }).topic === \"string\" ? (pref as { topic: string }).topic.trim() : \"\"\n if (!topic) return null\n const enabled = (pref as Record<string, unknown>)[key] === true\n return enabled ? null : topic\n })\n .filter((topic): topic is string => Boolean(topic))\n}\n\nconst listNotifications: ApiHandler<Notifications.ListRequestPayload, Notifications.ListResponsePayload> = async(\n payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"read\", \"RBNotification\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const parsed = Notifications.listRequestSchema.safeParse(payload)\n if (!parsed.success) {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_payload\" }\n }\n\n const { userId } = session\n const includeArchived = parsed.data.includeArchived === true\n const unreadOnly = parsed.data.unreadOnly === true\n const limit = parsed.data.limit ?? 50\n const markSeen = parsed.data.markSeen === true\n\n const SettingsModel = await models.get(\"RBNotificationSettings\", { req: ctx.req, ability })\n const settings = (await SettingsModel.findOne({ userId }).lean()) as SettingsDoc | null\n const disabledTopics = buildDisabledTopics(settings, \"inApp\")\n\n const NotificationModel = await models.get(\"RBNotification\", { req: ctx.req, ability })\n\n const queryFilters: Record<string, unknown>[] = [\n { userId },\n getAccessibleByQuery(ability, \"read\", \"RBNotification\"),\n ]\n if (!includeArchived) queryFilters.push({ archivedAt: { $exists: false } })\n if (unreadOnly) queryFilters.push({ readAt: { $exists: false } })\n if (disabledTopics.length > 0) queryFilters.push({ topic: { $nin: disabledTopics } })\n const query: Record<string, unknown> = { $and: queryFilters }\n\n const notifications = (await NotificationModel.find(query)\n .sort({ createdAt: -1 })\n .limit(limit)\n .lean()) as NotificationDoc[]\n\n const unseenQueryFilters: Record<string, unknown>[] = [\n { userId },\n { archivedAt: { $exists: false } },\n { seenAt: { $exists: false } },\n getAccessibleByQuery(ability, \"read\", \"RBNotification\"),\n ]\n if (disabledTopics.length > 0) unseenQueryFilters.push({ topic: { $nin: disabledTopics } })\n const unseenQuery: Record<string, unknown> = { $and: unseenQueryFilters }\n\n const unreadQueryFilters: Record<string, unknown>[] = [\n { userId },\n { archivedAt: { $exists: false } },\n { readAt: { $exists: false } },\n getAccessibleByQuery(ability, \"read\", \"RBNotification\"),\n ]\n if (disabledTopics.length > 0) unreadQueryFilters.push({ topic: { $nin: disabledTopics } })\n const unreadQuery: Record<string, unknown> = { $and: unreadQueryFilters }\n\n const [unreadCount, unseenCount] = await Promise.all([\n NotificationModel.countDocuments(unreadQuery),\n NotificationModel.countDocuments(unseenQuery),\n ])\n\n const now = markSeen ? new Date() : null\n if (now && unseenCount > 0) {\n await NotificationModel.updateMany(unseenQuery, { $set: { seenAt: now } })\n }\n\n return Notifications.listResponseSchema.parse({\n ok: true,\n notifications: notifications.map((n) => ({\n id: String(n._id),\n topic: typeof n.topic === \"string\" ? n.topic : undefined,\n title: typeof n.title === \"string\" ? n.title : \"\",\n body: typeof n.body === \"string\" ? n.body : undefined,\n image: typeof n.image === \"string\" ? n.image : undefined,\n data: toStringMap(n.data),\n platform: isRecord(n.platform) ? n.platform : undefined,\n createdAt: toIso(n.createdAt) ?? new Date().toISOString(),\n seenAt: toIso(n.seenAt) ?? (now && !n.archivedAt && !n.seenAt ? now.toISOString() : undefined),\n readAt: toIso(n.readAt),\n archivedAt: toIso(n.archivedAt),\n })),\n unreadCount,\n unseenCount: now ? 0 : unseenCount,\n })\n}\n\nconst createNotificationForCurrentUser: ApiHandler<Notifications.CreateRequestPayload, Notifications.CreateResponsePayload> = async(\n payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"create\", \"RBNotification\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const parsed = Notifications.createRequestSchema.safeParse(payload)\n if (!parsed.success) {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_payload\" }\n }\n\n const created = await createNotification(ctx, {\n userId: session.userId,\n topic: parsed.data.topic,\n title: parsed.data.title,\n body: parsed.data.body,\n image: parsed.data.image,\n data: parsed.data.data,\n platform: parsed.data.platform,\n }, ability)\n\n return Notifications.createResponseSchema.parse({ ok: true, id: created.id })\n}\n\nconst markRead: ApiHandler<unknown, Notifications.MarkReadResponsePayload> = async(\n _payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"update\", \"RBNotification\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const notificationId = typeof ctx.req.params.notificationId === \"string\" ? ctx.req.params.notificationId.trim() : \"\"\n if (!notificationId) {\n ctx.res.status(400)\n return { ok: false, error: \"missing_notification_id\" }\n }\n\n const NotificationModel = await models.get(\"RBNotification\", { req: ctx.req, ability })\n const now = new Date()\n\n try {\n await NotificationModel.updateOne(\n { $and: [{ _id: notificationId }, { archivedAt: { $exists: false } }, getAccessibleByQuery(ability, \"update\", \"RBNotification\")] },\n { $set: { readAt: now, seenAt: now } },\n )\n } catch {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_notification_id\" }\n }\n\n return { ok: true }\n}\n\nconst markAllRead: ApiHandler<unknown, Notifications.MarkAllReadResponsePayload> = async(\n _payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"update\", \"RBNotification\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const SettingsModel = await models.get(\"RBNotificationSettings\", { req: ctx.req, ability })\n const settings = (await SettingsModel.findOne({ userId: session.userId }).lean()) as SettingsDoc | null\n const disabledTopics = buildDisabledTopics(settings, \"inApp\")\n\n const NotificationModel = await models.get(\"RBNotification\", { req: ctx.req, ability })\n\n const queryFilters: Record<string, unknown>[] = [\n { userId: session.userId },\n { archivedAt: { $exists: false } },\n { readAt: { $exists: false } },\n getAccessibleByQuery(ability, \"update\", \"RBNotification\"),\n ]\n if (disabledTopics.length > 0) queryFilters.push({ topic: { $nin: disabledTopics } })\n const query: Record<string, unknown> = { $and: queryFilters }\n\n const now = new Date()\n await NotificationModel.updateMany(query, { $set: { readAt: now, seenAt: now } })\n\n return { ok: true }\n}\n\nconst archiveNotification: ApiHandler<unknown, Notifications.ArchiveResponsePayload> = async(\n _payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"update\", \"RBNotification\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const notificationId = typeof ctx.req.params.notificationId === \"string\" ? ctx.req.params.notificationId.trim() : \"\"\n if (!notificationId) {\n ctx.res.status(400)\n return { ok: false, error: \"missing_notification_id\" }\n }\n\n const NotificationModel = await models.get(\"RBNotification\", { req: ctx.req, ability })\n\n try {\n await NotificationModel.updateOne(\n { $and: [{ _id: notificationId }, { archivedAt: { $exists: false } }, getAccessibleByQuery(ability, \"update\", \"RBNotification\")] },\n { $set: { archivedAt: new Date() } },\n )\n } catch {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_notification_id\" }\n }\n\n return { ok: true }\n}\n\nconst getSettings: ApiHandler<unknown, Notifications.SettingsResponsePayload> = async(\n _payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"read\", \"RBNotificationSettings\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const SettingsModel = await models.get(\"RBNotificationSettings\", { req: ctx.req, ability })\n const settings = (await SettingsModel.findOne(\n { $and: [{ userId: session.userId }, getAccessibleByQuery(ability, \"read\", \"RBNotificationSettings\")] },\n ).lean()) as SettingsDoc | null\n\n const digestFrequencyRaw = typeof settings?.digestFrequency === \"string\" ? settings.digestFrequency : \"weekly\"\n const digestFrequency: Notifications.DigestFrequency =\n digestFrequencyRaw === \"off\" || digestFrequencyRaw === \"daily\" || digestFrequencyRaw === \"weekly\"\n ? digestFrequencyRaw\n : \"weekly\"\n\n const topicPreferences = Array.isArray(settings?.topicPreferences)\n ? settings!.topicPreferences.map((pref) => ({\n topic: typeof pref.topic === \"string\" ? pref.topic : \"\",\n inApp: pref.inApp === true,\n emailDigest: pref.emailDigest === true,\n push: pref.push === true,\n })).filter((pref) => pref.topic.length > 0)\n : []\n\n return Notifications.settingsResponseSchema.parse({\n ok: true,\n settings: {\n digestFrequency,\n topicPreferences,\n lastDigestSentAt: toIso(settings?.lastDigestSentAt),\n },\n })\n}\n\nconst updateSettings: ApiHandler<Notifications.UpdateSettingsRequestPayload, Notifications.UpdateSettingsResponsePayload> = async(\n payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"update\", \"RBNotificationSettings\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const parsed = Notifications.updateSettingsRequestSchema.safeParse(payload)\n if (!parsed.success) {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_payload\" }\n }\n\n const SettingsModel = await models.get(\"RBNotificationSettings\", { req: ctx.req, ability })\n const nextValues: Record<string, unknown> = {}\n\n if (parsed.data.digestFrequency) {\n nextValues.digestFrequency = parsed.data.digestFrequency\n }\n\n if (parsed.data.topicPreferences) {\n const seen = new Set<string>()\n const next = parsed.data.topicPreferences\n .map((pref) => ({\n topic: pref.topic.trim(),\n inApp: pref.inApp,\n emailDigest: pref.emailDigest,\n push: pref.push,\n }))\n .filter((pref) => pref.topic.length > 0)\n .filter((pref) => {\n if (seen.has(pref.topic)) return false\n seen.add(pref.topic)\n return true\n })\n\n nextValues.topicPreferences = next\n }\n\n const ops: Record<string, unknown> = {\n $setOnInsert: { userId: session.userId },\n }\n\n if (Object.keys(nextValues).length > 0) {\n ops.$set = nextValues\n }\n\n const settings = (await SettingsModel.findOneAndUpdate(\n { $and: [{ userId: session.userId }, getAccessibleByQuery(ability, \"update\", \"RBNotificationSettings\")] },\n ops,\n { upsert: true, returnDocument: \"after\", setDefaultsOnInsert: true },\n ).lean()) as SettingsDoc | null\n\n const digestFrequencyRaw = typeof settings?.digestFrequency === \"string\" ? settings.digestFrequency : \"weekly\"\n const digestFrequency: Notifications.DigestFrequency =\n digestFrequencyRaw === \"off\" || digestFrequencyRaw === \"daily\" || digestFrequencyRaw === \"weekly\"\n ? digestFrequencyRaw\n : \"weekly\"\n\n const topicPreferences = Array.isArray(settings?.topicPreferences)\n ? settings!.topicPreferences.map((pref) => ({\n topic: typeof pref.topic === \"string\" ? pref.topic : \"\",\n inApp: pref.inApp === true,\n emailDigest: pref.emailDigest === true,\n push: pref.push === true,\n })).filter((pref) => pref.topic.length > 0)\n : []\n\n return Notifications.updateSettingsResponseSchema.parse({\n ok: true,\n settings: {\n digestFrequency,\n topicPreferences,\n lastDigestSentAt: toIso(settings?.lastDigestSentAt),\n },\n })\n}\n\nconst runDigest: ApiHandler<Notifications.DigestRunRequestPayload, Notifications.DigestRunResponsePayload> = async(\n payload,\n ctx,\n) => {\n const session = getSessionUser(ctx)\n if (!session) {\n return { ok: false, error: \"unauthorized\" }\n }\n\n const ability = buildAbilityFromSession({ tenantId: session.tenantId, session: ctx.req.session })\n if (!ability.can(\"read\", \"RBNotification\")) {\n ctx.res.status(403)\n return { ok: false, error: \"forbidden\" }\n }\n\n const parsed = Notifications.digestRunRequestSchema.safeParse(payload)\n if (!parsed.success) {\n ctx.res.status(400)\n return { ok: false, error: \"invalid_payload\" }\n }\n\n const result = await sendNotificationsDigestForUser(ctx, {\n userId: session.userId,\n ability,\n force: parsed.data.force === true,\n })\n\n if (!result.ok) {\n ctx.res.status(500)\n return { ok: false, error: result.error }\n }\n\n return {\n ok: true,\n sent: result.sent,\n ...(result.skippedReason ? { skippedReason: result.skippedReason } : {}),\n }\n}\n\nexport default (api: Api) => {\n api.post(Notifications.ListRoute, listNotifications)\n api.post(Notifications.CreateRoute, createNotificationForCurrentUser)\n api.post(Notifications.MarkReadRoute, markRead)\n api.post(Notifications.MarkAllReadRoute, markAllRead)\n api.post(Notifications.ArchiveRoute, archiveNotification)\n api.get(Notifications.SettingsRoute, getSettings)\n api.put(Notifications.SettingsRoute, updateSettings)\n api.post(Notifications.DigestRunRoute, runDigest)\n}\n"],"names":["getSessionUser","ctx","rawSessionUser","req","session","user","userId","id","trim","tenantId","currentTenantId","res","status","ListRoute","CreateRoute","MarkReadRoute","ArchiveRoute","MarkAllReadRoute","SettingsRoute","DigestRunRoute","listRequestSchema","z","includeArchived","boolean","optional","unreadOnly","limit","int","min","max","markSeen","notificationDataSchema","notificationPlatformPayloadSchema","webpush","string","unknown","fcmOptions","android","apns","passthrough","createRequestStringSchema","notificationContentFieldsSchema","title","body","image","createRequestSchema","topic","data","platform","notificationSchema","shape","createdAt","seenAt","readAt","archivedAt","listResponseSchema","ok","error","notifications","unreadCount","number","unseenCount","createResponseSchema","digestFrequencySchema","topicPreferenceSchema","inApp","emailDigest","push","settingsSchema","digestFrequency","topicPreferences","lastDigestSentAt","settingsResponseSchema","settings","updateSettingsRequestSchema","updateSettingsResponseSchema","digestRunRequestSchema","force","sent","skippedReason","toIso","value","Date","toISOString","undefined","isRecord","Boolean","Array","isArray","toStringMap","entries","Object","filter","entry","length","fromEntries","buildDisabledTopics","key","raw","map","pref","enabled","listNotifications","payload","ability","buildAbilityFromSession","can","parsed","Notifications","safeParse","success","SettingsModel","models","get","findOne","lean","disabledTopics","NotificationModel","queryFilters","getAccessibleByQuery","$exists","$nin","query","$and","find","sort","unseenQueryFilters","unseenQuery","unreadQueryFilters","unreadQuery","Promise","all","countDocuments","now","updateMany","$set","parse","n","String","_id","createNotificationForCurrentUser","created","createNotification","markRead","_payload","notificationId","params","updateOne","markAllRead","archiveNotification","getSettings","digestFrequencyRaw","updateSettings","nextValues","seen","Set","next","has","add","ops","$setOnInsert","keys","findOneAndUpdate","upsert","returnDocument","setDefaultsOnInsert","runDigest","result","sendNotificationsDigestForUser","api","post","put"],"mappings":";;;;AAQO,MAAMA,iBAAiBA,CAACC,QAAa;AAC1C,QAAMC,iBAAkBD,IAAIE,IAAIC,SAAmEC;AACnG,QAAMC,SAAS,OAAOJ,gBAAgBK,OAAO,WAAWL,eAAeK,GAAGC,SAAS;AACnF,QAAMC,WAAW,OAAOP,gBAAgBQ,oBAAoB,WAAWR,eAAeQ,gBAAgBF,SAAS;AAE/G,MAAI,CAACF,QAAQ;AACXL,QAAIU,IAAIC,OAAO,GAAG;AAClB,WAAO;AAAA,EACT;A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