Add uarite-js: JavaScript/TypeScript port published to npm. Bump version.

This commit is contained in:
2026-09-09 23:35:59 +00:00
parent f25bfafbc7
commit a225bacfc4
12 changed files with 917 additions and 4 deletions
+8 -1
View File
@@ -2,10 +2,17 @@
__pycache__/
*.py[oc]
build/
dist/
/dist/
wheels/
*.egg-info
.*
!.gitignore
!*/.prettierrc.json
*.lock
# JS build artifacts
node_modules/
package-lock.json
uarite-js/dist/*
!uarite-js/dist/uarite.min.js
+3 -3
View File
@@ -1,17 +1,17 @@
# User-Agent Parsing Done Right
Fast and accurate handling of modern browsers and crawlers. Despite its light weight, uarite identifies both browsers and crawlers more accurately than any competing implementation tested here. Despite being pure Python, it outperforms ua-parser's C++/Rust variants.
Fast and accurate handling of modern browsers and crawlers. Despite its light weight, uarite identifies both browsers and crawlers more accurately than any competing implementation tested here. Despite being pure Python, it outperforms ua-parser's C++/Rust variants. We also provide a [JavaScript uarite](https://www.npmjs.com/package/@vasanko/uarite) with exact same output.
It returns structured classification, but also the thing most applications eventually need: **a short pretty description**.
## Usage
Add it to your project:
```sh
uv add uarite
```
## Usage
```python
from uarite import uaparse
+1
View File
@@ -14,6 +14,7 @@ authors = [
]
keywords = ["user-agent", "ua-parser"]
readme = "README.md"
license = "MIT OR Unlicense"
requires-python = ">=3.10"
classifiers = [
"Intended Audience :: Developers",
+68
View File
@@ -0,0 +1,68 @@
"""Generate the JS data tables for uarite-js from the Python source.
Run from the repository root:
uv run scripts/port_tables.py
Writes uarite-js/src/tables.ts. That file is generated — edit the Python
tables (uarite/bots.py, uarite/clients.py) instead and re-run this script.
"""
import json
from pathlib import Path
from uarite.bots import BOTS, KIND_LABEL, LABELED, PRETTY_OVERRIDE, PROVIDER_OF
from uarite.clients import BROWSERS, SAMSUNG, SAMSUNG_SERIES
OUT = Path(__file__).resolve().parent.parent / "uarite-js" / "src" / "tables.ts"
HEADER = """\
// Generated by scripts/port_tables.py from uarite/bots.py and
// uarite/clients.py. Do not edit by hand; re-run the script.
"""
def js(obj: object) -> str:
return json.dumps(obj, indent=2, ensure_ascii=False)
def main() -> None:
src = [HEADER]
src.append(
"/** UA token -> display name, checked in order; first hit wins. */\n"
f"export const BROWSERS: ReadonlyArray<readonly [string, string]> = {js(list(map(list, BROWSERS)))};\n"
)
src.append(
"/** Lowercase UA substring -> [display name, kind]. First match wins. */\n"
f"export const BOTS: Readonly<Record<string, readonly [string, string]>> = {js({k: list(v) for k, v in BOTS.items()})};\n"
)
src.append(
"/** Pretty suffixes for the kinds more precise than a generic spider. */\n"
f"export const KIND_LABEL: Readonly<Record<string, string>> = {js(KIND_LABEL)};\n"
)
src.append(
"/** Bot display name -> provider. */\n"
f"export const PROVIDER_OF: Readonly<Record<string, string>> = {js(PROVIDER_OF)};\n"
)
src.append(
"/** Per-bot pretty overrides: the full display string. */\n"
f"export const PRETTY_OVERRIDE: Readonly<Record<string, string>> = {js(PRETTY_OVERRIDE)};\n"
)
src.append(
"/** Bot names whose kind label is displayed. */\n"
f"export const LABELED: ReadonlySet<string> = new Set({js(sorted(LABELED))});\n"
)
src.append(
"/** Samsung model code (without region/carrier letter) -> marketing name. */\n"
f"export const SAMSUNG: Readonly<Record<string, string>> = {js(SAMSUNG)};\n"
)
src.append(
"/** Samsung series for codes missing from SAMSUNG. */\n"
f"export const SAMSUNG_SERIES: Readonly<Record<string, string>> = {js(SAMSUNG_SERIES)};\n"
)
OUT.write_text("\n".join(src))
print(f"wrote {OUT}")
if __name__ == "__main__":
main()
+3
View File
@@ -0,0 +1,3 @@
{
"semi": false
}
+89
View File
@@ -0,0 +1,89 @@
# User-Agent Parsing Done Right
Fast and accurate handling of modern browsers and crawlers. Despite its light weight and no dependencies, uarite identifies both browsers and crawlers more accurately than any competing implementation tested here. We also provide a [Python uarite](https://pypi.org/project/uarite/) with exact same output.
It returns structured classification, but also the thing most applications eventually need: **a short pretty description**.
## Usage
Add it to your project:
```sh
npm install @vasanko/uarite
```
```js
import { uaparse } from "@vasanko/uarite"
const { pretty, engine, os, kind } = uaparse(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36",
)
// Chrome/152 Windows, Chromium, Windows, browser
const { pretty, kind, url, provider } = uaparse(
"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; GPTBot/1.2; +https://openai.com/gptbot",
)
// GPTBot (AI), ai, https://openai.com/gptbot, OpenAI
```
Plain HTML? A prebuilt minified ESM bundle you can host yourself or link from CDN:
```html
<script type="module">
import { uaparse } from "https://cdn.jsdelivr.net/npm/@vasanko/uarite/dist/uarite.min.js"
console.log(uaparse(navigator.userAgent))
</script>
```
## Output
`uaparse(ua)` returns a `UA` object with string fields. Any field may be empty string when the information is unavailable.
| Field | Content |
| -------- | ------------------------------------------------ |
| pretty | Compact display string; raw UA when unrecognized |
| engine | Chromium, Gecko, Safari, ArkWeb |
| os | Windows, macOS, Linux, iOS, Android, HarmonyOS |
| kind | browser, ai, search, social, analytics, spider |
| url | Crawler information URL |
| provider | Provider of a known crawler family |
The pretty field is intended for UIs and logs. The url can be attached to it as a link when available.
The engine and os fields are intentionally broad. The kind field distinguishes browsers from AI collectors, search engines, social previews, monitoring tools, generic spiders, and ordinary HTTP clients. Any non-browser kind represents automated traffic.
Detection is necessarily limited by what the User-Agent reveals. Crawlers can masquerade as ordinary browsers or other crawlers, so sites that need stronger identification should use additional methods rather than relying on UA detection alone.
## Comparison
The popular npm options for this task are bowser and ua-parser-js. The table below compares representative User-Agent formats.
| Case | uarite¹ | ua-parser-js² | bowser³ |
| ---------------------------- | ------------------------- | ------------------------------------ | ------------------------------------ |
| Chrome, Windows | Chrome/152 Windows | Chrome/152 Windows | Chrome/152.0.0.0 Windows |
| Chrome, Android (no model) | Chrome/152 Android | Mobile Chrome/152 Android K❌ | Chrome/152.0.0.0 Android |
| Edge, Android (model code) | Edge/110 Galaxy S7 | Edge/110 Android SM-G930P | Microsoft Edge/110.0.1587.66 Android |
| Safari, iPhone | iPhone iOS 17 | Mobile Safari/17 iOS iPhone | Safari/17.0 iOS iPhone |
| Huawei HarmonyOS phone | HuaweiBrowser/6 HarmonyOS | Huawei Browser/6 HarmonyOS ALN-AL00 | Android Browser/ Android ❌ |
| GPTBot | GPTBot (AI) | WebKit/537 ❌ | GPTBot/1.2 |
| Googlebot (disguised) | Googlebot (search) | Mobile Chrome/122 Android Nexus 5 ❌ | Googlebot/2.1 Android❌ |
| Facebook preview (disguised) | Facebook | Mobile Chrome/134 Android Pixel 7 ❌ | FacebookExternalHit/ Android❌ |
| WhatsApp preview | WhatsApp | (nothing) ❌ | WhatsApp/2.23.20.0 |
| python-requests | python-requests/2.32.5 | (nothing) ❌ | (nothing) ❌ |
- ❌ marks incorrect data such as an OS from a crawler's disguise, a frozen compat placeholder reported as a device, or a missed identity
- ¹ `uaparse(ua).pretty` shown as is
- ² `{browser.name??''}/{browser.major??''} {os.name??''} {device.model??''}`; free MIT tier of v2
- ³ `{browser.name??''}/{browser.version??''} {os.name??''} {platform.model??''}`
Parsing a mixed set of 316 real-world browser and crawler UAs, parses per second: **uarite 580 000**, bowser 130 000 and ua-parser-js 18 000. The other parsers don't appear to implement caching. For previously seen UA strings, however, uarite reaches **5.6 million**, while all others remain at the rates quoted above.
All are relatively small: **uarite minifies to 9 kB**, bowser to 37 kB and ua-parser-js to 28 kB.
## Why yet another UA parser
Rather than relying on a large historical regex database, the parser focuses on modern UA formats and parses them directly, choosing the most specific interpretation available. This keeps the implementation small while handling today's browsers and crawler traffic well. Until now, I had been using those other modules and building my own pretty-UA formatting on top of them, fixing by post processing issues the upstream didn't care of.
Eventually it became easier to start over with a parser designed around modern traffic. The result is uarite.
Hopefully it helps you too. Star my [GitHub](https://github.com/leovasanko/uarite) if it did.
+1
View File
File diff suppressed because one or more lines are too long
+43
View File
@@ -0,0 +1,43 @@
{
"name": "@vasanko/uarite",
"version": "0.2.2",
"description": "User-Agent parsing done right. Accurate, small, dependency-free and fast.",
"keywords": [
"user-agent",
"ua-parser"
],
"homepage": "https://git.zi.fi/LeoVasanko/uarite",
"repository": "https://git.zi.fi/LeoVasanko/uarite",
"bugs": "https://github.com/LeoVasanko/uarite",
"license": "MIT OR Unlicense",
"publishConfig": {
"access": "public"
},
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"files": [
"dist"
],
"engines": {
"node": ">=18"
},
"scripts": {
"build": "tsc && npm run build:min",
"build:min": "esbuild src/index.ts --bundle --minify --format=esm --target=es2022 --outfile=dist/uarite.min.js",
"format": "prettier --write src test",
"format:check": "prettier --check src test",
"gen:tables": "cd .. && uv run scripts/port_tables.py && cd uarite-js && prettier --write src/tables.ts",
"test": "npm run build && node --test test/*.test.js",
"prepublishOnly": "npm run build && npm test"
},
"devDependencies": {
"esbuild": "^0.28.2",
"prettier": "^3.9.6",
"typescript": "^5.6.0"
}
}
+311
View File
@@ -0,0 +1,311 @@
import {
BOTS,
BROWSERS,
KIND_LABEL,
LABELED,
PRETTY_OVERRIDE,
PROVIDER_OF,
SAMSUNG,
SAMSUNG_SERIES,
} from "./tables.js"
/** Result of parsing a User-Agent string. Any field may be empty. */
export interface UA {
/** Compact display string; raw UA when unrecognized. */
pretty: string
/** Chromium, Gecko, Safari, ArkWeb. */
engine: string
/** Windows, macOS, Linux, iOS, Android, HarmonyOS. */
os: string
/** browser, ai, search, social, analytics, spider. */
kind: string
/** Crawler information URL. */
url: string
/** Provider of a known crawler family. */
provider: string
}
const EMPTY: UA = {
pretty: "",
engine: "",
os: "",
kind: "",
url: "",
provider: "",
}
/** Fallback for unknown crawlers: a product token whose name says so. */
const BOT_TOKEN = /[^\s();/]*(?:bot|spider|crawl|scan|verif|check)[^\s();/]*/i
/** A "+https://…" pointer is a crawler tell; real browsers carry no URL. */
const URL = /\+\s*(https?:\/\/[^\s;)]+)/
const ANY_URL = /(https?:\/\/[^\s;)]+)/
/** Crawler name next to the info URL: "compatible; Page2RSS/0.7; +http://…". */
const COMPATIBLE_NAME = /compatible;\s*([^;/()]+?)(?:\/[\d.vx]+)?\s*;/
/** Name from an info URL's host when no product token is available. */
const HOST = /https?:\/\/(?:www\.)?([^/\s;)]+)/
/** Android model token: "Android 15; SM-S918B)", "Android 12; Pixel 6; Build/…". */
const ANDROID_MODEL = /Android [\d.]+; ([^;()]+?)(?:;|\)| Build\/)/
/** All known-bot substrings in one compiled pass. */
const BOTS_RE = new RegExp(
Object.keys(BOTS)
.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
.join("|"),
)
/** The crawler's info URL from the UA, or "" (mailto: is not a URL). */
export function url(ua: string): string {
const m = URL.exec(ua) ?? ANY_URL.exec(ua)
return m ? m[1] : ""
}
/** (display name, kind) of the crawler/unfurler the UA claims. */
export function bot(ua: string): readonly [string, string] {
const low = ua.toLowerCase()
const m = BOTS_RE.exec(low)
if (m) return BOTS[m[0]]
// Cheap keyword gates keep the regexes off the hot path.
if (/(?:bot|spider|crawl|scan|verif|check)/.test(low)) {
const t = BOT_TOKEN.exec(ua)
if (t) {
const name = t[0].replace(/^;+|;+$/g, "")
return [name[0].toUpperCase() + name.slice(1), "spider"]
}
}
// An info URL in the UA is a crawler convention. Name it from the
// "compatible; Name/x" token, else the first product token, else the
// URL's host.
if (ua.includes("://")) {
let name = ""
const cm = COMPATIBLE_NAME.exec(ua)
if (cm) {
name = cm[1].trim()
} else if (!ua.startsWith("Mozilla")) {
name = ua.split(" ")[0].split("/")[0]
}
const nl = name.toLowerCase()
if (!name || nl.startsWith("mozilla") || nl.startsWith("msie")) {
const hm = HOST.exec(ua)
name = hm ? hm[1] : ""
}
if (name) return [name[0].toUpperCase() + name.slice(1), "spider"]
}
return ["", ""]
}
/** Major version of a `token/x.y` product in the UA, or "". */
export function version(ua: string, token: string): string {
const m = new RegExp(
`${token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/(\\d+)`,
).exec(ua)
return m ? m[1] : ""
}
/** `Browser/major` for the browsers we care to distinguish. */
export function browser(ua: string): string {
for (const [token, name] of BROWSERS) {
const ver = version(ua, token)
if (ver) return `${name}/${ver}`
}
if (ua.includes("Safari/")) {
const ver = version(ua, "Version")
return ver ? `Safari/${ver}` : "Safari"
}
return ""
}
/** Engines that differ from the Chromium default for recognized browsers. */
const ENGINES: Readonly<Record<string, string>> = {
Firefox: "Gecko",
LibreWolf: "Gecko",
Safari: "Safari",
}
/** Oldest plausible major versions (≈2023 releases); see the Python source. */
const ANCIENT: Readonly<Record<string, number>> = {
Firefox: 108,
Chrome: 108,
Edge: 108,
Opera: 95,
}
/** True when a `Browser/major` claims an impossibly old version. */
export function spoofed(b: string): boolean {
const i = b.indexOf("/")
const name = i < 0 ? b : b.slice(0, i)
const ver = i < 0 ? "" : b.slice(i + 1)
const floor = ANCIENT[name]
return floor !== undefined && /^\d+$/.test(ver) && Number(ver) < floor
}
/** Engine for a `Browser/major` result; Chromium is the modern default. */
export function engine(b: string): string {
const name = b.split("/")[0]
return ENGINES[name] ?? (name ? "Chromium" : "")
}
/** Desktop OS name, or "" when not recognizable. */
export function os(ua: string): string {
if (ua.includes("Windows NT")) return "Windows"
if (ua.includes("Mac OS X")) return "macOS"
if (ua.includes("Linux") || ua.includes("X11")) return "Linux"
if (ua.includes("Windows")) return "Windows"
if (ua.includes("Darwin")) return "macOS"
return ""
}
/**
* Human-readable phone name for an Android model code.
*
* Returns the input unchanged when nothing is known about it (Pixel and
* most other brands already send readable names).
*/
export function modelName(model: string): string {
if (model.startsWith("SM-")) {
// Strip the region/carrier suffix: SM-S918B -> SM-S918, and the
// Chinese/HK variant's trailing zero: SM-S9370 -> SM-S937.
let code = model.replace(/[A-Z]{1,2}$/, "")
if (!(code in SAMSUNG) && code.endsWith("0")) code = code.slice(0, -1)
if (code in SAMSUNG) return SAMSUNG[code]
const series = SAMSUNG_SERIES[code.slice(0, 4)]
if (series) return series
}
return model
}
const CACHE_MAX = 1024
const cache = new Map<string, UA>()
/** Parse a User-Agent string into a compact {@link UA} record. */
export function uaparse(ua: string | null | undefined): UA {
if (!ua || !ua.trim() || ua === "-" || ua === "null") return EMPTY
const hit = cache.get(ua)
if (hit) {
// Refresh recency, mirroring Python's lru_cache.
cache.delete(ua)
cache.set(ua, hit)
return hit
}
const r = parse(ua)
if (cache.size >= CACHE_MAX) {
cache.delete(cache.keys().next().value as string)
}
cache.set(ua, r)
return r
}
function parse(ua: string): UA {
const [name, kind] = bot(ua)
if (name) {
// The browser/OS in crawler UAs is a disguise; the bot identity is
// the relevant information, so `engine` and `os` are left empty.
let pretty = PRETTY_OVERRIDE[name]
if (pretty === undefined) {
const label = LABELED.has(name) ? (KIND_LABEL[kind] ?? "") : ""
pretty = label ? `${name} (${label})` : name
}
return {
...EMPTY,
pretty,
kind,
url: url(ua),
provider: PROVIDER_OF[name] ?? "",
}
}
return parseClient(ua)
}
function parseClient(ua: string): UA {
const r = client(ua)
// Frozen ancient browser strings are scanners/scripts, not users: show
// the claimed browser, but mark it and drop the fake engine/os/kind.
if (r.kind === "browser" && spoofed(browser(ua))) {
return { ...EMPTY, pretty: `${r.pretty} (spoofed)` }
}
return r
}
function client(ua: string): UA {
// Non-browser HTTP clients ("python-requests/2.32.5", "curl/8.0",
// "pip/24.3.1 {json…}"): the first product token, plus the OS when
// their payload mentions one in free text.
if (!ua.startsWith("Mozilla")) {
const token = ua.split(" ")[0]
let pretty = token.includes("/") ? token : ua
const osName = os(ua)
if (osName && !pretty.includes(osName)) pretty = `${pretty} ${osName}`
return { ...EMPTY, pretty, os: osName }
}
// HarmonyOS carries an "Android" compatibility token, so it must be
// detected before Android.
if (
ua.includes("OpenHarmony") ||
ua.includes("HarmonyOS") ||
ua.includes("ArkWeb")
) {
const b = browser(ua)
return {
...EMPTY,
pretty: b ? `${b} HarmonyOS` : "HarmonyOS",
engine: "ArkWeb",
os: "HarmonyOS",
kind: "browser",
}
}
if (ua.includes("iPhone") || ua.includes("iPad")) {
const device = ua.includes("iPhone") ? "iPhone" : "iPad"
const m = /OS (\d+)/.exec(ua)
return {
...EMPTY,
pretty: m ? `${device} iOS ${m[1]}` : device,
engine: "Safari",
os: "iOS",
kind: "browser",
}
}
const am = /Android ([\d.]+)/.exec(ua)
if (am) {
const b = browser(ua)
const mm = ANDROID_MODEL.exec(ua)
const token = mm ? mm[1].trim() : ""
let parts: string[]
if (token === "K") {
// Chrome's reduced UA freezes both: "Android 10; K". Neither
// is real — report just the OS.
parts = [b, "Android"].filter(Boolean)
} else {
// Firefox sends the form factor ("Mobile"/"Tablet") in the model
// slot. A known model replaces the OS.
let model = ""
if (token && !["wv", "Mobile", "Tablet"].includes(token)) {
model = modelName(token)
}
parts = [b, model || `Android ${am[1]}`].filter(Boolean)
}
return {
...EMPTY,
pretty: parts.join(" "),
engine: engine(b),
os: "Android",
kind: "browser",
}
}
const b = browser(ua)
const osName = os(ua)
const pretty = `${b} ${osName}`.trim()
return {
...EMPTY,
pretty: pretty || ua,
engine: engine(b),
os: osName,
kind: "browser",
}
}
+231
View File
@@ -0,0 +1,231 @@
// Generated by scripts/port_tables.py from uarite/bots.py and
// uarite/clients.py. Do not edit by hand; re-run the script.
/** UA token -> display name, checked in order; first hit wins. */
export const BROWSERS: ReadonlyArray<readonly [string, string]> = [
["HuaweiBrowser", "HuaweiBrowser"],
["EdgA", "Edge"],
["Edg", "Edge"],
["OPR", "Opera"],
["Vivaldi", "Vivaldi"],
["YaBrowser", "Yandex"],
["Brave", "Brave"],
["Whale", "Whale"],
["SamsungBrowser", "Samsung Internet"],
["MiuiBrowser", "Mi Browser"],
["UCBrowser", "UC Browser"],
["QQBrowser", "QQ Browser"],
["DuckDuckGo", "DuckDuckGo"],
["LibreWolf", "LibreWolf"],
["Firefox", "Firefox"],
["Chrome", "Chrome"],
["CriOS", "Chrome"],
["FxiOS", "Firefox"],
]
/** Lowercase UA substring -> [display name, kind]. First match wins. */
export const BOTS: Readonly<Record<string, readonly [string, string]>> = {
"mozilla/5.0 (x11; linux x86_64; rv:45.0) gecko/20100101 firefox/45.0": [
"Qualys SSL Labs",
"spider",
],
"feedfetcher-google": ["Feedfetcher-Google", "search"],
"google-inspectiontool": ["Google-InspectionTool", "search"],
"google-read-aloud": ["Google-Read-Aloud", "ai"],
"mediapartners-google": ["Mediapartners-Google", "analytics"],
"adsbot-google": ["AdsBot-Google", "analytics"],
"apis-google": ["APIs-Google", "spider"],
"storebot-google": ["Storebot-Google", "search"],
"google-extended": ["Google-Extended", "ai"],
googlebot: ["Googlebot", "search"],
googleother: ["GoogleOther", "ai"],
bingbot: ["Bingbot", "search"],
applebot: ["Applebot", "search"],
gptbot: ["GPTBot", "ai"],
"oai-searchbot": ["OAI-SearchBot", "search"],
"chatgpt-user": ["ChatGPT-User", "ai"],
"claude-searchbot": ["Claude-SearchBot", "search"],
claudebot: ["ClaudeBot", "ai"],
"claude-user": ["Claude-User", "ai"],
"perplexity-user": ["Perplexity-User", "ai"],
perplexitybot: ["PerplexityBot", "search"],
grokbot: ["GrokBot", "ai"],
bytespider: ["Bytespider", "ai"],
reflectionbot: ["Reflectionbot", "ai"],
"amzn-searchbot": ["Amzn-SearchBot", "search"],
amazonbot: ["Amazonbot", "search"],
ahrefsbot: ["AhrefsBot", "search"],
mj12bot: ["MJ12bot", "analytics"],
facebookexternalhit: ["Facebook", "social"],
"meta-externalagent": ["Meta-ExternalAgent", "ai"],
"meta-externalfetcher": ["Meta-ExternalFetcher", "ai"],
"meta-webindexer": ["Meta-WebIndexer", "search"],
bingpreview: ["BingPreview", "search"],
pinterest: ["Pinterest", "social"],
embedly: ["Embedly", "social"],
iframely: ["Iframely", "social"],
discordbot: ["Discord", "social"],
slackbot: ["Slack", "social"],
telegrambot: ["Telegram", "social"],
twitterbot: ["Twitter", "social"],
linkedinbot: ["LinkedIn", "social"],
whatsapp: ["WhatsApp", "social"],
headlesschrome: ["HeadlessChrome", "spider"],
uptimerobot: ["UptimeRobot", "analytics"],
pingdom: ["Pingdom", "analytics"],
}
/** Pretty suffixes for the kinds more precise than a generic spider. */
export const KIND_LABEL: Readonly<Record<string, string>> = {
ai: "AI",
search: "search",
social: "social",
analytics: "analytics",
}
/** Bot display name -> provider. */
export const PROVIDER_OF: Readonly<Record<string, string>> = {
GoogleOther: "Google",
"Mediapartners-Google": "Google",
Googlebot: "Google",
"Storebot-Google": "Google",
"APIs-Google": "Google",
"Google-Extended": "Google",
"Google-Read-Aloud": "Google",
"Feedfetcher-Google": "Google",
"AdsBot-Google": "Google",
"Google-InspectionTool": "Google",
"Claude-User": "Anthropic",
"Claude-SearchBot": "Anthropic",
ClaudeBot: "Anthropic",
GPTBot: "OpenAI",
"ChatGPT-User": "OpenAI",
"OAI-SearchBot": "OpenAI",
"Perplexity-User": "Perplexity",
PerplexityBot: "Perplexity",
Amazonbot: "Amazon",
"Amzn-SearchBot": "Amazon",
Bingbot: "Microsoft",
BingPreview: "Microsoft",
"Meta-ExternalFetcher": "Meta",
"Meta-WebIndexer": "Meta",
Facebook: "Meta",
"Meta-ExternalAgent": "Meta",
}
/** Per-bot pretty overrides: the full display string. */
export const PRETTY_OVERRIDE: Readonly<Record<string, string>> = {
Facebook: "Facebook",
"Feedfetcher-Google": "Google Feedfetcher (search)",
"Google-InspectionTool": "Google InspectionTool (search)",
"Google-Read-Aloud": "Google Read-Aloud (AI)",
"Mediapartners-Google": "Google Mediapartners (analytics)",
"AdsBot-Google": "Google AdsBot (analytics)",
"APIs-Google": "Google APIs",
"Storebot-Google": "Google Storebot (search)",
"Google-Extended": "Google Extended (AI)",
GoogleOther: "Google Other (AI)",
}
/** Bot names whose kind label is displayed. */
export const LABELED: ReadonlySet<string> = new Set([
"APIs-Google",
"AdsBot-Google",
"ChatGPT-User",
"Claude-SearchBot",
"Claude-User",
"ClaudeBot",
"Facebook",
"Feedfetcher-Google",
"GPTBot",
"Google-Extended",
"Google-InspectionTool",
"Google-Read-Aloud",
"GoogleOther",
"Googlebot",
"Mediapartners-Google",
"Meta-ExternalAgent",
"Meta-ExternalFetcher",
"Meta-WebIndexer",
"OAI-SearchBot",
"Perplexity-User",
"PerplexityBot",
"Storebot-Google",
])
/** Samsung model code (without region/carrier letter) -> marketing name. */
export const SAMSUNG: Readonly<Record<string, string>> = {
"SM-G930": "Galaxy S7",
"SM-G935": "Galaxy S7 Edge",
"SM-G950": "Galaxy S8",
"SM-G955": "Galaxy S8+",
"SM-G960": "Galaxy S9",
"SM-G965": "Galaxy S9+",
"SM-G970": "Galaxy S10e",
"SM-G973": "Galaxy S10",
"SM-G975": "Galaxy S10+",
"SM-G977": "Galaxy S10 5G",
"SM-G980": "Galaxy S20",
"SM-G981": "Galaxy S20",
"SM-G985": "Galaxy S20+",
"SM-G986": "Galaxy S20+",
"SM-G988": "Galaxy S20 Ultra",
"SM-G990": "Galaxy S21 FE",
"SM-G991": "Galaxy S21",
"SM-G996": "Galaxy S21+",
"SM-G998": "Galaxy S21 Ultra",
"SM-S901": "Galaxy S22",
"SM-S906": "Galaxy S22+",
"SM-S908": "Galaxy S22 Ultra",
"SM-S911": "Galaxy S23",
"SM-S916": "Galaxy S23+",
"SM-S918": "Galaxy S23 Ultra",
"SM-S921": "Galaxy S24",
"SM-S926": "Galaxy S24+",
"SM-S928": "Galaxy S24 Ultra",
"SM-S931": "Galaxy S25",
"SM-S936": "Galaxy S25+",
"SM-S937": "Galaxy S25 Edge",
"SM-S938": "Galaxy S25 Ultra",
"SM-S942": "Galaxy S26",
"SM-S946": "Galaxy S26+",
"SM-S948": "Galaxy S26 Ultra",
"SM-N930": "Galaxy Note 7",
"SM-N950": "Galaxy Note 8",
"SM-N960": "Galaxy Note 9",
"SM-N970": "Galaxy Note 10",
"SM-N975": "Galaxy Note 10+",
"SM-N980": "Galaxy Note 20",
"SM-N981": "Galaxy Note 20",
"SM-N985": "Galaxy Note 20 Ultra",
"SM-N986": "Galaxy Note 20 Ultra",
"SM-F700": "Galaxy Z Flip",
"SM-F707": "Galaxy Z Flip 5G",
"SM-F711": "Galaxy Z Flip3",
"SM-F721": "Galaxy Z Flip4",
"SM-F731": "Galaxy Z Flip5",
"SM-F741": "Galaxy Z Flip6",
"SM-F766": "Galaxy Z Flip7",
"SM-F900": "Galaxy Fold",
"SM-F907": "Galaxy Fold 5G",
"SM-F916": "Galaxy Z Fold2",
"SM-F926": "Galaxy Z Fold3",
"SM-F936": "Galaxy Z Fold4",
"SM-F946": "Galaxy Z Fold5",
"SM-F956": "Galaxy Z Fold6",
"SM-F966": "Galaxy Z Fold7",
}
/** Samsung series for codes missing from SAMSUNG. */
export const SAMSUNG_SERIES: Readonly<Record<string, string>> = {
"SM-S": "Galaxy S",
"SM-G": "Galaxy S",
"SM-N": "Galaxy Note",
"SM-A": "Galaxy A",
"SM-J": "Galaxy J",
"SM-M": "Galaxy M",
"SM-E": "Galaxy E",
"SM-F": "Galaxy Z",
"SM-T": "Galaxy Tab",
"SM-X": "Galaxy Tab",
}
+145
View File
@@ -0,0 +1,145 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { uaparse } from "../dist/index.js"
test("empty and missing UAs", () => {
for (const ua of ["", " ", "-", "null", null, undefined]) {
assert.deepEqual(uaparse(ua), {
pretty: "",
engine: "",
os: "",
kind: "",
url: "",
provider: "",
})
}
})
test("Chrome on Windows", () => {
const r = uaparse(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36",
)
assert.equal(r.pretty, "Chrome/152 Windows")
assert.equal(r.engine, "Chromium")
assert.equal(r.os, "Windows")
assert.equal(r.kind, "browser")
assert.equal(r.url, "")
})
test("Safari on macOS", () => {
const r = uaparse(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Safari/605.1.15",
)
assert.equal(r.pretty, "Safari/18 macOS")
assert.equal(r.engine, "Safari")
})
test("Firefox on Android keeps the OS version", () => {
const r = uaparse(
"Mozilla/5.0 (Android 15; Mobile; rv:154.0) Gecko/154.0 Firefox/154.0",
)
assert.equal(r.pretty, "Firefox/154 Android 15")
assert.equal(r.engine, "Gecko")
assert.equal(r.os, "Android")
})
test("Chrome on Android with a Pixel model", () => {
const r = uaparse(
"Mozilla/5.0 (Linux; Android 12; Pixel 6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",
)
assert.equal(r.pretty, "Chrome/118 Pixel 6")
assert.equal(r.os, "Android")
})
test("Samsung model codes resolve to marketing names", () => {
const r = uaparse(
"Mozilla/5.0 (Linux; Android 13; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",
)
assert.equal(r.pretty, "Chrome/118 Galaxy S23 Ultra")
})
test("Chrome reduced UA (Android 10; K)", () => {
const r = uaparse(
"Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Mobile Safari/537.36",
)
assert.equal(r.pretty, "Chrome/152 Android")
})
test("iPhone", () => {
const r = uaparse(
"Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1",
)
assert.equal(r.pretty, "iPhone iOS 17")
assert.equal(r.engine, "Safari")
assert.equal(r.os, "iOS")
})
test("HarmonyOS before Android", () => {
const r = uaparse(
"Mozilla/5.0 (Linux; Android 12; HarmonyOS; ALN-AL00; HMSCore 6.13.0.312) AppleWebKit/537.36 (KHTML, like Gecko) HuaweiBrowser/6.0.1.311 Mobile Safari/537.36",
)
assert.equal(r.pretty, "HuaweiBrowser/6 HarmonyOS")
assert.equal(r.engine, "ArkWeb")
assert.equal(r.os, "HarmonyOS")
})
test("ancient browser versions are marked spoofed", () => {
const r = uaparse(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.0.0 Safari/537.36",
)
assert.equal(r.pretty, "Chrome/60 Windows (spoofed)")
assert.equal(r.kind, "")
})
test("HTTP clients", () => {
assert.equal(
uaparse("python-requests/2.32.5").pretty,
"python-requests/2.32.5",
)
assert.equal(uaparse("curl/8.0").pretty, "curl/8.0")
})
test("GPTBot", () => {
const r = uaparse(
"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; GPTBot/1.2; +https://openai.com/gptbot",
)
assert.equal(r.pretty, "GPTBot (AI)")
assert.equal(r.kind, "ai")
assert.equal(r.provider, "OpenAI")
assert.equal(r.url, "https://openai.com/gptbot")
})
test("Facebook external hit, disguised as Chrome on Android", () => {
const r = uaparse(
"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.6885.65 Mobile Safari/537.36; compatible; facebookexternalhit/1.1; +http://www.facebook.com/externalhit_uatext.php",
)
assert.equal(r.pretty, "Facebook")
assert.equal(r.kind, "social")
assert.equal(r.provider, "Meta")
assert.equal(r.url, "http://www.facebook.com/externalhit_uatext.php")
})
test("unknown bot from product token", () => {
const r = uaparse("NewBot/1.0 (+https://example.com/bot)")
assert.equal(r.pretty, "NewBot")
assert.equal(r.kind, "spider")
})
test("named from compatible token", () => {
const r = uaparse(
"Mozilla/5.0 (compatible; Page2RSS/0.7; +http://page2rss.com/)",
)
assert.equal(r.pretty, "Page2RSS")
assert.equal(r.kind, "spider")
})
test("unrecognized Mozilla UA falls back to the raw string", () => {
const ua = "Mozilla/5.0 (something entirely unknown)"
assert.equal(uaparse(ua).pretty, ua)
})
test("results are cached", () => {
const ua =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36"
assert.equal(uaparse(ua), uaparse(ua))
})
+14
View File
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"outDir": "dist",
"declaration": true,
"strict": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true
},
"include": ["src"]
}