UNPKG

lanesdotdev-analytics

Version:

Analytics package for Lanes.dev

112 lines (111 loc) 3.06 kB
// src/index.ts var Analytics = class _Analytics { static { this.API_URL = window.__ANALYTICS_API_URL__ || "https://lanes.dev/api/event"; } constructor({ apiKey }) { this.apiKey = apiKey; configureAnalytics({ projectApiKey: apiKey, autoTrack: true, trackSPA: true }); this.trackPageView(); } async trackPageView(options = {}) { const data = { path: window.location.pathname, referrer: document.referrer, userAgent: navigator.userAgent, sessionId: this.getSessionId(), timestamp: (/* @__PURE__ */ new Date()).toISOString() }; try { await fetch(_Analytics.API_URL, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${this.apiKey}` }, body: JSON.stringify(data) }); } catch (error) { console.error("Failed to track page view:", error); } } getSessionId() { let sessionId = localStorage.getItem("analytics_session_id"); if (!sessionId) { sessionId = Math.random().toString(36).substring(2) + Date.now().toString(36); localStorage.setItem("analytics_session_id", sessionId); } return sessionId; } }; async function trackPageView({ projectApiKey, path, referrer }) { if (!projectApiKey) { console.error("Project API key is required"); return; } const currentPath = path || window.location.pathname; const currentReferrer = referrer || document.referrer; const eventData = { path: currentPath, referrer: currentReferrer, user_agent: navigator.userAgent }; try { await fetch(Analytics.API_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": projectApiKey }, body: JSON.stringify(eventData), // Do not send cookies with the request credentials: "omit" }); } catch (error) { console.error("Failed to track page view:", error); } } function configureAnalytics(config) { if (typeof window !== "undefined") { window.__ANALYTICS_CONFIG__ = config; } } if (typeof window !== "undefined") { const script = document.currentScript; if (script) { const projectApiKey = script.getAttribute("data-project-api-key"); const autoTrack = script.getAttribute("data-auto-track") !== "false"; const trackSPA = script.getAttribute("data-track-spa") !== "false"; if (projectApiKey) { configureAnalytics({ projectApiKey, autoTrack, trackSPA }); if (autoTrack) { trackPageView({ projectApiKey }); if (trackSPA && "pushState" in history) { const originalPushState = history.pushState; history.pushState = function(...args) { originalPushState.apply(this, args); trackPageView({ projectApiKey }); }; window.addEventListener("popstate", () => { trackPageView({ projectApiKey }); }); } } } } } export { Analytics };