UNPKG

@dotcms/analytics

Version:

Official JavaScript library for Content Analytics with DotCMS.

203 lines (202 loc) 6.67 kB
import { ANALYTICS_JS_DEFAULT_PROPERTIES as T, SESSION_STORAGE_KEY as h, DEFAULT_SESSION_TIMEOUT_MINUTES as y, USER_ID_KEY as w, DEFAULT_IMPRESSION_MUTATION_OBSERVER_DEBOUNCE_MS as I, EXPECTED_UTM_KEYS as D, ANALYTICS_CONTENTLET_CLASS as S } from "../constants/dot-analytics.constants.js"; import { DotLogger as E } from "../dot-analytics.logger.js"; import "../../../../uve/src/internal/constants.js"; function Y(t) { var n, s; const e = []; return (n = t.siteAuth) != null && n.trim() || e.push('"siteAuth"'), (s = t.server) != null && s.trim() || e.push('"server"'), e.length > 0 ? e : null; } let u = null, l = null; const g = (t) => { const e = Date.now(), n = Math.random().toString(36).substr(2, 9), s = Math.random().toString(36).substr(2, 9); return `${t}_${e}_${n}${s}`; }, _ = { getItem: (t) => { try { return localStorage.getItem(t); } catch { return null; } }, setItem: (t, e) => { try { localStorage.setItem(t, e); } catch { console.warn(`DotCMS Analytics [Core]: Could not save ${t} to localStorage`); } } }, A = () => { let t = _.getItem(w); return t || (t = g("user"), _.setItem(w, t)), t; }, C = (t) => { const e = new Date(t), n = /* @__PURE__ */ new Date(), s = new Date( e.getUTCFullYear(), e.getUTCMonth(), e.getUTCDate() ), r = new Date(n.getUTCFullYear(), n.getUTCMonth(), n.getUTCDate()); return s.getTime() !== r.getTime(); }, v = () => { const t = Date.now(); if (typeof window > "u") return g("session_fallback"); try { const e = sessionStorage.getItem(h); if (e) { const { sessionId: r, startTime: o, lastActivity: a } = JSON.parse(e), i = !C(o), c = t - a < y * 60 * 1e3; if (i && c) return sessionStorage.setItem( h, JSON.stringify({ sessionId: r, startTime: o, lastActivity: t }) ), r; } const n = g("session"), s = { sessionId: n, startTime: t, lastActivity: t }; return sessionStorage.setItem(h, JSON.stringify(s)), n; } catch { return g("session_fallback"); } }, x = (t) => { const e = v(), n = A(), s = O(); return { site_auth: t.siteAuth, session_id: e, user_id: n, device: s }; }, p = () => u || (u = { user_language: navigator.language, doc_encoding: document.characterSet || document.charset, screen_resolution: typeof screen < "u" && screen.width && screen.height ? `${screen.width}x${screen.height}` : "" }, u), O = () => { const t = p(), e = window.innerWidth || document.documentElement.clientWidth || 0, n = window.innerHeight || document.documentElement.clientHeight || 0; return { screen_resolution: t.screen_resolution ?? "", language: t.user_language ?? "", viewport_width: String(e), viewport_height: String(n) }; }, N = (t) => { const e = t.search; if (l && l.search === e) return l.params; const n = new URLSearchParams(e), s = {}; return D.forEach((r) => { const o = n.get(r); if (o) { const a = r.replace("utm_", ""); s[a] = o; } }), l = { search: e, params: s }, s; }, b = () => { try { const t = (/* @__PURE__ */ new Date()).getTimezoneOffset(), e = t > 0 ? "-" : "+", n = Math.abs(t), s = Math.floor(n / 60), r = n % 60; return `${e}${s.toString().padStart(2, "0")}:${r.toString().padStart(2, "0")}`; } catch { return "+00:00"; } }, M = () => { try { const t = /* @__PURE__ */ new Date(), e = b(), n = t.getFullYear(), s = (t.getMonth() + 1).toString().padStart(2, "0"), r = t.getDate().toString().padStart(2, "0"), o = t.getHours().toString().padStart(2, "0"), a = t.getMinutes().toString().padStart(2, "0"), i = t.getSeconds().toString().padStart(2, "0"); return `${n}-${s}-${r}T${o}:${a}:${i}${e}`; } catch { return (/* @__PURE__ */ new Date()).toISOString(); } }, B = (t, e = typeof window < "u" ? window.location : {}) => { const n = M(), s = p(), { properties: r } = t, o = {}; Object.keys(r).forEach((c) => { T.includes(c) || (o[c] = r[c]); }); const a = { url: e.href, doc_encoding: s.doc_encoding, doc_hash: e.hash, doc_protocol: e.protocol, doc_search: e.search, doc_host: e.hostname, doc_path: e.pathname, title: r.title ?? (document == null ? void 0 : document.title) }, i = N(e); return { ...t, page: a, ...Object.keys(i).length > 0 && { utm: i }, // Only include custom if there are user-provided properties ...Object.keys(o).length > 0 && { custom: o }, local_time: n }; }; function L(t, e) { let n = 0; return (...s) => { const r = Date.now(); r - n >= e && (t(...s), n = r); }; } function F(t) { return t.dataset.dotAnalyticsIdentifier || null; } function k(t) { return { identifier: t.dataset.dotAnalyticsIdentifier || "", inode: t.dataset.dotAnalyticsInode || "", contentType: t.dataset.dotAnalyticsContenttype || "", title: t.dataset.dotAnalyticsTitle || "", baseType: t.dataset.dotAnalyticsBasetype || "" }; } const z = 100, U = () => typeof window < "u" && typeof document < "u", H = () => Array.from(document.querySelectorAll(`.${S}`)), J = (t, e = I) => { const n = L(t, e), s = new MutationObserver((r) => { r.some((a) => a.addedNodes.length === 0 && a.removedNodes.length === 0 ? !1 : [ ...Array.from(a.addedNodes), ...Array.from(a.removedNodes) ].some((c) => { var f, m; if (c.nodeType !== Node.ELEMENT_NODE) return !1; const d = c; return (f = d.classList) != null && f.contains(S) ? !0 : ((m = d.querySelector) == null ? void 0 : m.call(d, `.${S}`)) !== null; })) && n(); }); return s.observe(document.body, { childList: !0, subtree: !0, attributes: !1, characterData: !1 }), s; }, K = (t) => { U() && (window.addEventListener("beforeunload", t), window.addEventListener("pagehide", t)); }, j = (t, e) => { const n = e.logLevel ?? (e.debug ? "debug" : "warn"); return new E("Analytics", t, n); }, W = (t, e, n) => [ t.impressions && e(t), t.clicks && n(t) ].filter(Boolean); export { z as INITIAL_SCAN_DELAY_MS, J as createContentletObserver, j as createPluginLogger, L as createThrottle, B as enrichPagePayloadOptimized, k as extractContentletData, F as extractContentletIdentifier, N as extractUTMParameters, H as findContentlets, g as generateSecureId, x as getAnalyticsContext, O as getDeviceDataForContext, W as getEnhancedTrackingPlugins, M as getLocalTime, v as getSessionId, A as getUserId, U as isBrowser, K as setupPluginCleanup, Y as validateAnalyticsConfig };