@aman-sagar06077/zappa-analytics 0.0.0-stage → 0.1.1
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 +29 -3
- package/index.d.ts +3 -0
- package/index.js +122 -0
- package/next.d.ts +2 -0
- package/next.js +12 -0
- package/package.json +31 -6
package/README.md
CHANGED
|
@@ -1,3 +1,29 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @aman-sagar06077/zappa-analytics
|
|
2
|
+
|
|
3
|
+
Add Zappa page views and custom events to a site.
|
|
4
|
+
|
|
5
|
+
## Next.js
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm i @aman-sagar06077/zappa-analytics
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```tsx
|
|
12
|
+
import { Analytics } from '@aman-sagar06077/zappa-analytics/next';
|
|
13
|
+
|
|
14
|
+
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
15
|
+
return <html><body>{children}<Analytics projectId="YOUR_PROJECT_ID" writeKey="Zappa_YOUR_PROJECT_WRITE_KEY" /></body></html>;
|
|
16
|
+
}
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Any JavaScript site
|
|
20
|
+
|
|
21
|
+
```js
|
|
22
|
+
import { init } from '@aman-sagar06077/zappa-analytics';
|
|
23
|
+
const analytics = init({ projectId: 'YOUR_PROJECT_ID', writeKey: 'Zappa_YOUR_PROJECT_WRITE_KEY' });
|
|
24
|
+
analytics.track('signup_completed', { plan: 1 });
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The SDK defaults to Zappa's hosted collector at `https://www.zappa.in/api/events`. Override `endpoint` only when using a different collector.
|
|
28
|
+
|
|
29
|
+
Only initialize analytics when your consent policy permits it. Pass `enabled={false}` to the Next.js component until consent is granted, then render it with `enabled` set to `true`. `init` fails closed without a valid write key. The package tracks initial navigation, History API push/replace, query-only changes and browser back/forward, suppressing duplicate pageviews. It shares a persistent first-party visitor and session hint across tabs; the collector assigns the authoritative session after 30 minutes of inactivity or at a UTC day boundary. Use `analytics.reset()` to start a fresh anonymous identity and `analytics.optOut()` to stop collection and clear identifiers. Events are sent in batches of up to 20 and retried on transient network failures.
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export type AnalyticsOptions = { projectId: string; writeKey: string; endpoint?: string; enabled?: boolean };
|
|
2
|
+
export type AnalyticsClient = { track(name: string, properties?: Record<string, string | number | boolean>): void; page(): void; flush(): void; identify(): string | undefined; reset(): void; optOut(): void; destroy(): void };
|
|
3
|
+
export function init(options: AnalyticsOptions): AnalyticsClient;
|
package/index.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
const DEFAULT_ENDPOINT = 'https://www.zappa.in/api/events';
|
|
2
|
+
const VISITOR_KEY = 'Zappa_visitor';
|
|
3
|
+
const SESSION_KEY = 'Zappa_session';
|
|
4
|
+
const IDLE_MS = 30 * 60 * 1000;
|
|
5
|
+
const MAX_SESSION_MS = 24 * 60 * 60 * 1000;
|
|
6
|
+
|
|
7
|
+
function makeId() {
|
|
8
|
+
try { return crypto.randomUUID(); } catch { return undefined; }
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function init(options = {}) {
|
|
12
|
+
const noop = { track() {}, page() {}, identify() { return null; }, reset() {}, optOut() {}, destroy() {} };
|
|
13
|
+
if (typeof window === 'undefined' || !options.projectId || typeof options.writeKey !== 'string' || !/^Zappa_[A-Za-z0-9_-]{16,}$/.test(options.writeKey)) return noop;
|
|
14
|
+
if (options.enabled === false) return noop;
|
|
15
|
+
if (window.__ZappaAnalytics) return window.__ZappaAnalytics;
|
|
16
|
+
|
|
17
|
+
const endpoint = options.endpoint || DEFAULT_ENDPOINT;
|
|
18
|
+
const visitorKey = VISITOR_KEY + ':' + options.projectId, sessionKey = SESSION_KEY + ':' + options.projectId;
|
|
19
|
+
let enabled = options.enabled !== false;
|
|
20
|
+
let queue = [], timer = null, lastUrl = null, lastPath = null;
|
|
21
|
+
let vitals = {}, vitalsSent = false;
|
|
22
|
+
const observerList = [];
|
|
23
|
+
const originals = {};
|
|
24
|
+
const read = (key) => { try { return localStorage.getItem(key); } catch { return null; } };
|
|
25
|
+
const write = (key, value) => { try { localStorage.setItem(key, value); } catch {} };
|
|
26
|
+
const remove = (key) => { try { localStorage.removeItem(key); } catch {} };
|
|
27
|
+
if (enabled) { if (!read(visitorKey) && read(VISITOR_KEY)) write(visitorKey, read(VISITOR_KEY)); if (!read(sessionKey) && read(SESSION_KEY)) write(sessionKey, read(SESSION_KEY)); }
|
|
28
|
+
const visitor = () => { if (!enabled) return null; let value = read(visitorKey); if (!value) { value = makeId(); if (value) write(visitorKey, value); } return value; };
|
|
29
|
+
const campaign = () => { const values = {}; try { const params = new URL(location.href).searchParams; ['utm_source','utm_medium','utm_campaign','utm_content','utm_term'].forEach(key => { const value = params.get(key); if (value && /^[a-zA-Z0-9][a-zA-Z0-9 _.-]{0,127}$/.test(value)) values[key] = value; }); } catch {} return values; };
|
|
30
|
+
const session = () => {
|
|
31
|
+
const now = Date.now(); let state;
|
|
32
|
+
try { state = JSON.parse(read(sessionKey) || 'null'); } catch { state = null; }
|
|
33
|
+
if (!state?.id || now - state.lastActivity >= IDLE_MS || now - state.startedAt >= MAX_SESSION_MS) {
|
|
34
|
+
state = { id: makeId(), startedAt: now, lastActivity: now, entryPage: location.pathname, exitPage: location.pathname, pageviews: 0 };
|
|
35
|
+
}
|
|
36
|
+
state.lastActivity = now; write(sessionKey, JSON.stringify(state)); return state;
|
|
37
|
+
};
|
|
38
|
+
const observe = (type, update) => {
|
|
39
|
+
try { const observer = new PerformanceObserver((list) => update(list.getEntries())); observer.observe({ type, buffered: true }); observerList.push(observer); } catch {}
|
|
40
|
+
};
|
|
41
|
+
const observeVitals = () => {
|
|
42
|
+
if (typeof PerformanceObserver === 'undefined') return;
|
|
43
|
+
observe('largest-contentful-paint', (entries) => { const last = entries[entries.length - 1]; if (last) vitals.lcp = Math.round(last.startTime); });
|
|
44
|
+
observe('layout-shift', (entries) => entries.forEach((entry) => { vitals.clsSeen = true; if (!entry.hadRecentInput) vitals.cls = Math.round(((vitals.cls || 0) + entry.value) * 10000) / 10000; }));
|
|
45
|
+
observe('event', (entries) => { const list = vitals.interactions || []; entries.forEach((entry) => { if (entry.duration) list.push(entry.duration); }); vitals.interactions = list.slice(-50).sort((a, b) => a - b); });
|
|
46
|
+
};
|
|
47
|
+
const resetVitals = () => { vitals = {}; vitalsSent = false; };
|
|
48
|
+
const flushVitals = (path) => {
|
|
49
|
+
if (!enabled || vitalsSent) return;
|
|
50
|
+
const properties = {}, interactions = vitals.interactions || [];
|
|
51
|
+
if (vitals.lcp) properties.lcp_ms = vitals.lcp;
|
|
52
|
+
if (vitals.clsSeen) properties.cls = vitals.cls || 0;
|
|
53
|
+
if (interactions.length) properties.inp_ms = Math.round(interactions[Math.floor((interactions.length - 1) * 0.98)]);
|
|
54
|
+
if (!properties.lcp_ms && !properties.cls && !properties.inp_ms) return;
|
|
55
|
+
vitalsSent = true; track('web_vitals', properties, path);
|
|
56
|
+
};
|
|
57
|
+
const flush = () => {
|
|
58
|
+
if (timer) clearTimeout(timer); timer = null;
|
|
59
|
+
if (!enabled || !queue.length) return;
|
|
60
|
+
const batch = queue.slice(0, 20); queue = queue.slice(batch.length);
|
|
61
|
+
fetch(endpoint, { method: 'POST', credentials: 'omit', keepalive: true, headers: { 'Content-Type': 'application/json', 'X-Zappa-Key': options.writeKey }, body: JSON.stringify({ projectId: options.projectId, events: batch }) })
|
|
62
|
+
.then((response) => { if (!response.ok && (response.status === 429 || response.status >= 500)) throw new Error('Temporary ingestion failure'); })
|
|
63
|
+
.catch(() => { if (enabled) { queue = [...batch, ...queue].slice(0, 100); timer ??= setTimeout(flush, 10000); } });
|
|
64
|
+
if (queue.length) timer ??= setTimeout(flush, 2000);
|
|
65
|
+
};
|
|
66
|
+
const track = (name, properties = {}, pathOverride, pageReferrer) => {
|
|
67
|
+
if (!enabled || typeof name !== 'string' || !/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(name)) return;
|
|
68
|
+
const clean = {};
|
|
69
|
+
if (properties && typeof properties === 'object') Object.entries(properties).slice(0, 20).forEach(([key, value]) => {
|
|
70
|
+
if (/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(key) && !/password|token|secret|email/i.test(key) && (typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value)))) clean[key] = value;
|
|
71
|
+
});
|
|
72
|
+
const active = session();
|
|
73
|
+
if (name === 'pageview') { active.pageviews += 1; active.exitPage = location.pathname; write(sessionKey, JSON.stringify(active)); }
|
|
74
|
+
let referrer = pageReferrer;
|
|
75
|
+
if (typeof referrer === 'undefined') {
|
|
76
|
+
try { referrer = document.referrer ? new URL(document.referrer).hostname : null; } catch { referrer = null; }
|
|
77
|
+
}
|
|
78
|
+
const event = { id: makeId(), name, timestamp: new Date().toISOString(), path: pathOverride || location.pathname, visitorId: visitor(), sessionId: active.id, referrer, properties: clean, schemaVersion: 1 };
|
|
79
|
+
if (name === 'pageview') event.attribution = campaign();
|
|
80
|
+
queue.push(event);
|
|
81
|
+
if (queue.length > 100) queue.shift();
|
|
82
|
+
if (queue.length >= 20) flush(); else timer ??= setTimeout(flush, 2000);
|
|
83
|
+
};
|
|
84
|
+
const page = () => {
|
|
85
|
+
const url = location.pathname + location.search;
|
|
86
|
+
if (!enabled || url === lastUrl) return;
|
|
87
|
+
flushVitals(lastPath || location.pathname); resetVitals();
|
|
88
|
+
const previous = lastUrl;
|
|
89
|
+
lastUrl = url; lastPath = location.pathname;
|
|
90
|
+
// SPA navigation comes from this site, not from the original external referrer.
|
|
91
|
+
const referrer = previous ? location.hostname : undefined;
|
|
92
|
+
track('pageview', {}, undefined, referrer);
|
|
93
|
+
};
|
|
94
|
+
const leaving = () => { flushVitals(lastPath); flush(); };
|
|
95
|
+
const hidden = () => { if (document.visibilityState === 'hidden') leaving(); };
|
|
96
|
+
const dispatchRoute = () => window.dispatchEvent(new Event('Zappa:navigation'));
|
|
97
|
+
['pushState', 'replaceState'].forEach((method) => {
|
|
98
|
+
const original = history[method];
|
|
99
|
+
if (typeof original !== 'function' || original.__ZappaPatched) return;
|
|
100
|
+
const wrapped = function (...args) { const result = original.apply(this, args); dispatchRoute(); return result; };
|
|
101
|
+
wrapped.__ZappaPatched = true; originals[method] = original; history[method] = wrapped;
|
|
102
|
+
});
|
|
103
|
+
const api = {
|
|
104
|
+
track, page, flush, identify: visitor,
|
|
105
|
+
reset() { remove(visitorKey); remove(sessionKey); remove(VISITOR_KEY); remove(SESSION_KEY); resetVitals(); lastUrl = null; lastPath = null; page(); },
|
|
106
|
+
optOut() { enabled = false; queue = []; lastUrl = null; resetVitals(); observerList.forEach((observer) => { try { observer.disconnect(); } catch {} }); observerList.length = 0; if (timer) clearTimeout(timer); timer = null; remove(visitorKey); remove(sessionKey); remove(VISITOR_KEY); remove(SESSION_KEY); },
|
|
107
|
+
destroy() {
|
|
108
|
+
enabled = false; queue = [];
|
|
109
|
+
window.removeEventListener('popstate', page); window.removeEventListener('Zappa:navigation', page); window.removeEventListener('pagehide', leaving);
|
|
110
|
+
document.removeEventListener('visibilitychange', hidden);
|
|
111
|
+
Object.entries(originals).forEach(([method, original]) => { if (history[method]?.__ZappaPatched) history[method] = original; });
|
|
112
|
+
if (timer) clearTimeout(timer); timer = null;
|
|
113
|
+
if (window.__ZappaAnalytics === api) delete window.__ZappaAnalytics;
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
if (enabled) {
|
|
117
|
+
observeVitals();
|
|
118
|
+
window.addEventListener('popstate', page); window.addEventListener('Zappa:navigation', page); window.addEventListener('pagehide', leaving); document.addEventListener('visibilitychange', hidden); page();
|
|
119
|
+
}
|
|
120
|
+
window.__ZappaAnalytics = api;
|
|
121
|
+
return api;
|
|
122
|
+
}
|
package/next.d.ts
ADDED
package/next.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { useEffect } from 'react';
|
|
3
|
+
import { init } from './index.js';
|
|
4
|
+
|
|
5
|
+
export function Analytics({ projectId, writeKey, endpoint, enabled = true }) {
|
|
6
|
+
useEffect(() => {
|
|
7
|
+
if (!enabled) return;
|
|
8
|
+
const analytics = init({ projectId, writeKey, endpoint });
|
|
9
|
+
return () => analytics.destroy();
|
|
10
|
+
}, [projectId, writeKey, endpoint, enabled]);
|
|
11
|
+
return null;
|
|
12
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@aman-sagar06077/zappa-analytics",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@aman-sagar06077/zappa-analytics",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Privacy-aware website analytics for Zappa projects.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./index.d.ts",
|
|
11
|
+
"default": "./index.js"
|
|
12
|
+
},
|
|
13
|
+
"./next": {
|
|
14
|
+
"types": "./next.d.ts",
|
|
15
|
+
"default": "./next.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"index.js",
|
|
20
|
+
"index.d.ts",
|
|
21
|
+
"next.js",
|
|
22
|
+
"next.d.ts",
|
|
23
|
+
"README.md"
|
|
24
|
+
],
|
|
25
|
+
"peerDependencies": {
|
|
26
|
+
"react": ">=18"
|
|
27
|
+
},
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
}
|
|
31
|
+
}
|