import { describe, expect, it } from 'vitest' import { BUILTIN_LOOKALIKES } from '../src/shared/lookalikes.ts' import { PhraseSchema } from '../src/shared/schemas.ts' import { parseCmdFlags, parseNukeArgs } from '../src/server/bot/commands.ts' import { evaluateMath } from '../src/server/bot/engine/math.ts' import { nowPlayingFromStatus } from '../src/server/bot/services.ts' import { escalatedTimeout } from '../src/server/bot/engine/moderation.ts' import { renderTemplate } from '../src/server/bot/engine/template.ts' import { capsPercent, chunkMessage, compileLookalikes, compilePhrase, countEmoji, extractHosts, hostAllowed, maxCombining, repetition, similarity, } from '../src/server/bot/engine/text.ts' import { makeResolver, type VarContext, type VarServices } from '../src/server/bot/engine/variables.ts' import { cleanForDetection, detectForeignLanguage, letterCount, loadLanguageDetector } from '../src/server/bot/engine/language.ts' import { searchLanguages } from '../src/shared/languages.ts' import { FilterConfigSchemas, LastfmSchema, PunishmentSchema, TealfmSchema } from '../src/shared/schemas.ts' const phrase = (text: string, extra: Partial> = {}) => PhraseSchema.parse({ text, ...extra }) describe('phrase matching', () => { it('matches anywhere, case-insensitively by default', () => { const m = compilePhrase(phrase('free viewers'))! expect(m('get FREE VIEWERS now')).toBeTruthy() expect(m('get free viewer')).toBeNull() }) it('respects position', () => { expect(compilePhrase(phrase('hi', { position: 'start' }))!('hi there')).toBeTruthy() expect(compilePhrase(phrase('hi', { position: 'start' }))!('oh hi')).toBeNull() expect(compilePhrase(phrase('bye', { position: 'end' }))!('ok bye')).toBeTruthy() expect(compilePhrase(phrase('bye', { position: 'end' }))!('bye ok')).toBeNull() expect(compilePhrase(phrase('lol', { position: 'exact' }))!(' lol ')).toBeTruthy() expect(compilePhrase(phrase('lol', { position: 'exact' }))!('lol!')).toBeNull() }) it('supports unicode word boundaries', () => { const m = compilePhrase(phrase('ass', { wordBoundary: true }))! expect(m('you ass')).toBeTruthy() expect(m('class')).toBeNull() expect(m('passé')).toBeNull() }) it('supports case sensitivity and regex', () => { expect(compilePhrase(phrase('KEKW', { caseSensitive: true }))!('kekw')).toBeNull() expect(compilePhrase(phrase('b[a@]d', { regex: true }))!('so b@d')).toBeTruthy() expect(compilePhrase(phrase('regex:^\\d{3}$'))!('123')).toBeTruthy() expect(compilePhrase(phrase('(unclosed', { regex: true }))).toBeNull() }) it('escapes literal phrases', () => { expect(compilePhrase(phrase('a.b'))!('axb')).toBeNull() expect(compilePhrase(phrase('a.b'))!('a.b')).toBeTruthy() }) it('resolves var: references, failing when the variable is missing', () => { const vars = new Map([['slurs', 'regex:abc(123)?']]) expect(compilePhrase(phrase('var:slurs'), vars)!('test abc123')).toBeTruthy() expect(compilePhrase(phrase('var:nope'), vars)).toBeNull() }) }) describe('lookalikes', () => { const normalize = compileLookalikes(BUILTIN_LOOKALIKES) it('folds leetspeak, homoglyphs, accents and invisible characters', () => { expect(normalize('fr33 v1ewers')).toBe('free viewers') expect(normalize('frее')).toBe('free') // Cyrillic е expect(normalize('free')).toBe('free') expect(normalize('𝐟𝐫𝐞𝐞')).toBe('free') expect(normalize('fr​ee')).toBe('free') expect(normalize('café')).toBe('cafe') }) it('applies later groups over earlier ones in a single pass', () => { const n = compileLookalikes([{ id: 'x', slug: 'x', name: 'x', description: '', enabled: true, public: false, groups: [{ replacement: 'a', phrases: ['@'], enabled: true }, { replacement: 'at', phrases: ['@'], enabled: true }] }]) expect(n('@')).toBe('at') }) it('skips disabled lookalikes', () => { const n = compileLookalikes([{ ...BUILTIN_LOOKALIKES[2], enabled: false }]) expect(n('fr33')).toBe('fr33') }) }) describe('measurements', () => { it('counts caps, emoji, combining marks and repetition', () => { expect(Math.round(capsPercent('HELLO world'))).toBe(50) expect(countEmoji('hi 👋🏽 🎉🎉 👨‍👩‍👧')).toBe(4) expect(maxCombining('z̴̡̢̛a')).toBe(4) expect(repetition('lol lol lol lol').maxWordRepeats).toBe(4) expect(repetition('noooooooo').maxCharRun).toBe(8) }) it('finds links and checks allowlists', () => { expect(extractHosts('go to https://Evil.example.com/x and bsky.app')).toEqual(['evil.example.com', 'bsky.app']) expect(extractHosts('see index.js or 1.5')).toEqual([]) expect(hostAllowed('clips.stream.place', ['stream.place'])).toBe(true) expect(hostAllowed('notstream.place', ['stream.place'])).toBe(false) }) it('scores similarity', () => { expect(similarity('buy followers now', 'buy followers now!')).toBeGreaterThan(0.9) expect(similarity('hello', 'goodbye')).toBeLessThan(0.3) }) it('chunks long messages on word boundaries', () => { const chunks = chunkMessage('word '.repeat(100).trim(), 50) expect(chunks.every((c) => [...c].length <= 50)).toBe(true) expect(chunks.join(' ')).toBe('word '.repeat(100).trim()) }) }) describe('language filter', () => { const englishOnly = FilterConfigSchemas.language.parse({}) const detect = (text: string, cfg = englishOnly) => detectForeignLanguage(text, cfg) it('defaults to English and migrates filters saved with writing systems', () => { expect(englishOnly).toEqual({ allowedLanguages: ['en'], strictness: 'balanced', minLength: 12 }) const migrated = FilterConfigSchemas.language.parse({ allowedScripts: ['cyrillic'], minLength: 8, maxPercent: 40 }) expect(migrated.allowedLanguages.sort()).toEqual(['be', 'bg', 'ru', 'sr', 'uk']) expect(migrated.minLength).toBe(8) }) it('finds languages by English name, native name, alias or code', () => { expect(searchLanguages('eng')[0].code).toBe('en') expect(searchLanguages('deutsch')[0].code).toBe('de') expect(searchLanguages('espanol')[0].code).toBe('es') expect(searchLanguages('indonesian')[0].code).toBe('ms') expect(searchLanguages('ja')[0].code).toBe('ja') }) it('ignores links, mentions, emote codes, chat shorthand and repeats', () => { expect(cleanForDetection('LMAOOOO @mmatt.net check https://x.com/a :pog: hype hype hype gg')).toBe('check hype') expect(letterCount('你好')).toBe(6) }) it('catches other languages and lets slangy English through', async () => { await loadLanguageDetector() for (const text of ['lmao that was so good', 'yo whats up chat how is everyone doing', 'this stream is fire ngl', 'W streamer W chat', 'KEKW KEKW KEKW KEKW', 'valid valid valid', 'happy birthday!!!', 'bonjour from france but i speak english lol', '(ノಠ益ಠ)ノ彡┻━┻']) expect(detect(text), text).toBeNull() expect(detect('hola que tal como estan todos')).toBe('es') expect(detect('hallo zusammen wie geht es euch')).toBe('de') expect(detect('привет всем как дела')).toBe('ru') expect(detect('你好大家好')).toBe('zh') expect(detect('こんにちは皆さん')).toBe('ja') expect(detect('hola amigos')).toBeNull() // too short to tell expect(detect('hola que tal como estan todos', { ...englishOnly, allowedLanguages: ['en', 'es'] })).toBeNull() expect(detect('hola que tal como estan todos', { ...englishOnly, allowedLanguages: [] })).toBeNull() }) }) describe('music integration settings', () => { it('requires a Last.fm username to be on, and keeps saved usernames working after upgrade', () => { expect(LastfmSchema.safeParse({ enabled: true, username: '' }).success).toBe(false) expect(LastfmSchema.parse({ username: 'rj' })).toEqual({ enabled: true, username: 'rj' }) expect(LastfmSchema.parse(undefined)).toEqual({ enabled: false, username: '' }) }) it('lets teal.fm be on with no handle', () => { expect(TealfmSchema.parse({ enabled: true, handle: '' })).toEqual({ enabled: true, handle: '' }) expect(TealfmSchema.parse(undefined)).toEqual({ enabled: false, handle: '' }) }) }) describe('teal.fm status', () => { const now = Date.parse('2026-11-24T02:20:00Z') it('reads the playing track from a status record', () => { const status = { time: '2026-11-24T02:19:21Z', expiry: '2026-11-24T02:29:21Z', item: { trackName: 'I Wish That I Could Fall', artists: [{ artistName: 'Jamie Paige' }, { artistName: 'Guest' }] } } expect(nowPlayingFromStatus(status, now)).toEqual({ artist: 'Jamie Paige, Guest', track: 'I Wish That I Could Fall' }) }) it('treats expired or blank statuses as not playing', () => { expect(nowPlayingFromStatus({ expiry: '2026-11-24T02:18:17Z', item: { trackName: 'Old song', artists: [] } }, now)).toBeNull() expect(nowPlayingFromStatus({ expiry: '2026-11-24T03:00:00Z', item: { trackName: '', artists: [] } }, now)).toBeNull() expect(nowPlayingFromStatus(undefined, now)).toBeNull() }) }) describe('math', () => { it('evaluates expressions safely', () => { expect(evaluateMath('1 + 1')).toBe(2) expect(evaluateMath('2 * (3 + 4)')).toBe(14) expect(evaluateMath('2^10')).toBe(1024) expect(evaluateMath('-3 + 5')).toBe(2) expect(evaluateMath('round(10/3, 2)')).toBe(3.33) expect(() => evaluateMath('process.exit()')).toThrow() expect(() => evaluateMath('1/0')).toThrow() }) }) function services(overrides: Partial = {}): VarServices { const counters = new Map() return { channel: { did: 'did:plc:chan', handle: 'streamer.bsky.social', displayName: 'Streamer' }, live: { isLive: true, title: 'Speedruns!', activity: { kind: 'label', id: 'just_chatting', name: 'Just Chatting' }, activitySince: Date.now() - 60_000, startedAt: Date.now() - 3_660_000, endedAt: null, viewers: 42, gamesPlayed: ['Just Chatting'] }, publicUrl: 'https://bot.example', timezone: 'UTC', botStartedAt: Date.now() - 1000, profile: async (a) => (a === 'friend.bsky.social' ? { did: 'did:plc:friend', handle: 'friend.bsky.social', displayName: 'Friend', createdAt: '2020-01-01T00:00:00Z' } : null), follow: async () => ({ createdAt: new Date(Date.now() - 86400_000 * 40).toISOString() }), counterAdd: (n, d) => { counters.set(n, (counters.get(n) ?? 0) + d) return counters.get(n)! }, counterGet: (n) => counters.get(n) ?? 0, counterSet: (n, v) => { counters.set(n, v) return v }, quote: (n) => (n === 2 ? { number: 2, text: 'hello' } : n === null ? { number: 1, text: 'first' } : null), commandResponse: (name) => (name === 'socials' ? 'Follow $(channel)!' : undefined), eightBall: () => 'Yes.', chatters: () => [], watchtime: () => null, currentSong: () => null, setTitle: async () => {}, setActivity: async (q) => q, fetchText: async () => 'remote', lastfm: async () => ({ artist: 'Artist', track: 'Song' }), tealfm: async (actor) => (actor === 'quiet.bsky.social' ? null : { artist: 'Teal Artist', track: `Song for ${actor}` }), musicSettings: () => ({ lastfm: { enabled: true, account: '' }, tealfm: { enabled: true, account: 'saved.bsky.social' } }), weather: async () => 'sunny', latestPost: async () => 'https://bsky.app/profile/x/post/1', ...overrides, } } function render(template: string, ctx: Partial = {}) { const full: VarContext = { services: services(), sender: { did: 'did:plc:me', handle: 'me.bsky.social', displayName: 'Me' }, message: '!cmd a b c', messageUri: 'at://x/y/z', args: ['a', 'b', 'c'], counterKey: 'cmd:1', inTimer: false, dryRun: false, ...ctx, } return renderTemplate(template, makeResolver(full)) } describe('variables', () => { it('renders users, channel and stream', async () => { expect(await render('hi $(sender)')).toBe('hi Me') expect(await render('$(user friend.bsky.social)')).toBe('Friend') expect(await render('$(user.handle)')).toBe('me.bsky.social') expect(await render('$(channel) $(channel.display_name) $(viewers)')).toBe('streamer.bsky.social Streamer 42') expect(await render('$(title) / $(game)')).toBe('Speedruns! / Just Chatting') expect(await render('$(uptime)')).toBe('1 hour and 1 minute') }) it('handles argument shorthands with fallbacks', async () => { expect(await render('$(1) $(3)')).toBe('a c') expect(await render('$(2:)')).toBe('b c') expect(await render('$(:2)')).toBe('a b') expect(await render('$(5 nothing here)')).toBe('nothing here') expect(await render('$(5)')).toBe('[Error: Index 5 is not in arguments.]') expect(await render('$(query)')).toBe('a b c') expect(await render('$(echo)')).toBe('!cmd a b c') expect(await render('$(touser)', { args: ['@friend.bsky.social'] })).toBe('friend.bsky.social') expect(await render('$(touser)', { args: [] })).toBe('me.bsky.social') }) it('nests variables', async () => { expect(await render('$(user $(1))', { args: ['friend.bsky.social'] })).toBe('Friend') expect(await render('$(math $(randint 2 2) * 3)')).toBe('6') expect(await render('$(upper $(1))')).toBe('A') }) it('counts', async () => { const s = services() expect(await render('$(count) $(count)', { services: s })).toBe('1 2') expect(await render('$(count.increment deaths 5) $(count.get deaths)', { services: s })).toBe('5 5') expect(await render('$(count.set deaths 1)', { services: s })).toBe('1') expect(await render('$(count.get bad!name)', { services: s })).toContain('Count name invalid') }) it('does not write counters in dry-run mode', async () => { const s = services() expect(await render('$(count)', { services: s, dryRun: true })).toBe('1') expect(await render('$(count)', { services: s, dryRun: true })).toBe('1') }) it('renders quotes, references and misc', async () => { expect(await render('$(quote 2)')).toBe('#2: hello') expect(await render('$(quote 9)')).toBe('[Error: Quote not found.]') expect(await render('$(references socials)')).toBe('Follow streamer.bsky.social!') expect(await render('$(rngphrase only)')).toBe('only') expect(await render('$(repeat 3 hi)')).toBe('hi hi hi') expect(await render('$(urlencode a b&c)')).toBe('a+b%26c') expect(await render('$(lastfm someone)')).toBe('Artist - Song') expect(await render('$(lastfm)')).toBe('[Error: You must provide a last.fm username.]') expect(await render('$(tealfm)')).toBe('Teal Artist - Song for saved.bsky.social') expect(await render('$(tealfm @dj.bsky.social)')).toBe('Teal Artist - Song for dj.bsky.social') expect(await render('$(tealfm 🎵 {songname} by {artist})')).toBe('🎵 Song for saved.bsky.social by Teal Artist') expect(await render('$(tealfm quiet.bsky.social)')).toBe('quiet.bsky.social isn’t playing anything right now.') expect(await render('$(tealfm Listening to {songname})')).toBe('Listening to Song for saved.bsky.social') expect(await render('$(lastfm rj {songname})')).toBe('Song') const off = services({ musicSettings: () => ({ lastfm: { enabled: false, account: 'rj' }, tealfm: { enabled: false, account: 'x.bsky.social' } }) }) expect(await render('$(tealfm)', { services: off })).toBe('[Error: teal.fm is turned off. Turn it on in Integrations.]') expect(await render('$(lastfm rj)', { services: off })).toBe('[Error: Last.fm is turned off. Turn it on in Integrations.]') expect(await render('$(followage)')).toMatch(/^Me has been following Streamer for 1 month/) expect(await render('$(unknownvar 1)')).toBe('$(unknownvar 1)') expect(await render('$(sender)', { inTimer: true })).toContain('Cannot be executed inside of a timer') }) it('reports offline errors', async () => { const s = services() s.live.isLive = false expect(await render('$(uptime)', { services: s })).toBe('[Error: Stream is offline.]') }) }) describe('command parsing', () => { it('parses Fossabot-style flags', () => { const { rest, flags } = parseCmdFlags(['hello', 'Hi', '$(user)!', '-g', '10', '--user', '30', '-t', 'reply', '--addalias', '!hey', '--disable']) expect(rest).toEqual(['hello', 'Hi', '$(user)!']) expect(flags).toMatchObject({ global: 10, user: 30, type: 'reply', addAliases: ['hey'], enable: false }) }) it('parses nuke arguments', () => { expect(parseNukeArgs(['spam'])).toMatchObject({ pattern: 'spam', lookback: 60, action: 'delete' }) expect(parseNukeArgs(['buy', 'followers', '120', 'ban'])).toMatchObject({ pattern: 'buy followers', lookback: 120, action: 'ban' }) expect(parseNukeArgs(['/f+ree/', '30', '600'])).toMatchObject({ pattern: 'f+ree', regex: true, lookback: 30, action: 'timeout', duration: 600 }) }) }) describe('punishment escalation', () => { it('multiplies timeouts for repeat offenders up to the max', () => { const p = PunishmentSchema.parse({ baseTimeout: 60, maxTimeout: 600, repeatOffenders: { enabled: true, multiplier: 2 } }) expect(escalatedTimeout(p, 0)).toBe(60) expect(escalatedTimeout(p, 1)).toBe(120) expect(escalatedTimeout(p, 3)).toBe(480) expect(escalatedTimeout(p, 10)).toBe(600) const flat = PunishmentSchema.parse({ baseTimeout: 60, maxTimeout: 600 }) expect(escalatedTimeout(flat, 5)).toBe(60) }) })