export type UserAgentDevice = 'desktop' | 'phone' | 'tablet' export interface UserAgentDescription { label: string device: UserAgentDevice } const BROWSERS: ReadonlyArray = [ [/Edg\//, 'Edge'], [/OPR\/|Opera/, 'Opera'], [/Firefox\/|FxiOS\//, 'Firefox'], [/Chrome\/|CriOS\//, 'Chrome'], [/Safari\//, 'Safari'] ] const SYSTEMS: ReadonlyArray = [ [/iPhone/, 'iPhone'], [/iPad/, 'iPad'], [/Android/, 'Android'], [/Mac OS X|Macintosh/, 'macOS'], [/Windows/, 'Windows'], [/CrOS/, 'ChromeOS'], [/Linux/, 'Linux'] ] function findName(list: ReadonlyArray, userAgent: string) { return list.find(([pattern]) => pattern.test(userAgent))?.[1] ?? null } export function describeUserAgent(userAgent: string | null | undefined): UserAgentDescription { const value = userAgent ?? '' const browser = findName(BROWSERS, value) const system = findName(SYSTEMS, value) const isTablet = /iPad/.test(value) || (/Android/.test(value) && !/Mobile/.test(value)) const isPhone = /iPhone|Mobile/.test(value) let label = 'Unknown device' if (browser && system) { label = `${browser} on ${system}` } else if (browser || system) { label = browser ?? system ?? label } let device: UserAgentDevice = 'desktop' if (isTablet) { device = 'tablet' } else if (isPhone) { device = 'phone' } return { label, device } }