UNPKG

@chordcommerce/analytics

Version:

Chord Commerce event tracking

73 lines (72 loc) 2.57 kB
import { getOneTrustGlobal, getNormalizedCategories, coerceConsentModel, hasActiveGroups, } from './onetrust-api.js'; /** * Returns whether the user can currently be tracked. * Uses duck typing to check if OneTrust is fully loaded. */ const userCanBeTracked = () => { // Always loads when OneTrust is ready, a la `consentModel: 'opt-out'` return !!getOneTrustGlobal(); }; /** * Returns the user's current consent configuration. * Reads FRESH from OneTrust - no caching! */ const getCurrentConsent = () => { const api = getOneTrustGlobal(); if (!api) return {}; return { consentCategories: getNormalizedCategories(), }; }; /** * Handles subsequent changes to consent configuration. * Sets up OnConsentChanged listener with retry logic. */ const handleConsentUpdates = (updateCdpConsent, options) => { const maxRetries = 100; const retryInterval = 50; let attempts = 0; const setupHandler = () => { const api = getOneTrustGlobal(); if (!api) { attempts++; if (attempts < maxRetries) { if (options.debug && options.enableLogging) { console.log('[Chord Analytics DEBUG]: OneTrust API not found, retrying...'); } setTimeout(setupHandler, retryInterval); } return; } if (options.debug && options.enableLogging) { console.log('[Chord Analytics DEBUG]: OneTrust API found, setting up consent changed handler'); } api.OnConsentChanged(() => { updateCdpConsent(getCurrentConsent()); if (options.debug && options.enableLogging) { console.log('[Chord Analytics DEBUG]: OneTrust consent changed, sending Consent Preferences Updated track event'); } }); }; setupHandler(); }; export const onetrustConsentAdapter = (options) => { return { // Existing methods for backwards compatibility getCurrentConsent, handleConsentUpdates: (updateCdpConsent) => { handleConsentUpdates(updateCdpConsent, options); }, userCanBeTracked, getCategories: () => getNormalizedCategories(), isConsentReady: () => !!getOneTrustGlobal() && hasActiveGroups(), getConsentModel: () => { const api = getOneTrustGlobal(); if (!api) return 'opt-out'; return coerceConsentModel(api.GetDomainData().ConsentModel.Name); }, getApi: getOneTrustGlobal, }; };