@chordcommerce/analytics
Version:
Chord Commerce event tracking
74 lines (73 loc) • 3.36 kB
JavaScript
/* eslint-disable no-console */
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { addCdpConsent } from './consent/index.js';
import { normalizeCDPDomain } from './utils.js';
/*
* Adds the Chord CDP snippet to the page.
* Returns initial consent configuration to be tracked after CDP is fully ready.
*/
export const addCdpSnippet = (options) => __awaiter(void 0, void 0, void 0, function* () {
if (!document || typeof document.createElement === 'undefined') {
return { initialConsent: null };
}
const normalizedCDPDomain = normalizeCDPDomain(options.cdpDomain);
// Create a promise that resolves when CDP is ready
const cdpReadyPromise = new Promise((resolve) => {
const checkCdpReady = () => {
const cdp = window[`_${options.namespace}`];
if (cdp && typeof cdp.configure === 'function') {
resolve();
}
else {
setTimeout(checkCdpReady, 50);
}
};
checkCdpReady();
});
// Guard against duplicate script injection (e.g. React StrictMode remounts)
const escapedNamespace = typeof CSS !== 'undefined' && typeof CSS.escape === 'function'
? CSS.escape(`_${options.namespace}`)
: `_${options.namespace}`;
const existingScript = document.querySelector(`script[data-namespace="${escapedNamespace}"]`);
if (!existingScript) {
const s = document.createElement('script');
s.async = true;
s.src = `${normalizedCDPDomain}/p.js`;
s.setAttribute('data-debug', `${!!options.debug}`);
s.setAttribute('data-init-only', 'true');
s.setAttribute('data-namespace', `_${options.namespace}`);
s.setAttribute('data-write-key', options.cdpWriteKey);
document.head.appendChild(s);
}
// Wait for CDP to be ready before setting up consent
yield cdpReadyPromise;
let initialConsent = null;
if (options.consent) {
initialConsent = yield addCdpConsent(options).init();
}
if (options.debug && options.enableLogging) {
console.log('[Chord Analytics DEBUG]: CDP snippet added, initialConsent:', JSON.stringify(initialConsent));
}
return { initialConsent };
});
/*
* Returns the CDP queue to hold events ahead of CDP initialization.
*/
export const cdpQueue = (namespace) => {
var _a;
const q = window && (window[_a = `_${namespace}Q`] || (window[_a] = []));
return {
track: (...args) => q.push((cdp) => cdp.track(...args)),
identify: (...args) => q.push((cdp) => cdp.identify(...args)),
page: (...args) => q.push((cdp) => cdp.page(...args)),
reset: (...args) => q.push((cdp) => cdp.reset(...args)),
};
};