import { log } from '@stacksjs/cli' import { config as appConfig, notification as _notification } from '@stacksjs/config' import type { ChatMessage, ChatResult, EmailMessage, EmailResult, NotificationOptions, SmsMessage, SmsSendResult } from '@stacksjs/types' import { mail } from '@stacksjs/email' import { chat, email, push, sms } from './drivers' import { BroadcastNotificationDriver } from './drivers/broadcast' import { DatabaseNotificationDriver } from './drivers/database' import { makeDeliveryRecord, recordNotificationDelivery } from './delivery' import { type NotificationAction, type NotificationEmailTemplate, type NotificationFrameLocale, type NotificationUnsubscribe, notificationEmailMessage, notificationSmsBody } from './email-body' import { filterChannelsByPreferences } from './preferences' const config = _notification as NotificationOptions | undefined export type NotificationChannel = 'email' | 'sms' | 'chat' | 'database' | 'push' | 'broadcast' /** Optional flags accepted by {@link notify}. */ export interface NotifyOptions { /** * Skip the user-preference filter (the `notification_preferences` rows, * including category unsubscribes). Use for transactional notifications a * user cannot switch off in the app (password resets, security alerts, * billing failures). It does NOT bypass legal opt-outs: a phone that texted * STOP still gets nothing unless {@link NotifyOptions.ignoreOptOut} is set. * Default: `false`. */ ignorePreferences?: boolean /** * Send to a recipient who has legally opted out (a phone that texted STOP, * recorded in `sms_opt_outs`). Only for messages the law requires you to * send whatever the person's consent, such as a mandated security or * safety notice. Never set it for marketing or ordinary transactional * mail: carriers filter senders that keep texting after STOP. It does not * skip the preference filter; pass `ignorePreferences` as well for that. * Email suppression is enforced by the mailer itself, through * `email.suppressionPolicy`. Default: `false`. */ ignoreOptOut?: boolean /** * Optional preference category — passed to the preferences lookup so * users can opt out of, e.g., `marketing` while staying opted in to * `system`. Ignored when `ignorePreferences` is true. * * A categorized send is one a person can unsubscribe from, so when the * preferences cannot be read it is not sent: each channel's result fails * with the lookup error, and the send can be retried later. An * uncategorized send goes out anyway. */ category?: string } /** Minimal transport contract used by `notify()` — anything that exposes a * `send(EmailMessage)` returning an `EmailResult` works (the @stacksjs/email * Mail singleton, a per-test LogEmailDriver, a custom mock, etc.). */ export interface EmailTransport { send: (message: EmailMessage) => Promise } /** * What `notify()` sends. `locale` (and `strings`, from * {@link NotificationFrameLocale}) put the frame in the reader's language: the * email's footer, unsubscribe links and default button label, and a marketing * text's opt-out line. The subject and body are sent as given. */ export interface NotificationPayload extends NotificationFrameLocale { emailTemplate?: NotificationEmailTemplate subject?: string body: string data?: Record /** Where the notification leads. Emailed as a button under the body. */ action?: NotificationAction /** * Unsubscribe links for a marketing notification. The email's footer says * why it came and links to `url` (and `preferencesUrl`), the text part * spells the link out, and the email carries `List-Unsubscribe` (plus * `List-Unsubscribe-Post` when `oneClickUrl` is set). Build one per person * with `notificationUnsubscribeLinks(userId)`. */ unsubscribe?: NotificationUnsubscribe /** Extra email headers. Values with line breaks are dropped by the mailer. */ headers?: Record /** * The opt-out line a text ends with. A `marketing` text gets * "Reply STOP to opt out." by default (in the payload's `locale`); a string * replaces it (and adds it to other categories), `false` leaves it out. */ smsOptOut?: string | false /** * Who a text is from, put first as `{smsSender}: `. Use it whenever several * businesses share one sending number (a platform texting for its tenants), * so the person can tell them apart. Cut to 30 characters. */ smsSender?: string } export interface NotificationRecipient { email?: string phone?: string /** * The channel or user a bot-token chat send posts to. Leave it out for a * webhook, whose URL already says where the message goes. */ chatRecipient?: string | string[] /** * Which chat transport carries the `chat` channel. Defaults to * `config.notification.chat.default`, then Slack. */ chatDriver?: 'slack' | 'discord' | 'teams' userId?: number /** * Device token(s) for the push channel — Expo tokens * (`ExponentPushToken[...]`) or raw FCM registration IDs. A single * recipient can have multiple tokens registered (one per device); pass * an array and the push driver fans out (multicast on FCM, batch * receipts on Expo). Required when `'push'` is in the channel list, * same way `email` / `phone` are required for their channels. */ pushTokens?: string | string[] /** Match the token issuer; native Apple tokens require apns. Defaults to Expo. */ pushDriver?: import('@stacksjs/push').PushDriver /** * WebSocket channel name for the `broadcast` notification channel * (stacksjs/stacks#669). When omitted, the driver derives a default: * `private-user.{userId}` if `userId` is set, otherwise the public * `notifications` channel. */ broadcastChannel?: string } export interface NotifyResult { channel: NotificationChannel success: boolean error?: Error } export function ensureSuccessfulEmailResult(result: EmailResult): void { if (!result.success) throw new Error(result.message || `Email delivery failed through ${result.provider || 'the configured provider'}.`) } /** Require at least one delivered channel and surface partial fan-out failure. */ export function ensureSuccessfulNotificationResults(results: readonly NotifyResult[]): void { if (!results.length) throw new Error('No notification channels were delivered') const failures = results.filter(result => !result.success) if (failures.length) { const errors = failures.map(result => result.error instanceof Error ? result.error : new Error(`Notification delivery failed through ${result.channel}`)) if (errors.length === 1) throw errors[0] throw new AggregateError(errors, errors.map(error => error.message).join('; ')) } } function ensureSuccessfulProviderResult(result: { success: boolean, message?: string, error?: string }): void { if (!result.success) throw new Error(result.error || result.message || 'Notification provider rejected delivery') } export interface ChatTransport { send: (message: ChatMessage) => Promise } /** * The chat transport `config/notification.ts` names (`chat.default`), read * when a notification is sent; `msTeams` is the Teams driver. Declared and * typed but read by nothing before, so `notify()` used Slack whatever an app * configured, and an app on Discord or Teams could not get a chat * notification at all. */ export function configuredChatDriver(): string | undefined { const configured = (appConfig as { notification?: NotificationOptions }).notification?.chat?.default return configured === 'msTeams' ? 'teams' : configured || undefined } export function useChat(driver?: string): ChatTransport { const resolvedDriver = driver || 'slack' if (!['slack', 'discord', 'teams'].includes(resolvedDriver)) throw new Error(`Unsupported chat driver: ${resolvedDriver}`) return chat[resolvedDriver as 'slack' | 'discord' | 'teams'] } /** * Return the email transport — by default the @stacksjs/email Mail * singleton, which lazy-resolves its driver from `config.email.default` * (so `MAIL_MAILER=log` in dev / `ses` in prod just works). Pass an * explicit driver name to scope to a specific transport — useful in * tests that want to assert against `LogEmailDriver` specifically without * touching the global config. * * Earlier this function returned the *driver namespace* (e.g. * `{ SESDriver, default }`), which has no `send`. The `'send' in driver` * guard in `notify()` was always false, so the email channel silently * no-op'd for every booking confirmation, host alert, etc. */ export function useEmail(driver?: string): EmailTransport { if (driver) { try { return mail.use(driver) as unknown as EmailTransport } catch (err) { log.warn(`[notifications] email driver '${driver}' not registered - falling back to default mail singleton (${(err as Error).message})`) } } return mail as unknown as EmailTransport } export interface SmsTransport { send: (message: SmsMessage) => Promise } export function useSMS(driver?: string): SmsTransport { if (!driver) return sms if (driver !== 'twilio' && driver !== 'vonage') throw new Error(`Unsupported SMS driver: ${driver}`) const provider = driver return { send: async (message) => { await sms.init() return sms.getDriver(provider).send(message) } } } /** * Push transport — returns the `@stacksjs/push` namespace whose * `send(to, notification, options)` dispatches to Expo or FCM based on * `options.driver`. `notify()` calls it with the driver omitted so the * push package's own default kicks in (`expo`). Apps that need to * force FCM can call `push.send(...)` directly with `{ driver: 'fcm' }`. * * Previously the `'push'` switch arm in `notify()` threw a hardcoded * "not yet wired into a default driver" error even though both drivers * exist (stacksjs/stacks#1874 F-1) — this helper is the missing link. */ export function usePush(): typeof push { return push } export function useDatabase(): typeof DatabaseNotificationDriver { return DatabaseNotificationDriver } /** * Broadcast transport — returns the `BroadcastNotificationDriver` which * fans out a notification payload over the realtime WebSocket layer * (`@stacksjs/realtime` `emit()`). See {@link BroadcastNotificationDriver} * for channel-naming rules. stacksjs/stacks#669. */ export function useBroadcast(): typeof BroadcastNotificationDriver { return BroadcastNotificationDriver } export function useNotification(typeParam?: string, driverParam?: string): ReturnType | ReturnType | ReturnType | typeof DatabaseNotificationDriver { const type = typeParam || config?.default || 'email' const driver = driverParam switch (type) { case 'email': return useEmail(driver) case 'chat': return useChat(driver) case 'sms': return useSMS(driver) case 'database': return useDatabase() default: throw new Error(`Notification type "${type}" is not supported`) } } /** * Send a notification through multiple channels simultaneously. * Uses Promise.allSettled so one channel failure doesn't block others. * * When `recipient.userId` is set and `options.ignorePreferences` is not * `true`, the channel list is first filtered through the user's * `notification_preferences` rows — any channel they've explicitly * disabled is silently skipped. Channels with no preference recorded fall * through as enabled (default-allow), so introducing this feature doesn't * regress notifications for users who haven't visited the preferences UI. * * For transactional notifications that must always go out (password * resets, security alerts, billing failures), pass * `{ ignorePreferences: true }`. That skips preferences only: a phone that * texted STOP is still never texted, unless `{ ignoreOptOut: true }` marks a * message the law requires you to send. * * @example * ```ts * // respects user preferences * await notify({ userId: 7, email: 'a@x' }, { body: 'New message' }, ['email', 'sms']) * * // bypasses preferences (security alert) * await notify({ userId: 7, email: 'a@x' }, { body: 'New login' }, ['email'], { ignorePreferences: true }) * * // category-specific opt-out * await notify({ userId: 7, email: 'a@x' }, { body: 'Sale!' }, ['email'], { category: 'marketing' }) * ``` */ export async function notify( recipient: NotificationRecipient, payload: NotificationPayload, channels: NotificationChannel[] = ['email'], options: NotifyOptions = {}, ): Promise { // Filter channels by user preferences when we have a userId to look up. // Default-allow: channels with no preference row recorded pass through. let effectiveChannels = [...new Set(channels)] let unreadablePreferences: Error | undefined if (recipient.userId && !options.ignorePreferences) { try { effectiveChannels = await filterChannelsByPreferences( recipient.userId, effectiveChannels, options.category, ) } catch (err) { // A categorized send (marketing, a newsletter) is what people // unsubscribe from, and sending one past an opt-out is the violation // whatever the cause, so it waits for a lookup that works (#3102). // Anything else must not be taken down by a preferences DB hiccup. const reason = err instanceof Error ? err.message : String(err) if (options.category !== undefined) unreadablePreferences = new Error(`[notify] not sent: the '${options.category}' preferences could not be read (${reason})`) else log.warn(`[notify] preferences filter failed, sending all channels: ${reason}`) } } const results = await Promise.allSettled( effectiveChannels.map(async (channel) => { if (unreadablePreferences) throw unreadablePreferences switch (channel) { case 'email': { // Fail loudly when the recipient is missing the channel-specific // contact — silently no-op'ing meant a forgotten `email` field // looked like a successful notification dispatch. if (!recipient.email) { throw new Error('[notify] email channel requires recipient.email') } const driver = useEmail() // payload.body is plain text. It goes out as text and as HTML in // the framework's email layout (notificationEmailHtml), since the // SES/SendGrid drivers only render `html`/`text` and a body in a // bare

reached people as unstyled text. const result = await driver.send(await notificationEmailMessage(recipient.email, payload)) ensureSuccessfulEmailResult(result) break } case 'sms': { // Fail loudly, not silently (stacksjs/stacks#1936). Previously // a misconfigured SMS driver (one without a `send()`) let the // case fall through and `Promise.allSettled` recorded success — // so a broken SMS config looked like a delivered notification. if (!recipient.phone) { throw new Error('[notify] sms channel requires recipient.phone') } // STOP compliance: a phone that texted STOP gets nothing, whatever // `ignorePreferences` says - preferences are the app's own // settings, STOP is a legal opt-out. Only an explicit // `ignoreOptOut: true` (a message the law requires, such as a // mandated safety notice) goes through. Throws rather than silently // succeeding so the delivery log records why nothing was sent. if (options.ignoreOptOut !== true) { const { isPhoneOptedOut } = await import('@stacksjs/sms') if (await isPhoneOptedOut(recipient.phone)) { throw new Error('[notify] sms recipient has opted out (STOP)') } } const driver = useSMS() ensureSuccessfulProviderResult(await driver.send({ to: recipient.phone, body: notificationSmsBody(payload, options.category) })) break } case 'chat': { // No recipient check here: a webhook needs none, and requiring one // meant the framework's own `notify({}, ..., ['chat'])` alerts (CI // failures, runner pressure, feedback) never sent. A bot-token send // still refuses to go without a channel; the error says which field. const driver = useChat(recipient.chatDriver ?? configuredChatDriver()) const to = Array.isArray(recipient.chatRecipient) && !recipient.chatRecipient.length ? undefined : recipient.chatRecipient const result = await driver.send({ to, content: payload.body, subject: payload.subject, data: payload.data }) if (!result.success && !to) throw new Error(`${result.message || 'Chat delivery failed'} (notify() sends recipient.chatRecipient as the channel)`) ensureSuccessfulProviderResult(result) break } case 'database': { if (!recipient.userId) { throw new Error('[notify] database channel requires recipient.userId') } await DatabaseNotificationDriver.send({ userId: recipient.userId, type: payload.subject || 'notification', data: { body: payload.body, ...payload.data }, }) break } case 'push': { // Wired up in stacksjs/stacks#1874 F-1. Push tokens are the // channel-specific contact (analogous to `recipient.email` for // email and `recipient.phone` for SMS) — fail loudly when // they're missing rather than silently dropping the dispatch. if (!recipient.pushTokens || (Array.isArray(recipient.pushTokens) && recipient.pushTokens.length === 0)) { throw new Error('[notify] push channel requires recipient.pushTokens') } const driver = usePush() ensureSuccessfulProviderResult(await driver.send(recipient.pushTokens, { title: payload.subject, body: payload.body, data: payload.data, }, { driver: recipient.pushDriver })) break } case 'broadcast': { const result = await BroadcastNotificationDriver.send({ channel: recipient.broadcastChannel, userId: recipient.userId, event: payload.subject ?? 'notification', data: { body: payload.body, ...payload.data }, }) if (!result.delivered) throw new Error(result.reason || 'Broadcast notification was not delivered') break } default: throw new Error(`Unsupported notification channel: ${channel}`) } }), ) const mappedResults = results.map((result, index) => { const channel = effectiveChannels[index] if (!channel) throw new Error(`Missing notification channel for result ${index}`) if (result.status === 'rejected') { // Surface channel failures in the log even when the caller doesn't // inspect the returned NotifyResult[] — silently failing fan-out // notifications used to mask broken SMS/Slack/email config for days. const reason = result.reason instanceof Error ? result.reason.message : String(result.reason) log.warn(`[notify] ${channel} channel failed: ${reason}`) } return { channel, success: result.status === 'fulfilled', error: result.status === 'rejected' ? result.reason instanceof Error ? result.reason : new Error(String(result.reason)) : undefined, } }) await Promise.all(mappedResults.map(result => recordNotificationDelivery(makeDeliveryRecord(recipient, payload, result, options)), )) return mappedResults } export function notification(): ReturnType { return useNotification() } export { BroadcastNotificationDriver } from './drivers/broadcast' export type { BroadcastNotificationOptions, BroadcastNotificationResult } from './drivers/broadcast' export { makeDeliveryRecord, recordNotificationDelivery, resolveDeliveryRecipient } from './delivery' export type { NotificationDeliveryRecord } from './delivery' export { DatabaseNotificationDriver, notificationChannel } from './drivers/database' export type { CreateNotificationOptions, DatabaseNotification } from './drivers/database' export { bulkSetPreferences, filterChannelsByPreferences, getNotificationPreferences, setNotificationPreference, wherePreferenceCategory, } from './preferences' export type { NotificationPreferenceRow, PreferenceChannel } from './preferences' export { DEFAULT_SMS_OPT_OUT, DEFAULT_UNSUBSCRIBE_NOTICE, emailParagraphs, listUnsubscribeHeaders, notificationEmailHtml, notificationEmailMessage, notificationEmailText, notificationSmsBody, SMS_SENDER_MAX_LENGTH, smsSenderPrefix } from './email-body' export type { EmailBodyPart, NotificationAction, NotificationEmailPayload, NotificationEmailTemplate, NotificationFrameLocale, NotificationUnsubscribe } from './email-body' export { NOTIFICATION_FRAME_STRINGS, notificationFrameStrings, notificationLanguageTag } from './frame-strings' export type { NotificationFrameStrings } from './frame-strings' export { advanceSequence, isQuietTime, nextSendableTime, sequenceTimeline } from './sequences' export type { AdvanceSequenceOptions, QuietHours, SequenceAdvance, SequenceStepLike } from './sequences' export { notificationUnsubscribeLinks, notificationUnsubscribeToken, parseNotificationUnsubscribeToken, unsubscribeTokenFromRequest, unsubscribeWithToken } from './unsubscribe' export type { ParsedUnsubscribeToken, UnsubscribeChannel, UnsubscribeLinkOptions } from './unsubscribe' export { accountNotificationTemplates, commerceNotificationTemplates, createNotificationTemplates, defineNotificationTemplates, interpolateNotificationText, notificationTemplateVariables, renderNotificationTemplate, resolveNotificationLocale, subscriptionNotificationTemplates } from './templates' export type { AccountNotificationPaths, AccountNotificationTemplateName, CommerceNotificationPaths, CommerceNotificationTemplateName, NotificationTemplateAction, NotificationTemplateCatalog, NotificationTemplateCatalogOptions, NotificationTemplateCopy, NotificationTemplateDefinition, NotificationTemplateVariables, RenderedNotificationTemplate, RenderNotificationTemplateOptions, SubscriptionNotificationPaths, SubscriptionNotificationTemplateName } from './templates'