@dotcms/analytics
Version:
Official JavaScript library for Content Analytics with DotCMS.
130 lines (129 loc) • 3.81 kB
JavaScript
import { DotCMSPredefinedEventType as r } from "../../shared/constants/dot-analytics.constants.js";
import { sendAnalyticsEvent as N } from "../../shared/http/dot-analytics.http.js";
import { createAnalyticsQueue as w } from "../../shared/queue/dot-analytics.queue.utils.js";
const _ = (d) => {
let u = !1;
const m = d.queue !== !1;
let p = null;
const v = (e) => {
const c = e.events[0], t = e.context;
m && p ? p.enqueue(c, t) : N(e, d);
};
return {
name: "dot-analytics",
config: d,
/**
* Initialize the plugin with optional queue management
*/
initialize: () => (u = !0, m && (p = w(d), p.initialize()), Promise.resolve()),
/**
* Track a page view event
* Receives enriched payload from the enricher plugin and structures it into a pageview event
*/
page: ({ payload: e }) => {
if (!u)
throw new Error("DotCMS Analytics: Plugin not initialized");
const { context: c, page: t, utm: E, custom: s, local_time: a } = e;
if (!t)
throw new Error("DotCMS Analytics: Missing required page data");
const y = {
context: c,
events: [
{
event_type: r.PAGEVIEW,
local_time: a,
data: {
page: t,
...E && { utm: E },
...s && { custom: s }
}
}
]
};
v(y);
},
/**
* Track a custom or predefined event
* Receives enriched payload from enricher plugin and structures it into proper event format.
*
* - content_impression → extracts from properties, combines with enriched page data
* - content_click → extracts from properties, combines with enriched page data
* - custom events → wraps properties in custom object
*/
track: ({ payload: e }) => {
if (!u)
throw new Error("DotCMS Analytics: Plugin not initialized");
const { event: c, properties: t, context: E, local_time: s } = e;
let a;
switch (c) {
case r.CONTENT_IMPRESSION: {
const l = t, { content: n, position: i } = l, { page: o } = e;
if (!n || !i || !o)
throw new Error("DotCMS Analytics: Missing required impression data");
a = {
event_type: r.CONTENT_IMPRESSION,
local_time: s,
data: {
content: n,
position: i,
page: o
}
};
break;
}
case r.CONTENT_CLICK: {
const l = t, { content: n, position: i, element: o } = l, { page: C } = e;
if (!n || !i || !o || !C)
throw new Error("DotCMS Analytics: Missing required click data");
a = {
event_type: r.CONTENT_CLICK,
local_time: s,
data: {
content: n,
position: i,
element: o,
page: C
}
};
break;
}
case r.CONVERSION: {
const l = t, { name: n, custom: i } = l, { page: o } = e;
if (!n || !o)
throw new Error("DotCMS Analytics: Missing required conversion data");
a = {
event_type: r.CONVERSION,
local_time: s,
data: {
conversion: { name: n },
page: o,
...i && { custom: i }
}
};
break;
}
default: {
a = {
event_type: c,
local_time: s,
data: {
custom: t
}
};
break;
}
}
v({
context: E,
events: [a]
});
},
/**
* Check if the plugin is loaded
*/
loaded: () => u
};
};
export {
_ as dotAnalytics
};