Something went wrong. Try again.
fossabot clone for streamplace superbot.mmatt.net
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229import 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<string, string> = 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 = `(?<![\\p{L}\\p{N}_])(?:${source})(?![\\p{L}\\p{N}_])` else source = `(?:${source})` switch (phrase.position) { case 'start': source = `^\\s*${source}` break case 'end': source = `${source}\\s*$` break case 'exact': source = `^\\s*${source}\\s*$` break } try { const re = new RegExp(source, phrase.caseSensitive ? 'u' : 'iu') return (t) => { 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<string, string>() 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})*/guexport const countEmoji = (text: string) => text.match(EMOJI)?.length ?? 0
const LETTER = /\p{L}/uconst 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]*)?)/giconst 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<string>() 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<string, number>() 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<string, number>() 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}