@usenotra/geo
Version:
Request capture SDK for AI traffic attribution and agent feedback collection
1,435 lines (1,422 loc) • 41.6 kB
JavaScript
// src/signatures.ts
var AI_AGENT_SIGNATURES = [
{
agent: "GPTBot",
vendor: "OpenAI",
category: "training-crawler",
userAgents: ["GPTBot"],
confidence: "verified",
verification: "https://openai.com/gptbot.json",
source: "https://developers.openai.com/api/docs/bots"
},
{
agent: "OAI-SearchBot",
vendor: "OpenAI",
category: "search-index",
userAgents: ["OAI-SearchBot"],
confidence: "verified",
verification: "https://openai.com/searchbot.json",
source: "https://developers.openai.com/api/docs/bots"
},
{
agent: "ChatGPT-User",
vendor: "OpenAI",
category: "assistant-browse",
userAgents: ["ChatGPT-User"],
confidence: "verified",
verification: "https://openai.com/chatgpt-user.json",
source: "https://developers.openai.com/api/docs/bots"
},
{
agent: "OAI-AdsBot",
vendor: "OpenAI",
category: "search-index",
userAgents: ["OAI-AdsBot"],
confidence: "verified",
verification: "https://openai.com/adsbot.json",
source: "https://developers.openai.com/api/docs/bots"
},
{
agent: "Claude Code",
vendor: "Anthropic",
category: "assistant-browse",
userAgents: ["claude-code/"],
confidence: "reported",
verification: null,
source: "https://github.com/monperrus/crawler-user-agents"
},
{
agent: "Claude-SearchBot",
vendor: "Anthropic",
category: "search-index",
userAgents: ["Claude-SearchBot"],
confidence: "verified",
verification: "https://claude.com/crawling/bots.json",
source: "https://support.claude.com/en/articles/8896518-does-anthropic-crawl-data-from-the-web-and-how-can-site-owners-block-the-crawler"
},
{
agent: "Claude-User",
vendor: "Anthropic",
category: "assistant-browse",
userAgents: ["Claude-User"],
confidence: "verified",
verification: "https://claude.com/crawling/bots.json",
source: "https://support.claude.com/en/articles/8896518-does-anthropic-crawl-data-from-the-web-and-how-can-site-owners-block-the-crawler"
},
{
agent: "ClaudeBot",
vendor: "Anthropic",
category: "training-crawler",
userAgents: ["ClaudeBot"],
confidence: "verified",
verification: "https://claude.com/crawling/bots.json",
source: "https://support.claude.com/en/articles/8896518-does-anthropic-crawl-data-from-the-web-and-how-can-site-owners-block-the-crawler"
},
{
agent: "anthropic-ai",
vendor: "Anthropic",
category: "training-crawler",
userAgents: ["anthropic-ai"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "claude-web",
vendor: "Anthropic",
category: "assistant-browse",
userAgents: ["claude-web"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "PerplexityBot",
vendor: "Perplexity",
category: "search-index",
userAgents: ["PerplexityBot"],
confidence: "verified",
verification: "https://www.perplexity.ai/perplexitybot.json",
source: "https://docs.perplexity.ai/docs/resources/perplexity-crawlers"
},
{
agent: "Perplexity-User",
vendor: "Perplexity",
category: "assistant-browse",
userAgents: ["Perplexity-User"],
confidence: "verified",
verification: "https://www.perplexity.ai/perplexity-user.json",
source: "https://docs.perplexity.ai/docs/resources/perplexity-crawlers"
},
{
agent: "Google-CloudVertexBot",
vendor: "Google",
category: "search-index",
userAgents: ["Google-CloudVertexBot"],
confidence: "verified",
verification: "https://developers.google.com/static/crawling/ipranges/common-crawlers.json",
source: "https://developers.google.com/crawling/docs/crawlers-fetchers/google-common-crawlers"
},
{
agent: "GoogleOther-Image",
vendor: "Google",
category: "training-crawler",
userAgents: ["GoogleOther-Image"],
confidence: "heuristic",
verification: "https://developers.google.com/static/crawling/ipranges/common-crawlers.json",
source: "https://developers.google.com/crawling/docs/crawlers-fetchers/google-common-crawlers"
},
{
agent: "GoogleOther-Video",
vendor: "Google",
category: "training-crawler",
userAgents: ["GoogleOther-Video"],
confidence: "heuristic",
verification: "https://developers.google.com/static/crawling/ipranges/common-crawlers.json",
source: "https://developers.google.com/crawling/docs/crawlers-fetchers/google-common-crawlers"
},
{
agent: "GoogleOther",
vendor: "Google",
category: "training-crawler",
userAgents: ["GoogleOther"],
confidence: "heuristic",
verification: "https://developers.google.com/static/crawling/ipranges/common-crawlers.json",
source: "https://developers.google.com/crawling/docs/crawlers-fetchers/google-common-crawlers"
},
{
agent: "Bytespider",
vendor: "ByteDance",
category: "training-crawler",
userAgents: ["Bytespider"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "Amazonbot",
vendor: "Amazon",
category: "training-crawler",
userAgents: ["Amazonbot"],
confidence: "verified",
verification: "https://developer.amazon.com/amazonbot/ip-addresses/",
source: "https://developer.amazon.com/amazonbot"
},
{
agent: "Amzn-SearchBot",
vendor: "Amazon",
category: "search-index",
userAgents: ["Amzn-SearchBot"],
confidence: "verified",
verification: "https://developer.amazon.com/amazonbot/searchbot-ip-addresses/",
source: "https://developer.amazon.com/amazonbot"
},
{
agent: "Amzn-User",
vendor: "Amazon",
category: "assistant-browse",
userAgents: ["Amzn-User"],
confidence: "verified",
verification: "https://developer.amazon.com/amazonbot/live-ip-addresses/",
source: "https://developer.amazon.com/amazonbot"
},
{
agent: "Applebot",
vendor: "Apple",
category: "search-index",
userAgents: ["Applebot/"],
confidence: "verified",
verification: "https://search.developer.apple.com/applebot.json",
source: "https://support.apple.com/en-us/119829"
},
{
agent: "cohere-training-data-crawler",
vendor: "Cohere",
category: "training-crawler",
userAgents: ["cohere-training-data-crawler"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "cohere-ai",
vendor: "Cohere",
category: "assistant-browse",
userAgents: ["cohere-ai"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "meta-externalagent",
vendor: "Meta",
category: "training-crawler",
userAgents: ["meta-externalagent"],
confidence: "verified",
verification: null,
source: "https://developers.facebook.com/documentation/sharing/webmasters/web-crawlers"
},
{
agent: "meta-externalfetcher",
vendor: "Meta",
category: "assistant-browse",
userAgents: ["meta-externalfetcher"],
confidence: "verified",
verification: null,
source: "https://developers.facebook.com/documentation/sharing/webmasters/web-crawlers"
},
{
agent: "meta-webindexer",
vendor: "Meta",
category: "search-index",
userAgents: ["meta-webindexer"],
confidence: "verified",
verification: null,
source: "https://developers.facebook.com/docs/sharing/webmasters/web-crawlers/"
},
{
agent: "meta-externalads",
vendor: "Meta",
category: "search-index",
userAgents: ["meta-externalads"],
confidence: "verified",
verification: null,
source: "https://developers.facebook.com/docs/sharing/webmasters/web-crawlers/"
},
{
agent: "FacebookBot",
vendor: "Meta",
category: "training-crawler",
userAgents: ["FacebookBot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "DuckAssistBot",
vendor: "DuckDuckGo",
category: "assistant-browse",
userAgents: ["DuckAssistBot"],
confidence: "verified",
verification: "https://duckduckgo.com/duckassistbot.json",
source: "https://duckduckgo.com/duckduckgo-help-pages/results/duckassistbot/"
},
{
agent: "LinerBot",
vendor: "Liner",
category: "search-index",
userAgents: ["LinerBot"],
confidence: "verified",
verification: "https://docs.getliner.com/linerbot.json",
source: "https://docs.getliner.com/docs/linerbot"
},
{
agent: "YouBot",
vendor: "You.com",
category: "search-index",
userAgents: ["YouBot"],
confidence: "verified",
verification: "https://you.com/.well-known/http-message-signatures-directory",
source: "https://you.com/docs/youbot"
},
{
agent: "MistralAI-User",
vendor: "Mistral",
category: "assistant-browse",
userAgents: ["MistralAI-User"],
confidence: "verified",
verification: "https://mistral.ai/mistralai-user-ips.json",
source: "https://docs.mistral.ai/robots"
},
{
agent: "CCBot",
vendor: "Common Crawl",
category: "training-crawler",
userAgents: ["CCBot"],
confidence: "heuristic",
verification: "https://index.commoncrawl.org/ccbot.json",
source: "https://commoncrawl.org/ccbot"
},
{
agent: "Diffbot",
vendor: "Diffbot",
category: "search-index",
userAgents: ["Diffbot"],
confidence: "verified",
verification: null,
source: "https://www.diffbot.com/docs/crawl/faq/robots-txt"
},
{
agent: "Timpibot",
vendor: "Timpi",
category: "training-crawler",
userAgents: ["Timpibot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "Devin",
vendor: "Cognition",
category: "assistant-browse",
userAgents: ["Devin/"],
confidence: "reported",
verification: null,
source: "https://radar.cloudflare.com/bots/directory/devin"
},
{
agent: "Google-Agent",
vendor: "Google",
category: "assistant-browse",
userAgents: ["Google-Agent"],
confidence: "verified",
verification: "https://developers.google.com/static/crawling/ipranges/user-triggered-agents.json",
source: "https://developers.google.com/crawling/docs/crawlers-fetchers/google-user-triggered-fetchers"
},
{
agent: "Google-GeminiNotebook",
vendor: "Google",
category: "assistant-browse",
userAgents: ["Google-GeminiNotebook"],
confidence: "verified",
verification: "https://developers.google.com/static/crawling/ipranges/user-triggered-fetchers-google.json",
source: "https://developers.google.com/crawling/docs/crawlers-fetchers/google-user-triggered-fetchers"
},
{
agent: "Gemini CLI",
vendor: "Google",
category: "assistant-browse",
userAgents: ["GoogleAgent-URLContext"],
confidence: "reported",
verification: null,
source: "https://www.checklyhq.com/blog/state-of-ai-agent-content-negotation/"
},
{
agent: "Gemini CLI (legacy)",
vendor: "Google",
category: "assistant-browse",
userAgents: ["Google-Gemini-CLI"],
confidence: "reported",
verification: null,
source: "https://knownagents.com/agents/google-gemini-cli"
},
{
agent: "Gemini",
vendor: "Google",
category: "assistant-browse",
userAgents: ["Google"],
match: "exact",
confidence: "reported",
verification: null,
source: "https://developers.google.com/crawling/docs/crawlers-fetchers/google-user-triggered-fetchers"
},
{
agent: "OpenCode",
vendor: "OpenCode",
category: "assistant-browse",
userAgents: ["opencode"],
match: "exact",
confidence: "reported",
verification: null,
source: "https://github.com/sst/opencode"
},
{
agent: "Cursor",
vendor: "Anysphere",
category: "assistant-browse",
userAgents: ["Cursor/"],
confidence: "reported",
verification: null,
source: "https://cursor.com/download"
},
{
agent: "Cline",
vendor: "Cline Bot",
category: "assistant-browse",
userAgents: [
"Mozilla/5.0 (compatible; AgentBot/1.0)",
"VSCodeExtension/1.0; +https://cline.bot"
],
confidence: "reported",
verification: null,
source: "https://github.com/cline/cline/blob/main/apps/vscode/src/integrations/misc/link-preview.ts"
},
{
agent: "Trae-Agent",
vendor: "ByteDance",
category: "assistant-browse",
userAgents: ["Trae-Agent"],
confidence: "reported",
verification: null,
source: "https://knownagents.com/agents/trae"
},
{
agent: "omgili",
vendor: "Webz.io",
category: "training-crawler",
userAgents: ["omgilibot", "omgili"],
confidence: "heuristic",
verification: null,
source: "https://webz.io/blog/web-data/what-is-the-omgili-bot-and-why-is-it-crawling-your-website/"
},
{
agent: "Mozilla Tabstack",
vendor: "Mozilla",
category: "assistant-browse",
userAgents: ["Mozilla-Tabstack"],
confidence: "verified",
verification: null,
source: "https://docs.tabstack.ai/trust/controlling-access"
},
{
agent: "AI2Bot",
vendor: "Ai2",
category: "training-crawler",
userAgents: ["AI2Bot"],
confidence: "verified",
verification: null,
source: "https://allenai.org/crawler"
},
{
agent: "Kimi-User",
vendor: "Moonshot AI",
category: "assistant-browse",
userAgents: ["Kimi-User"],
confidence: "verified",
verification: "https://www.kimi.ai/policies/kimi-user.json",
source: "https://www.kimi.ai/policies/kimi-crawlers"
},
{
agent: "KimiBot",
vendor: "Moonshot AI",
category: "training-crawler",
userAgents: ["KimiBot"],
confidence: "verified",
verification: "https://www.kimi.ai/policies/kimibot.json",
source: "https://www.kimi.ai/policies/kimi-crawlers"
},
{
agent: "Kimi-SearchBot",
vendor: "Moonshot AI",
category: "search-index",
userAgents: ["Kimi-SearchBot"],
confidence: "verified",
verification: "https://www.kimi.ai/policies/kimi-searchbot.json",
source: "https://www.kimi.ai/policies/kimi-crawlers"
},
{
agent: "ChatGLM-Spider",
vendor: "Zhipu AI",
category: "training-crawler",
userAgents: ["ChatGLM-Spider"],
confidence: "reported",
verification: null,
source: "https://knownagents.com/agents/chatglm-spider"
},
{
agent: "TongyiBot",
vendor: "Alibaba",
category: "assistant-browse",
userAgents: ["TongyiBot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "YiyanBot",
vendor: "Baidu",
category: "assistant-browse",
userAgents: ["YiyanBot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "Manus-User",
vendor: "Butterfly Effect",
category: "assistant-browse",
userAgents: ["Manus-User"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "kagi-fetcher",
vendor: "Kagi",
category: "assistant-browse",
userAgents: ["kagi-fetcher"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "DeepSeekBot",
vendor: "DeepSeek",
category: "training-crawler",
userAgents: ["DeepSeekBot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "TikTokSpider",
vendor: "ByteDance",
category: "training-crawler",
userAgents: ["TikTokSpider"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "PanguBot",
vendor: "Huawei",
category: "training-crawler",
userAgents: ["PanguBot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "Cloudflare-AutoRAG",
vendor: "Cloudflare",
category: "search-index",
userAgents: ["Cloudflare-AutoRAG"],
confidence: "reported",
verification: null,
source: "https://developers.cloudflare.com/autorag/configuration/data-source/website/"
},
{
agent: "ExaSearchBot",
vendor: "Exa",
category: "search-index",
userAgents: ["ExaSearchBot"],
confidence: "verified",
verification: "https://crawler.exa.ai/.well-known/http-message-signatures-directory",
source: "https://crawler.exa.ai/"
},
{
agent: "ExaBot",
vendor: "Exa",
category: "search-index",
userAgents: ["ExaBot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "ShapBot",
vendor: "Parallel",
category: "search-index",
userAgents: ["ShapBot"],
confidence: "verified",
verification: "https://docs.parallel.ai/resources/shapbot.json",
source: "https://docs.parallel.ai/resources/crawler"
},
{
agent: "Shap-User",
vendor: "Parallel",
category: "assistant-browse",
userAgents: ["Shap-User"],
confidence: "verified",
verification: null,
source: "https://parallel.ai/parallel-web-systems-bots"
},
{
agent: "TavilyBot",
vendor: "Tavily",
category: "search-index",
userAgents: ["TavilyBot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "FirecrawlAgent",
vendor: "Firecrawl",
category: "search-index",
userAgents: ["FirecrawlAgent"],
confidence: "heuristic",
verification: null,
source: "https://docs.firecrawl.dev/advanced-scraping-guide"
},
{
agent: "GrokBot",
vendor: "xAI",
category: "search-index",
userAgents: ["GrokBot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "Codex CLI",
vendor: "OpenAI",
category: "assistant-browse",
userAgents: ["codex_cli_rs/", "codex-cli"],
confidence: "reported",
verification: null,
source: "https://github.com/openai/codex"
},
{
agent: "Google-NotebookLM",
vendor: "Google",
category: "assistant-browse",
userAgents: ["Google-NotebookLM"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "Grok-DeepSearch",
vendor: "xAI",
category: "assistant-browse",
userAgents: ["Grok-DeepSearch"],
confidence: "reported",
verification: null,
source: "https://www.mintlify.com/docs/analytics/traffic-classification"
},
{
agent: "Qwen-User",
vendor: "Alibaba",
category: "assistant-browse",
userAgents: ["Qwen-User"],
confidence: "reported",
verification: null,
source: "https://www.mintlify.com/docs/analytics/traffic-classification"
},
{
agent: "WarpBot",
vendor: "Warp",
category: "assistant-browse",
userAgents: ["WarpBot"],
confidence: "reported",
verification: null,
source: "https://www.mintlify.com/docs/analytics/traffic-classification"
},
{
agent: "Amazon-Bedrock-AgentCore-Browser",
vendor: "Amazon",
category: "assistant-browse",
userAgents: ["Amazon-Bedrock-AgentCore-Browser"],
confidence: "reported",
verification: null,
source: "https://knownagents.com/agents/amazon-bedrock-agentcore-browser"
},
{
agent: "MistralAI-Index",
vendor: "Mistral",
category: "search-index",
userAgents: ["MistralAI-Index"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "ref-tools-crawler",
vendor: "Ref",
category: "search-index",
userAgents: ["ref-tools-crawler"],
confidence: "reported",
verification: null,
source: "https://www.mintlify.com/docs/analytics/traffic-classification"
},
{
agent: "ERNIEBot",
vendor: "Baidu",
category: "training-crawler",
userAgents: ["ERNIEBot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "QwenBot",
vendor: "Alibaba",
category: "training-crawler",
userAgents: ["QwenBot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "Doubaobot",
vendor: "ByteDance",
category: "training-crawler",
userAgents: ["Doubaobot"],
confidence: "heuristic",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "ClueWeb-Crawler",
vendor: "Carnegie Mellon University",
category: "training-crawler",
userAgents: ["ClueWeb-Crawler"],
confidence: "reported",
verification: null,
source: "https://knownagents.com/agents/clueweb-crawler"
},
{
agent: "Cotoyogi",
vendor: "ROIS",
category: "training-crawler",
userAgents: ["Cotoyogi"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "ICC-Crawler",
vendor: "NICT",
category: "training-crawler",
userAgents: ["ICC-Crawler"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "img2dataset",
vendor: "img2dataset",
category: "training-crawler",
userAgents: ["img2dataset"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "Kangaroo Bot",
vendor: "Unknown",
category: "training-crawler",
userAgents: ["Kangaroo Bot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "VelenPublicWebCrawler",
vendor: "Velen",
category: "training-crawler",
userAgents: ["VelenPublicWebCrawler"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "ImagesiftBot",
vendor: "ImageSift",
category: "training-crawler",
userAgents: ["ImagesiftBot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "aiHitBot",
vendor: "aiHit",
category: "training-crawler",
userAgents: ["aiHitBot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
},
{
agent: "Factset_spyderbot",
vendor: "FactSet",
category: "training-crawler",
userAgents: ["Factset_spyderbot"],
confidence: "reported",
verification: null,
source: "https://raw.githubusercontent.com/ai-robots-txt/ai.robots.txt/main/robots.json"
}
];
// src/classify.ts
var NORMALIZED_AGENT_SIGNATURES = AI_AGENT_SIGNATURES.map((signature) => ({
signature,
userAgents: signature.userAgents.map((token) => token.toLowerCase())
}));
function classifyUserAgent(userAgent) {
const haystack = userAgent.toLowerCase();
if (!haystack) {
return null;
}
const exact = haystack.trim();
for (const { signature, userAgents } of NORMALIZED_AGENT_SIGNATURES) {
for (const needle of userAgents) {
const matched = signature.match === "exact" ? exact === needle : haystack.includes(needle);
if (matched) {
return {
agent: signature.agent,
vendor: signature.vendor,
category: signature.category,
confidence: signature.confidence
};
}
}
}
return null;
}
function classifyRequest(headers, _ip) {
return classifyUserAgent(headers.get("user-agent") ?? "");
}
// src/constants.ts
var DEFAULT_ENDPOINT = "https://ingest.usenotra.com";
var INGEST_PATH = "/api/geo/ingest";
var PREFETCH_PURPOSE_HEADERS = ["sec-purpose", "purpose", "x-moz"];
var INGEST_TIMEOUT_MS = 2e3;
var DEFAULT_EXCLUDE = ["/api"];
var JOURNEY_ID_PARAM = "ntr";
var JOURNEY_ID_PATTERN = /^[A-Za-z0-9_-]{8,32}$/;
var JOURNEY_ID_BYTES = 12;
var TAG_LOOP_GUARD_HEADER = "x-notra-geo-tag";
var TAG_LOOP_GUARD_VALUE = "1";
var DEFAULT_TAG_PATHS = [
/\.md$/i,
/(^|\/)llms\.txt$/i,
/(^|\/)llms-full\.txt$/i
];
var TAGGABLE_CONTENT_TYPES = ["text/markdown", "text/plain"];
var TAGGABLE_HTML_CONTENT_TYPES = ["text/html"];
var TAG_STRIPPED_RESPONSE_HEADERS = [
"content-encoding",
"content-length",
"transfer-encoding"
];
var TAG_STRIPPED_RESPONSE_HEADER_PREFIXES = ["x-middleware-"];
var ASSET_PATH_PREFIXES = [
"/_next/",
"/_nuxt/",
"/_vercel/",
"/_astro/",
"/_app/immutable/",
"/__nextjs",
"/static/"
];
var LLMS_TXT_FILE = /^llms(-full)?\.txt$/i;
var ASSET_EXTENSIONS = [
".avif",
".css",
".eot",
".gif",
".ico",
".jpeg",
".jpg",
".js",
".json",
".map",
".mjs",
".mp3",
".mp4",
".otf",
".pdf",
".png",
".svg",
".ttf",
".txt",
".wasm",
".webm",
".webmanifest",
".webp",
".woff",
".woff2",
".xml",
".zip"
];
// src/exclude.ts
function matchesPath(pathname, prefix) {
if (prefix === "/") {
return true;
}
const normalized = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
return pathname === normalized || pathname.startsWith(`${normalized}/`);
}
function isAssetPath(pathname) {
for (const prefix of ASSET_PATH_PREFIXES) {
if (pathname.startsWith(prefix)) {
return true;
}
}
const lastSegment = pathname.slice(pathname.lastIndexOf("/") + 1);
if (LLMS_TXT_FILE.test(lastSegment)) {
return false;
}
const dot = lastSegment.lastIndexOf(".");
if (dot <= 0) {
return false;
}
return ASSET_EXTENSIONS.includes(lastSegment.slice(dot).toLowerCase());
}
function matchesRule(request, url, rule) {
if (typeof rule === "string") {
return matchesPath(url.pathname, rule);
}
if (rule instanceof RegExp) {
return rule.test(url.pathname);
}
return rule(request, url);
}
function matchesAnyRule(request, url, rules) {
for (const rule of rules) {
if (matchesRule(request, url, rule)) {
return true;
}
}
return false;
}
function isExcluded(request, url, rules) {
return matchesAnyRule(request, url, rules);
}
function shouldTrackRequest(request, url, exclude) {
if (request.method.toUpperCase() !== "GET") {
return false;
}
if (isAssetPath(url.pathname)) {
return false;
}
return !isExcluded(request, url, exclude ?? DEFAULT_EXCLUDE);
}
// src/link-target.ts
var HTTP_PROTOCOL = /^https?:\/\//i;
var EXISTING_JOURNEY_PARAM = new RegExp(`[?&](?:amp;)?${JOURNEY_ID_PARAM}=`);
var RESOLVE_BASE = "https://journey.invalid";
function isSameHost(target, host) {
if (!host) {
return false;
}
try {
const parsed = new URL(target, RESOLVE_BASE);
return parsed.hostname.toLowerCase() === host.trim().toLowerCase();
} catch {
return false;
}
}
function isTaggableTarget(target, host) {
const value = target.trim();
if (value.length === 0 || value.startsWith("#") || value.startsWith("<")) {
return false;
}
if (EXISTING_JOURNEY_PARAM.test(value)) {
return false;
}
if (value.startsWith("//")) {
return isSameHost(value, host);
}
if (value.startsWith("/")) {
return true;
}
if (HTTP_PROTOCOL.test(value)) {
return isSameHost(value, host);
}
return false;
}
function appendJourneyParam(target, journeyId, ampersand = "&") {
const hashIndex = target.indexOf("#");
const base = hashIndex === -1 ? target : target.slice(0, hashIndex);
const fragment = hashIndex === -1 ? "" : target.slice(hashIndex);
let separator = "?";
if (base.endsWith("?")) {
separator = "";
} else if (base.includes("?")) {
separator = ampersand;
}
return `${base}${separator}${JOURNEY_ID_PARAM}=${journeyId}${fragment}`;
}
// src/html.ts
var ANCHOR_TAG = /<a\b[^>]*>/gi;
var HREF_ATTRIBUTE = /(\shref\s*=\s*)(?:"([^"]*)"|'([^']*)')/i;
var ENCODED_AMPERSAND = "&";
function tagHtmlLinks(html, journeyId, options = {}) {
if (!JOURNEY_ID_PATTERN.test(journeyId)) {
return html;
}
return html.replace(
ANCHOR_TAG,
(tag) => tag.replace(
HREF_ATTRIBUTE,
(match, prefix, doubleQuoted, singleQuoted) => {
const target = doubleQuoted ?? singleQuoted;
if (target === void 0) {
return match;
}
if (!isTaggableTarget(target, options.host)) {
return match;
}
const quote = doubleQuoted === void 0 ? "'" : '"';
const ampersand = target.includes(ENCODED_AMPERSAND) ? ENCODED_AMPERSAND : "&";
return `${prefix}${quote}${appendJourneyParam(target, journeyId, ampersand)}${quote}`;
}
)
);
}
// src/markdown.ts
var FENCE_SPLIT = /(```[\s\S]*?```|~~~[\s\S]*?~~~)/;
var INLINE_CODE_SPLIT = /(`+[^`]*`+)/;
var REFERENCE_LINK = /^([ \t]{0,3}\[[^\]]+\]:[ \t]*)(\S+)/gm;
var BASE64_URL_UNSAFE = /[+/]/g;
var BASE64_PADDING = /=+$/;
var BASE64_URL_REPLACEMENTS = { "+": "-", "/": "_" };
function mintJourneyId() {
const bytes = new Uint8Array(JOURNEY_ID_BYTES);
globalThis.crypto.getRandomValues(bytes);
let binary = "";
for (const byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary).replace(BASE64_URL_UNSAFE, (char) => BASE64_URL_REPLACEMENTS[char] ?? char).replace(BASE64_PADDING, "");
}
function toUrl(input) {
if (typeof input === "string") {
try {
return new URL(input, RESOLVE_BASE);
} catch {
return null;
}
}
if (input instanceof URL) {
return input;
}
try {
return new URL(input.url);
} catch {
return null;
}
}
function getJourneyId(request) {
const url = toUrl(request);
const value = url?.searchParams.get(JOURNEY_ID_PARAM);
if (!value || !JOURNEY_ID_PATTERN.test(value)) {
return null;
}
return value;
}
function tagText(text, journeyId, host) {
const output = [];
let outputStart = 0;
let searchFrom = 0;
while (searchFrom < text.length) {
const labelStart = text.indexOf("[", searchFrom);
if (labelStart === -1) {
break;
}
const labelEnd = text.indexOf("]", labelStart + 1);
if (labelEnd === -1) {
break;
}
if (text[labelEnd + 1] !== "(") {
searchFrom = labelEnd + 1;
continue;
}
let cursor = labelEnd + 2;
while (text[cursor]?.trim() === "") {
cursor += 1;
}
const targetStart = cursor;
while (cursor < text.length && text[cursor]?.trim() !== "" && text[cursor] !== "(" && text[cursor] !== ")") {
cursor += 1;
}
if (cursor === targetStart) {
searchFrom = labelEnd + 1;
continue;
}
const targetEnd = cursor;
while (text[cursor]?.trim() === "") {
cursor += 1;
}
let titleEnd = targetEnd;
if (cursor > targetEnd && text[cursor] === '"') {
cursor += 1;
while (cursor < text.length && text[cursor] !== '"') {
cursor += 1;
}
if (cursor === text.length) {
searchFrom = labelEnd + 1;
continue;
}
cursor += 1;
titleEnd = cursor;
while (text[cursor]?.trim() === "") {
cursor += 1;
}
}
if (text[cursor] !== ")") {
searchFrom = labelEnd + 1;
continue;
}
const matchEnd = cursor + 1;
const target = text.slice(targetStart, targetEnd);
const isImage = labelStart > 0 && text[labelStart - 1] === "!";
if (isImage || !isTaggableTarget(target, host)) {
searchFrom = matchEnd;
continue;
}
const label = text.slice(labelStart + 1, labelEnd);
const title = text.slice(targetEnd, titleEnd);
output.push(
text.slice(outputStart, labelStart),
`[${label}](${appendJourneyParam(target, journeyId)}${title})`
);
outputStart = matchEnd;
searchFrom = matchEnd;
}
output.push(text.slice(outputStart));
const withInlineLinks = output.join("");
return withInlineLinks.replace(
REFERENCE_LINK,
(match, prefix, target) => {
if (!isTaggableTarget(target, host)) {
return match;
}
return `${prefix}${appendJourneyParam(target, journeyId)}`;
}
);
}
function tagSegment(segment, journeyId, host) {
return segment.split(INLINE_CODE_SPLIT).map(
(part) => part.startsWith("`") ? part : tagText(part, journeyId, host)
).join("");
}
function tagMarkdownLinks(markdown, journeyId, options = {}) {
if (!JOURNEY_ID_PATTERN.test(journeyId)) {
return markdown;
}
return markdown.split(FENCE_SPLIT).map((segment) => {
const isFence = segment.startsWith("```") || segment.startsWith("~~~");
return isFence ? segment : tagSegment(segment, journeyId, options.host);
}).join("");
}
// src/send.ts
function ingestUrl(endpoint) {
const value = endpoint ?? DEFAULT_ENDPOINT;
let end = value.length;
while (end > 0 && value[end - 1] === "/") {
end -= 1;
}
const base = value.slice(0, end);
return `${base}${INGEST_PATH}`;
}
async function sendRequestLog(payload, options) {
const send = options.fetch ?? globalThis.fetch;
try {
const response = await send(ingestUrl(options.endpoint), {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${options.token}`
},
body: JSON.stringify(payload),
keepalive: true,
signal: AbortSignal.timeout(INGEST_TIMEOUT_MS)
});
if (!response.ok) {
void response.body?.cancel().catch(() => void 0);
throw new Error(`GEO ingest request failed (HTTP ${response.status})`);
}
} catch (error) {
reportGeoError(options.onError, error);
}
}
function reportGeoError(onError, error) {
try {
onError?.(error);
} catch {
}
}
// src/tag-response.ts
function resolveTagLinksConfig(option) {
if (!option) {
return null;
}
if (option === true) {
return {};
}
return option;
}
function passesSharedGates(request) {
if (request.headers.has(TAG_LOOP_GUARD_HEADER)) {
return false;
}
if (request.method.toUpperCase() !== "GET") {
return false;
}
return classifyRequest(request.headers) !== null;
}
function resolveTagMode(request, url, config, exclude) {
if (!passesSharedGates(request)) {
return null;
}
if (matchesAnyRule(request, url, config.paths ?? DEFAULT_TAG_PATHS)) {
return "markdown";
}
if (!config.html) {
return null;
}
if (!shouldTrackRequest(request, url, exclude)) {
return null;
}
return "html";
}
function isTaggableContentType(value, allowed) {
if (!value) {
return false;
}
const normalized = value.toLowerCase();
return allowed.some((type) => normalized.includes(type));
}
function taggedHeaders(source) {
const headers = new Headers(source);
for (const name of TAG_STRIPPED_RESPONSE_HEADERS) {
headers.delete(name);
}
for (const name of Array.from(headers.keys())) {
const isControlHeader = TAG_STRIPPED_RESPONSE_HEADER_PREFIXES.some(
(prefix) => name.startsWith(prefix)
);
if (isControlHeader) {
headers.delete(name);
}
}
return headers;
}
async function tagMarkdownResponse(request, config, options = {}) {
try {
const url = new URL(request.url);
const mode = resolveTagMode(request, url, config, options.exclude);
if (!mode) {
return;
}
const journeyId = getJourneyId(url) ?? mintJourneyId();
const headers = new Headers(request.headers);
headers.set(TAG_LOOP_GUARD_HEADER, TAG_LOOP_GUARD_VALUE);
const send = options.fetch ?? globalThis.fetch;
const origin = await send(request.url, { method: "GET", headers });
if (!origin.ok) {
return;
}
const contentType = origin.headers.get("content-type");
const isMarkdownBody = isTaggableContentType(
contentType,
TAGGABLE_CONTENT_TYPES
);
const isHtmlBody = mode === "html" && isTaggableContentType(contentType, TAGGABLE_HTML_CONTENT_TYPES);
if (!(isMarkdownBody || isHtmlBody)) {
return;
}
const body = await origin.text();
const host = config.host ?? url.hostname;
const tagged = isMarkdownBody ? tagMarkdownLinks(body, journeyId, { host }) : tagHtmlLinks(body, journeyId, { host });
return new Response(tagged, {
status: origin.status,
statusText: origin.statusText,
headers: taggedHeaders(origin.headers)
});
} catch (error) {
reportGeoError(options.onError, error);
return;
}
}
// src/serialize.ts
function header(headers, name) {
return headers.get(name) ?? void 0;
}
function decode(value) {
if (!value) {
return;
}
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function readIp(headers) {
const forwardedFor = headers.get("x-forwarded-for");
const first = forwardedFor?.split(",")[0]?.trim();
if (first) {
return first;
}
return header(headers, "x-real-ip") ?? header(headers, "x-vercel-forwarded-for");
}
function readGeo(headers) {
const location = {
country: header(headers, "x-vercel-ip-country") ?? header(headers, "cf-ipcountry"),
region: header(headers, "x-vercel-ip-country-region"),
city: decode(header(headers, "x-vercel-ip-city")),
timezone: header(headers, "x-vercel-ip-timezone"),
latitude: header(headers, "x-vercel-ip-latitude"),
longitude: header(headers, "x-vercel-ip-longitude")
};
const hasValue = Object.values(location).some((value) => value !== void 0);
return hasValue ? location : void 0;
}
var TRACING_HEADERS = ["traceparent", "b3", "x-b3-traceid"];
function isPrefetch(headers) {
return headers.has("next-router-prefetch") || PREFETCH_PURPOSE_HEADERS.some(
(name) => headers.get(name)?.toLowerCase().includes("prefetch")
);
}
function readSignals(headers) {
return {
clientHints: headers.has("sec-ch-ua"),
fetchMode: header(headers, "sec-fetch-mode") ?? null,
tracing: TRACING_HEADERS.some((name) => headers.has(name)),
prefetch: isPrefetch(headers)
};
}
function serializeRequest(request) {
const { headers } = request;
return {
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
method: request.method,
url: request.url,
ip: readIp(headers),
geo: readGeo(headers),
referer: header(headers, "referer"),
userAgent: header(headers, "user-agent"),
accept: header(headers, "accept"),
acceptLanguage: header(headers, "accept-language"),
requestId: header(headers, "x-request-id") ?? header(headers, "x-vercel-id"),
signals: readSignals(headers)
};
}
// src/tracker.ts
function isSampled(sample) {
if (sample === void 0 || sample >= 1) {
return true;
}
if (sample <= 0) {
return false;
}
return Math.random() < sample;
}
var Tracker = class {
options;
constructor(options) {
this.options = options;
}
buildPayload(request) {
let url;
try {
url = new URL(request.url);
} catch (error) {
reportGeoError(this.options.onError, error);
return null;
}
if (!shouldTrackRequest(request, url, this.options.exclude)) {
return null;
}
if (!isSampled(this.options.sample)) {
return null;
}
return serializeRequest(request);
}
async track(request) {
if (!this.options.token) {
return;
}
try {
const payload = this.buildPayload(request);
if (!payload) {
return;
}
await sendRequestLog(payload, this.options);
} catch (error) {
reportGeoError(this.options.onError, error);
}
}
};
// src/next.ts
var Tracker2 = class {
options;
tracker;
tagLinks;
constructor(options) {
this.options = options;
this.tracker = new Tracker(options);
this.tagLinks = resolveTagLinksConfig(options.tagLinks);
}
track(request, event) {
const pending = this.tracker.track(request);
if (typeof event?.waitUntil === "function") {
event.waitUntil(pending);
}
}
async handle(request, event) {
if (this.tagLinks) {
const tagged = await tagMarkdownResponse(request, this.tagLinks, {
fetch: this.options.fetch,
onError: this.options.onError,
exclude: this.options.exclude
});
if (tagged) {
this.track(request, event);
return tagged;
}
}
this.track(request, event);
return;
}
};
function createGeoProxy(options) {
const tracker = new Tracker2(options);
return (request, event) => tracker.handle(request, event);
}
export { Tracker2 as Tracker, createGeoProxy };