@aman-sagar06077/zappa-analytics 0.1.4 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/crawler.d.ts +1 -1
- package/crawler.js +4 -0
- package/next-crawler.d.ts +22 -22
- package/next-crawler.js +82 -82
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -50,7 +50,7 @@ const collectZappaCrawlerRequest = createNextCrawlerProxy({
|
|
|
50
50
|
collectZappaCrawlerRequest(request, event);
|
|
51
51
|
```
|
|
52
52
|
|
|
53
|
-
The Next.js `event` argument keeps the small telemetry request alive after the site response is returned. The collector only reports recognized crawler-like GET/HEAD page requests, removes query strings, sends no IP address, and records status as `0` (unknown) because Proxy runs before the route. It recognizes search crawlers and user-triggered fetchers, including Perplexity-User and Claude-Agent. Extend your existing matcher to include public page routes while excluding static assets and API routes. In the Vercel project, set `ZAPPA_PROJECT_ID` and `ZAPPA_CRAWLER_KEY` as server-only environment variables, then redeploy. The key is private: never add a `NEXT_PUBLIC_` prefix or commit it.
|
|
53
|
+
The Next.js `event` argument keeps the small telemetry request alive after the site response is returned. The collector only reports recognized crawler-like GET/HEAD page requests, removes query strings, sends no IP address, and records status as `0` (unknown) because Proxy runs before the route. It recognizes known search crawlers and user-triggered fetchers, including Perplexity-User and Claude-Agent. Unknown user agents that identify themselves with bot, crawler, spider, agent, assistant, or fetcher terms are also reported under generic unverified labels, so new providers do not require a package release just to appear. Extend your existing matcher to include public page routes while excluding static assets and API routes. In the Vercel project, set `ZAPPA_PROJECT_ID` and `ZAPPA_CRAWLER_KEY` as server-only environment variables, then redeploy. The key is private: never add a `NEXT_PUBLIC_` prefix or commit it.
|
|
54
54
|
|
|
55
55
|
## AI crawler observations on Node/Express
|
|
56
56
|
|
package/crawler.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ export type CrawlerMatch = {
|
|
|
9
9
|
crawler: string;
|
|
10
10
|
organization: string;
|
|
11
11
|
category: CrawlerCategory;
|
|
12
|
-
detectionMethod: 'known_user_agent_match' | 'generic_user_agent_match';
|
|
12
|
+
detectionMethod: 'known_user_agent_match' | 'generic_user_agent_match' | 'generic_ai_agent_match';
|
|
13
13
|
verificationStatus: 'unverified';
|
|
14
14
|
};
|
|
15
15
|
|
package/crawler.js
CHANGED
|
@@ -21,6 +21,7 @@ const REGISTRY = [
|
|
|
21
21
|
[/\bCCBot\b/i, 'CCBot', 'Common Crawl', 'unknown_bot'],
|
|
22
22
|
];
|
|
23
23
|
const GENERIC_BOT = /(?:\bbot\b|crawler|spider|crawl|slurp|scrapy|archiver|headlesschrome|phantomjs|puppeteer|playwright|selenium|lighthouse|pagespeed|pingdom|uptime|statuscake|gtmetrix|facebookexternalhit|slackbot|discordbot)/i;
|
|
24
|
+
const GENERIC_AI_AGENT = /\b(?!user-agent\b)[a-z][a-z0-9._-]*(?:agent|assistant|fetcher)\b/i;
|
|
24
25
|
const HOST_LABELS = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
|
|
25
26
|
|
|
26
27
|
/** Return a known UA match, explicitly unverified, or null for an ordinary UA. */
|
|
@@ -32,6 +33,9 @@ export function classifyCrawler(userAgent) {
|
|
|
32
33
|
return { crawler, organization, category, detectionMethod: 'known_user_agent_match', verificationStatus: 'unverified' };
|
|
33
34
|
}
|
|
34
35
|
}
|
|
36
|
+
if (GENERIC_AI_AGENT.test(value)) {
|
|
37
|
+
return { crawler: 'Unknown AI agent', organization: 'Unknown', category: 'ai_assistant_fetcher', detectionMethod: 'generic_ai_agent_match', verificationStatus: 'unverified' };
|
|
38
|
+
}
|
|
35
39
|
if (GENERIC_BOT.test(value)) {
|
|
36
40
|
return { crawler: 'Unknown bot', organization: 'Unknown', category: 'unknown_bot', detectionMethod: 'generic_user_agent_match', verificationStatus: 'unverified' };
|
|
37
41
|
}
|
package/next-crawler.d.ts
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
export type NextCrawlerRequest = {
|
|
2
|
-
url: string;
|
|
3
|
-
method?: string;
|
|
4
|
-
headers: { get(name: string): string | null };
|
|
5
|
-
};
|
|
6
|
-
|
|
7
|
-
export type NextCrawlerEvent = {
|
|
8
|
-
waitUntil(promise: Promise<unknown>): void;
|
|
9
|
-
};
|
|
10
|
-
|
|
11
|
-
export type NextCrawlerOptions = {
|
|
12
|
-
projectId: string;
|
|
13
|
-
crawlerKey: string;
|
|
14
|
-
endpoint?: string;
|
|
15
|
-
fetchImpl?: (input: URL, init: Record<string, unknown>) => Promise<unknown>;
|
|
16
|
-
timeoutMs?: number;
|
|
17
|
-
};
|
|
18
|
-
|
|
19
|
-
/** Create an Edge-safe collector for Next.js Proxy or Middleware request events. */
|
|
20
|
-
export function createNextCrawlerProxy(
|
|
21
|
-
options: NextCrawlerOptions,
|
|
22
|
-
): (request: NextCrawlerRequest, event: NextCrawlerEvent) => boolean;
|
|
1
|
+
export type NextCrawlerRequest = {
|
|
2
|
+
url: string;
|
|
3
|
+
method?: string;
|
|
4
|
+
headers: { get(name: string): string | null };
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
export type NextCrawlerEvent = {
|
|
8
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export type NextCrawlerOptions = {
|
|
12
|
+
projectId: string;
|
|
13
|
+
crawlerKey: string;
|
|
14
|
+
endpoint?: string;
|
|
15
|
+
fetchImpl?: (input: URL, init: Record<string, unknown>) => Promise<unknown>;
|
|
16
|
+
timeoutMs?: number;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** Create an Edge-safe collector for Next.js Proxy or Middleware request events. */
|
|
20
|
+
export function createNextCrawlerProxy(
|
|
21
|
+
options: NextCrawlerOptions,
|
|
22
|
+
): (request: NextCrawlerRequest, event: NextCrawlerEvent) => boolean;
|
package/next-crawler.js
CHANGED
|
@@ -1,82 +1,82 @@
|
|
|
1
|
-
import { classifyCrawler } from './crawler.js';
|
|
2
|
-
|
|
3
|
-
const DEFAULT_ENDPOINT = 'https://www.zappa.in/api/ai-crawlers';
|
|
4
|
-
const PRIVATE_KEY = /^ZappaCrawler_[A-Za-z0-9_-]{32,}$/;
|
|
5
|
-
const HOST_LABELS = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
|
|
6
|
-
const NON_PAGE_PATH = /(?:^\/_next\/|^\/api\/|\.(?:avif|bmp|css|gif|ico|jpe?g|js|map|mjs|png|svg|webp|woff2?|ttf|eot|pdf|zip|xml)$)/i;
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Create an Edge-safe collector for Next.js Proxy (or Middleware on older Next.js).
|
|
10
|
-
* Call it with the incoming Request and NextFetchEvent; it only schedules work for
|
|
11
|
-
* recognized crawler-like GET/HEAD requests and never changes the page response.
|
|
12
|
-
*/
|
|
13
|
-
export function createNextCrawlerProxy({
|
|
14
|
-
projectId,
|
|
15
|
-
crawlerKey,
|
|
16
|
-
endpoint = DEFAULT_ENDPOINT,
|
|
17
|
-
fetchImpl = globalThis.fetch,
|
|
18
|
-
timeoutMs = 800,
|
|
19
|
-
} = {}) {
|
|
20
|
-
// Keep collection optional in local/preview environments where secrets are absent.
|
|
21
|
-
if (!projectId || !crawlerKey) return () => false;
|
|
22
|
-
if (typeof projectId !== 'string' || !projectId.trim()) throw new TypeError('projectId is required');
|
|
23
|
-
if (typeof crawlerKey !== 'string' || !PRIVATE_KEY.test(crawlerKey)) throw new TypeError('A private Zappa crawler key is required');
|
|
24
|
-
if (typeof fetchImpl !== 'function') throw new TypeError('Fetch is required');
|
|
25
|
-
|
|
26
|
-
const target = new URL(endpoint);
|
|
27
|
-
if (target.protocol !== 'https:' && target.hostname !== 'localhost') throw new TypeError('The crawler endpoint must use HTTPS');
|
|
28
|
-
const safeTimeout = Math.max(100, Math.min(Number(timeoutMs) || 800, 3000));
|
|
29
|
-
|
|
30
|
-
return function collectNextCrawlerRequest(request, event) {
|
|
31
|
-
const userAgent = request?.headers?.get?.('user-agent')?.slice(0, 1024) ?? '';
|
|
32
|
-
if (!classifyCrawler(userAgent)) return false;
|
|
33
|
-
|
|
34
|
-
const method = String(request.method || 'GET').toUpperCase();
|
|
35
|
-
if (method !== 'GET' && method !== 'HEAD') return false;
|
|
36
|
-
|
|
37
|
-
let url;
|
|
38
|
-
try {
|
|
39
|
-
url = new URL(request.url);
|
|
40
|
-
} catch {
|
|
41
|
-
return false;
|
|
42
|
-
}
|
|
43
|
-
const path = url.pathname;
|
|
44
|
-
if (!HOST_LABELS.test(url.hostname) || !path.startsWith('/') || path.length > 512 || NON_PAGE_PATH.test(path)) return false;
|
|
45
|
-
if (!event || typeof event.waitUntil !== 'function' || typeof globalThis.crypto?.randomUUID !== 'function') return false;
|
|
46
|
-
|
|
47
|
-
const controller = new AbortController();
|
|
48
|
-
const timeout = setTimeout(() => controller.abort(), safeTimeout);
|
|
49
|
-
const payload = {
|
|
50
|
-
projectId,
|
|
51
|
-
requests: [{
|
|
52
|
-
requestId: globalThis.crypto.randomUUID(),
|
|
53
|
-
timestamp: new Date().toISOString(),
|
|
54
|
-
hostname: url.hostname.toLowerCase().replace(/\.$/, ''),
|
|
55
|
-
path,
|
|
56
|
-
method,
|
|
57
|
-
// Proxy runs before the route, so the final HTTP status is not observable here.
|
|
58
|
-
// 0 is the API's documented sentinel for a status unavailable in Proxy.
|
|
59
|
-
statusCode: 0,
|
|
60
|
-
userAgent,
|
|
61
|
-
}],
|
|
62
|
-
};
|
|
63
|
-
|
|
64
|
-
const task = Promise.resolve()
|
|
65
|
-
.then(() => fetchImpl(target, {
|
|
66
|
-
method: 'POST',
|
|
67
|
-
headers: { 'Content-Type': 'application/json', 'X-Zappa-Crawler-Key': crawlerKey },
|
|
68
|
-
body: JSON.stringify(payload),
|
|
69
|
-
signal: controller.signal,
|
|
70
|
-
}))
|
|
71
|
-
.catch(() => {})
|
|
72
|
-
.finally(() => clearTimeout(timeout));
|
|
73
|
-
|
|
74
|
-
try {
|
|
75
|
-
event.waitUntil(task);
|
|
76
|
-
return true;
|
|
77
|
-
} catch {
|
|
78
|
-
// Telemetry must never break or delay the site's page response.
|
|
79
|
-
return false;
|
|
80
|
-
}
|
|
81
|
-
};
|
|
82
|
-
}
|
|
1
|
+
import { classifyCrawler } from './crawler.js';
|
|
2
|
+
|
|
3
|
+
const DEFAULT_ENDPOINT = 'https://www.zappa.in/api/ai-crawlers';
|
|
4
|
+
const PRIVATE_KEY = /^ZappaCrawler_[A-Za-z0-9_-]{32,}$/;
|
|
5
|
+
const HOST_LABELS = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
|
|
6
|
+
const NON_PAGE_PATH = /(?:^\/_next\/|^\/api\/|\.(?:avif|bmp|css|gif|ico|jpe?g|js|map|mjs|png|svg|webp|woff2?|ttf|eot|pdf|zip|xml)$)/i;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Create an Edge-safe collector for Next.js Proxy (or Middleware on older Next.js).
|
|
10
|
+
* Call it with the incoming Request and NextFetchEvent; it only schedules work for
|
|
11
|
+
* recognized crawler-like GET/HEAD requests and never changes the page response.
|
|
12
|
+
*/
|
|
13
|
+
export function createNextCrawlerProxy({
|
|
14
|
+
projectId,
|
|
15
|
+
crawlerKey,
|
|
16
|
+
endpoint = DEFAULT_ENDPOINT,
|
|
17
|
+
fetchImpl = globalThis.fetch,
|
|
18
|
+
timeoutMs = 800,
|
|
19
|
+
} = {}) {
|
|
20
|
+
// Keep collection optional in local/preview environments where secrets are absent.
|
|
21
|
+
if (!projectId || !crawlerKey) return () => false;
|
|
22
|
+
if (typeof projectId !== 'string' || !projectId.trim()) throw new TypeError('projectId is required');
|
|
23
|
+
if (typeof crawlerKey !== 'string' || !PRIVATE_KEY.test(crawlerKey)) throw new TypeError('A private Zappa crawler key is required');
|
|
24
|
+
if (typeof fetchImpl !== 'function') throw new TypeError('Fetch is required');
|
|
25
|
+
|
|
26
|
+
const target = new URL(endpoint);
|
|
27
|
+
if (target.protocol !== 'https:' && target.hostname !== 'localhost') throw new TypeError('The crawler endpoint must use HTTPS');
|
|
28
|
+
const safeTimeout = Math.max(100, Math.min(Number(timeoutMs) || 800, 3000));
|
|
29
|
+
|
|
30
|
+
return function collectNextCrawlerRequest(request, event) {
|
|
31
|
+
const userAgent = request?.headers?.get?.('user-agent')?.slice(0, 1024) ?? '';
|
|
32
|
+
if (!classifyCrawler(userAgent)) return false;
|
|
33
|
+
|
|
34
|
+
const method = String(request.method || 'GET').toUpperCase();
|
|
35
|
+
if (method !== 'GET' && method !== 'HEAD') return false;
|
|
36
|
+
|
|
37
|
+
let url;
|
|
38
|
+
try {
|
|
39
|
+
url = new URL(request.url);
|
|
40
|
+
} catch {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
const path = url.pathname;
|
|
44
|
+
if (!HOST_LABELS.test(url.hostname) || !path.startsWith('/') || path.length > 512 || NON_PAGE_PATH.test(path)) return false;
|
|
45
|
+
if (!event || typeof event.waitUntil !== 'function' || typeof globalThis.crypto?.randomUUID !== 'function') return false;
|
|
46
|
+
|
|
47
|
+
const controller = new AbortController();
|
|
48
|
+
const timeout = setTimeout(() => controller.abort(), safeTimeout);
|
|
49
|
+
const payload = {
|
|
50
|
+
projectId,
|
|
51
|
+
requests: [{
|
|
52
|
+
requestId: globalThis.crypto.randomUUID(),
|
|
53
|
+
timestamp: new Date().toISOString(),
|
|
54
|
+
hostname: url.hostname.toLowerCase().replace(/\.$/, ''),
|
|
55
|
+
path,
|
|
56
|
+
method,
|
|
57
|
+
// Proxy runs before the route, so the final HTTP status is not observable here.
|
|
58
|
+
// 0 is the API's documented sentinel for a status unavailable in Proxy.
|
|
59
|
+
statusCode: 0,
|
|
60
|
+
userAgent,
|
|
61
|
+
}],
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const task = Promise.resolve()
|
|
65
|
+
.then(() => fetchImpl(target, {
|
|
66
|
+
method: 'POST',
|
|
67
|
+
headers: { 'Content-Type': 'application/json', 'X-Zappa-Crawler-Key': crawlerKey },
|
|
68
|
+
body: JSON.stringify(payload),
|
|
69
|
+
signal: controller.signal,
|
|
70
|
+
}))
|
|
71
|
+
.catch(() => {})
|
|
72
|
+
.finally(() => clearTimeout(timeout));
|
|
73
|
+
|
|
74
|
+
try {
|
|
75
|
+
event.waitUntil(task);
|
|
76
|
+
return true;
|
|
77
|
+
} catch {
|
|
78
|
+
// Telemetry must never break or delay the site's page response.
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
}
|