import type { JsonValue } from "./errors.js"; export type NotificationInput = { tenantId: string; userId?: string | null; channel?: NotificationPreferenceChannel; category?: string | null; messageKey: string; sourceKey?: string | null; payloadMetadata?: Record | null; }; export type NotificationPreferenceChannel = "IN_APP" | "EMAIL"; export type NotificationDeliveryStatus = "PENDING" | "SENT" | "FAILED" | "SKIPPED" | "READ"; export type NotificationPayloadMetadata = Record; export type NotificationPreference = { tenantId: string; userId: string; channel: NotificationPreferenceChannel; category: string; enabled: boolean; }; export type NotificationBundle = { tenantId: string; userId: string | null; channel: NotificationPreferenceChannel; category: string; messageKeys: readonly string[]; payloadMetadata: Record; }; export type NotificationClient = { notificationDelivery: { create(args: { data: { tenantId: string | null; userId: string | null; channel: NotificationPreferenceChannel; category: string; messageKey: string; sourceKey: string | null; status: NotificationDeliveryStatus; attemptsMade: number; providerMessageId: string | null; lastError: string | null; payloadMetadata: NotificationPayloadMetadata | null; sentAt: Date | null; readAt: Date | null; }; }): Promise; upsert?(args: { where: { tenantId_userId_channel_sourceKey: { tenantId: string; userId: string; channel: NotificationPreferenceChannel; sourceKey: string; }; }; create: { tenantId: string | null; userId: string | null; channel: NotificationPreferenceChannel; category: string; messageKey: string; sourceKey: string | null; status: NotificationDeliveryStatus; attemptsMade: number; providerMessageId: string | null; lastError: string | null; payloadMetadata: NotificationPayloadMetadata | null; sentAt: Date | null; readAt: Date | null; }; update: { category: string; messageKey: string; status: NotificationDeliveryStatus; attemptsMade: number; providerMessageId: string | null; lastError: string | null; payloadMetadata: NotificationPayloadMetadata | null; sentAt: Date | null; readAt: Date | null; }; }): Promise; }; }; export async function notify(input: NotificationInput, client: NotificationClient, preferences: readonly NotificationPreference[] = []): Promise { const tenantId = requireNotificationTenantScope(input.tenantId); const enabled = isNotificationEnabled(input, preferences); const channel = input.channel ?? "IN_APP"; const userId = input.userId ?? null; const sourceKey = normalizeNotificationSourceKey(input.sourceKey); const data = { tenantId, userId, channel, category: normalizeNotificationCategory(input.category), messageKey: input.messageKey, sourceKey, status: enabled ? channel === "IN_APP" ? "SENT" as const : "PENDING" as const : "SKIPPED" as const, attemptsMade: enabled && channel === "IN_APP" ? 1 : 0, providerMessageId: null, lastError: enabled ? null : "preference_disabled", payloadMetadata: sanitizeNotificationPayloadMetadata(input.payloadMetadata), sentAt: enabled && channel === "IN_APP" ? new Date() : null, readAt: null, }; if (sourceKey && userId && client.notificationDelivery.upsert) { return client.notificationDelivery.upsert({ where: { tenantId_userId_channel_sourceKey: { tenantId, userId, channel, sourceKey, }, }, create: data, update: { category: data.category, messageKey: data.messageKey, status: data.status, attemptsMade: data.attemptsMade, providerMessageId: data.providerMessageId, lastError: data.lastError, payloadMetadata: data.payloadMetadata, sentAt: data.sentAt, readAt: data.readAt, }, }); } return client.notificationDelivery.create({ data }); } export function isNotificationEnabled(input: NotificationInput, preferences: readonly NotificationPreference[]): boolean { const tenantId = requireNotificationTenantScope(input.tenantId); const userId = input.userId ?? null; const channel = input.channel ?? "IN_APP"; const category = normalizeNotificationCategory(input.category); const scopedPreferences = preferences.filter( (candidate) => candidate.tenantId === tenantId && candidate.userId === userId && candidate.channel === channel, ); const preference = scopedPreferences.find((candidate) => candidate.category === category) ?? scopedPreferences.find((candidate) => candidate.category === "default"); return preference?.enabled ?? true; } export function bundleNotifications(inputs: readonly NotificationInput[]): readonly NotificationBundle[] { const bundles = new Map }>(); for (const input of inputs) { const tenantId = requireNotificationTenantScope(input.tenantId); const userId = input.userId ?? null; const channel = input.channel ?? "IN_APP"; const category = normalizeNotificationCategory(input.category); const key = [tenantId ?? "", userId ?? "", channel, category].join(":"); const existing = bundles.get(key) ?? { tenantId, userId, channel, category, messageKeys: [], payloadMetadata: {}, }; existing.messageKeys.push(input.messageKey); if (input.payloadMetadata) { Object.assign(existing.payloadMetadata, sanitizeNotificationPayloadMetadata(input.payloadMetadata) ?? {}); } bundles.set(key, existing); } return [...bundles.values()].map((bundle) => ({ ...bundle, messageKeys: [...new Set(bundle.messageKeys)], })); } function normalizeNotificationCategory(category: string | null | undefined) { return category?.trim().toLowerCase() || "default"; } function normalizeNotificationSourceKey(sourceKey: string | null | undefined): string | null { const normalized = sourceKey?.trim(); return normalized ? normalized : null; } function requireNotificationTenantScope(tenantId: string | null | undefined): string { const normalized = tenantId?.trim(); if (!normalized) { throw new Error("Notification delivery tenant scope is required."); } return normalized; } const SENSITIVE_NOTIFICATION_METADATA_KEY_PATTERN = /authorization|cookie|password|secret|token|api[-_]?key|payload|body|header/i; const NOTIFICATION_PAYLOAD_METADATA_STRING_MAX_LENGTH = 500; function sanitizeNotificationPayloadMetadata(payloadMetadata?: Record | null): NotificationPayloadMetadata | null { if (!payloadMetadata) { return null; } const sanitized: NotificationPayloadMetadata = {}; for (const [rawKey, value] of Object.entries(payloadMetadata)) { const key = rawKey.trim(); if (!key) { continue; } if (SENSITIVE_NOTIFICATION_METADATA_KEY_PATTERN.test(key)) { sanitized[key] = "[redacted]"; } else if (typeof value === "string") { sanitized[key] = value.slice(0, NOTIFICATION_PAYLOAD_METADATA_STRING_MAX_LENGTH); } else if (typeof value === "number" && Number.isFinite(value)) { sanitized[key] = value; } else if (typeof value === "boolean" || value === null) { sanitized[key] = value; } } return Object.keys(sanitized).length > 0 ? sanitized : null; } export async function notifyMany( inputs: readonly NotificationInput[], client: NotificationClient, preferences: readonly NotificationPreference[] = [], ): Promise { return Promise.all(inputs.map((input) => notify(input, client, preferences))); } export function assertI18nKey(key: string): string { if (!/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/.test(key)) { throw new Error(`Invalid i18n key: ${key}`); } return key; }