import { describe, expect, test } from 'bun:test' // --------------------------------------------------------------------------- // Import the real notification functions directly — no mocks. // We test the driver resolution and notification routing logic. // The real drivers, config, and database module all load in test env. // --------------------------------------------------------------------------- const { useChat, useEmail, useSMS, usePush, useDatabase, useNotification, notify, notification, ensureSuccessfulEmailResult, makeDeliveryRecord, resolveDeliveryRecipient, wherePreferenceCategory, } = await import('../src/index') // --------------------------------------------------------------------------- // Tests // --------------------------------------------------------------------------- describe('Notifications - useChat()', () => { test('returns a chat driver', () => { const driver = useChat() expect(driver).toBeDefined() }) test('useChat("slack") returns the slack driver', () => { const driver = useChat('slack') expect(driver).toBeDefined() expect(driver).toHaveProperty('send') }) test('useChat("discord") returns the discord driver', () => { const driver = useChat('discord') expect(driver).toBeDefined() }) }) describe('Notifications - useEmail()', () => { test('returns an email driver when driver specified', () => { const driver = useEmail('ses') expect(driver).toBeDefined() }) test('useEmail("sendgrid") returns the sendgrid driver', () => { const driver = useEmail('sendgrid') expect(driver).toBeDefined() }) }) describe('Notifications - useSMS()', () => { test('useSMS is a function', () => { expect(typeof useSMS).toBe('function') }) test('useSMS returns a value', () => { // The SMS driver may not have sub-drivers keyed by name, // so the default lookup may return undefined. We just verify no crash. const driver = useSMS() // driver could be undefined if the package doesn't export keyed sub-drivers expect(true).toBe(true) }) }) describe('Notifications - usePush() (stacksjs/stacks#1874 F-1)', () => { test('returns the @stacksjs/push namespace with a send() function', () => { const driver = usePush() expect(driver).toBeDefined() expect(typeof driver.send).toBe('function') }) }) describe('Notifications - notify() push channel (F-1)', () => { test('throws a clear error when recipient.pushTokens is missing', async () => { const [result] = await notify( { userId: 0 }, // no pushTokens → channel-specific contact missing { body: 'hello' }, ['push'], { ignorePreferences: true }, // skip the prefs lookup since userId=0 has no row ) expect(result.success).toBe(false) expect(result.error?.message).toContain('recipient.pushTokens') }) test('throws when pushTokens is an empty array (same failure shape)', async () => { const [result] = await notify( { pushTokens: [] }, { body: 'hello' }, ['push'], { ignorePreferences: true }, ) expect(result.success).toBe(false) expect(result.error?.message).toContain('recipient.pushTokens') }) }) describe('Notifications - sms/chat fail loudly (stacksjs/stacks#1936)', () => { test('sms channel without recipient.phone reports failure, not silent success', async () => { const [result] = await notify( { userId: 0 }, // no phone { body: 'hi' }, ['sms'], { ignorePreferences: true }, ) // Before #1936 a misconfigured SMS driver let this resolve as a // (false) success; now a missing channel contact always surfaces. expect(result.success).toBe(false) expect(result.error?.message).toContain('recipient.phone') }) }) describe('Notifications - useDatabase()', () => { test('returns the DatabaseNotificationDriver', () => { const driver = useDatabase() expect(driver).toBeDefined() expect(driver).toHaveProperty('send') }) }) describe('Notifications - useNotification()', () => { test('routes to email with explicit type', () => { const driver = useNotification('email', 'ses') expect(driver).toBeDefined() }) test('routes to chat driver when type is "chat"', () => { const driver = useNotification('chat') expect(driver).toBeDefined() }) test('sms type does not throw', () => { // SMS driver may return undefined if not configured expect(() => useNotification('sms')).not.toThrow() }) test('routes to database driver when type is "database"', () => { const driver = useNotification('database') expect(driver).toBeDefined() }) test('throws for unsupported notification type', () => { expect(() => useNotification('pigeon' as any)).toThrow('not supported') }) }) describe('Notifications - notify()', () => { test('notify is a function', () => { expect(typeof notify).toBe('function') }) test('surfaces resolved email driver failures', () => { expect(() => ensureSuccessfulEmailResult({ success: false, message: 'Provider rejected the message', provider: 'ses', })).toThrow('Provider rejected the message') expect(() => ensureSuccessfulEmailResult({ success: true, message: 'Email sent', provider: 'capture', })).not.toThrow() }) }) describe('Notifications - delivery tracking', () => { test('resolves the channel-specific recipient', () => { const recipient = { email: 'user@example.com', phone: '+15551234567', userId: 42, pushTokens: ['token-a', 'token-b'], broadcastChannel: 'private-orders', } expect(resolveDeliveryRecipient(recipient, 'email')).toBe('user@example.com') expect(resolveDeliveryRecipient(recipient, 'sms')).toBe('+15551234567') expect(resolveDeliveryRecipient(recipient, 'database')).toBe('User #42') expect(resolveDeliveryRecipient(recipient, 'push')).toBe('token-a, token-b') expect(resolveDeliveryRecipient(recipient, 'broadcast')).toBe('private-orders') }) test('builds a failed delivery record without throwing away context', () => { const error = new Error('Provider unavailable') const record = makeDeliveryRecord( { email: 'user@example.com', userId: 42 }, { subject: 'Security alert', body: 'A new login was detected.', data: { ip: '127.0.0.1' } }, { channel: 'email', success: false, error }, { category: 'security' }, '2026-07-29T10:00:00.000Z', ) expect(record).toEqual({ userId: 42, channel: 'email', recipient: 'user@example.com', subject: 'Security alert', body: 'A new login was detected.', status: 'failed', error: 'Provider unavailable', metadata: { ip: '127.0.0.1', category: 'security' }, sentAt: '2026-07-29T10:00:00.000Z', }) }) }) describe('Notifications - notification()', () => { test('notification function is exported', () => { expect(typeof notification).toBe('function') }) }) describe('Notifications - nullable preference categories', () => { test('uses whereNull for an uncategorized preference (Postgres-safe)', () => { const calls: unknown[][] = [] const query: any = { where: (...args: unknown[]) => { calls.push(['where', ...args]); return query }, whereNull: (...args: unknown[]) => { calls.push(['whereNull', ...args]); return query }, } expect(wherePreferenceCategory(query, null)).toBe(query) expect(calls).toEqual([['whereNull', 'category']]) }) test('uses equality for a named category', () => { const calls: unknown[][] = [] const query: any = { where: (...args: unknown[]) => { calls.push(['where', ...args]); return query }, whereNull: (...args: unknown[]) => { calls.push(['whereNull', ...args]); return query }, } wherePreferenceCategory(query, 'marketing') expect(calls).toEqual([['where', 'category', '=', 'marketing']]) }) })