import type { Lookalike, Phrase } from '../../../shared/schemas.ts' // --- phrases --------------------------------------------------------------- const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') export type Matcher = (text: string) => RegExpExecArray | null /** * Compile a phrase into a matcher. Returns null when the phrase can't be used: * an invalid regex, or a `var:` reference to a missing or disabled variable. */ export function compilePhrase(phrase: Phrase, variables: ReadonlyMap = new Map()): Matcher | null { let text = phrase.text let regex = phrase.regex const varRef = /^var:([a-z0-9_]+)$/i.exec(text.trim()) if (varRef) { const value = variables.get(varRef[1].toLowerCase()) if (value === undefined) return null text = value } if (text.startsWith('regex:')) { text = text.slice('regex:'.length) regex = true } if (!text) return null let source = regex ? text : escapeRegex(text) if (phrase.wordBoundary) source = `(? { re.lastIndex = 0 return re.exec(t) } } catch { return null } } // --- lookalikes -------------------------------------------------------------- export type Normalizer = (text: string) => string const COMBINING = /\p{M}+/gu /** NFKD-fold accents and compatibility characters (fullwidth, math alphanumerics) to plain letters. */ export function foldAccents(text: string): string { return text.normalize('NFKD').replace(COMBINING, '').normalize('NFC') } /** * Build a single-pass normalizer from installed lookalikes, in order. Within * a lookalike, groups apply top to bottom, so later groups take priority. */ export function compileLookalikes(list: (Lookalike & { id: string })[]): Normalizer { const steps: Normalizer[] = [] for (const l of list) { if (!l.enabled) continue if (l.id === 'builtin:accents') { steps.push(foldAccents) continue } const map = new Map() for (const g of l.groups) { if (!g.enabled) continue for (const p of g.phrases) map.set(p, g.replacement) } if (map.size === 0) continue const keys = [...map.keys()].sort((a, b) => b.length - a.length).map(escapeRegex) const re = new RegExp(keys.join('|'), 'gu') steps.push((t) => t.replace(re, (m) => map.get(m) ?? m)) } return (text) => steps.reduce((acc, step) => step(acc), text) } // --- measurements for spam filters ----------------------------------------- const EMOJI = /\p{Extended_Pictographic}(?:️|‍\p{Extended_Pictographic})*/gu export const countEmoji = (text: string) => text.match(EMOJI)?.length ?? 0 const LETTER = /\p{L}/u const UPPER = /\p{Lu}/u /** Percentage of letters that are capitals. */ export function capsPercent(text: string): number { let letters = 0 let upper = 0 for (const ch of text) { if (LETTER.test(ch)) { letters++ if (UPPER.test(ch)) upper++ } } return letters ? (upper / letters) * 100 : 0 } const SYMBOL = /[\p{P}\p{S}]/u /** Percentage of non-space characters that are punctuation or symbols (emoji excluded). */ export function symbolsPercent(text: string): number { const stripped = text.replace(EMOJI, '').replace(/\s+/g, '') if (!stripped) return 0 let symbols = 0 let total = 0 for (const ch of stripped) { total++ if (SYMBOL.test(ch)) symbols++ } return (symbols / total) * 100 } /** The most combining marks stacked on a single character. */ export function maxCombining(text: string): number { let max = 0 for (const m of text.matchAll(/\p{M}+/gu)) max = Math.max(max, [...m[0]].length) return max } const URL_RE = /\b((?:https?:\/\/)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,24}(?::\d+)?(?:\/[^\s]*)?)/gi const NOT_TLDS = new Set(['js', 'ts', 'py', 'md', 'txt', 'exe', 'png', 'jpg', 'gif', 'json', 'html', 'css']) /** Hostnames of links in a message, including ones only present as link facets. */ export function extractHosts(text: string, facetUris: string[] = []): string[] { const hosts = new Set() for (const m of text.matchAll(URL_RE)) { const raw = m[1] const host = raw.replace(/^https?:\/\//i, '').split(/[/:?#]/)[0].toLowerCase() const tld = host.split('.').pop() ?? '' if (!/^https?:/i.test(raw) && NOT_TLDS.has(tld)) continue if (/^\d+(\.\d+)+$/.test(host) && !/^https?:/i.test(raw)) continue hosts.add(host.replace(/^www\./, '')) } for (const uri of facetUris) { try { hosts.add(new URL(uri).hostname.toLowerCase().replace(/^www\./, '')) } catch {} } return [...hosts] } export function hostAllowed(host: string, allowed: string[]): boolean { return allowed.some((d) => { const domain = d.toLowerCase().replace(/^\*?\.?/, '').replace(/^https?:\/\//, '').split('/')[0] return host === domain || host.endsWith(`.${domain}`) }) } /** Dice coefficient on character bigrams: 1 means identical. */ export function similarity(a: string, b: string): number { a = a.toLowerCase().replace(/\s+/g, ' ').trim() b = b.toLowerCase().replace(/\s+/g, ' ').trim() if (a === b) return 1 if (a.length < 2 || b.length < 2) return 0 const grams = new Map() for (let i = 0; i < a.length - 1; i++) { const g = a.slice(i, i + 2) grams.set(g, (grams.get(g) ?? 0) + 1) } let overlap = 0 for (let i = 0; i < b.length - 1; i++) { const g = b.slice(i, i + 2) const n = grams.get(g) ?? 0 if (n > 0) { grams.set(g, n - 1) overlap++ } } return (2 * overlap) / (a.length + b.length - 2) } /** Longest run of one repeated character, and the most times any word repeats. */ export function repetition(text: string): { maxCharRun: number; maxWordRepeats: number } { let maxCharRun = 0 let run = 0 let prev = '' for (const ch of text) { if (ch === prev && !/\s/.test(ch)) run++ else run = 1 prev = ch maxCharRun = Math.max(maxCharRun, run) } const counts = new Map() for (const w of text.toLowerCase().split(/\s+/).filter(Boolean)) counts.set(w, (counts.get(w) ?? 0) + 1) return { maxCharRun, maxWordRepeats: Math.max(0, ...counts.values()) } } /** Rough number of lines a message takes up in a chat column. */ export function visualLines(text: string, charsPerLine: number): number { return text.split('\n').reduce((n, line) => n + Math.max(1, Math.ceil([...line].length / charsPerLine)), 0) } export const graphemeLength = (text: string) => [...new Intl.Segmenter().segment(text)].length /** Split chat text into whitespace-separated arguments. */ export const splitArgs = (text: string) => text.trim().split(/\s+/).filter(Boolean) /** Break a long message into chunks of at most `max` graphemes, on word boundaries. */ export function chunkMessage(text: string, max = 300): string[] { if (graphemeLength(text) <= max) return [text] const out: string[] = [] let current = '' for (const word of text.split(/(\s+)/)) { if (graphemeLength(current + word) > max) { if (current.trim()) out.push(current.trim()) current = '' let w = word while (graphemeLength(w) > max) { const segs = [...new Intl.Segmenter().segment(w)].map((s) => s.segment) out.push(segs.slice(0, max).join('')) w = segs.slice(max).join('') } current = w } else current += word } if (current.trim()) out.push(current.trim()) return out }