@identitysquare/cookiechimp-segment-wrapper
Version:
CookieChimp wrapper for Segment
59 lines (58 loc) • 2.96 kB
JavaScript
;
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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.withCookieChimpCMP = void 0;
const analytics_consent_tools_1 = require("@segment/analytics-consent-tools");
// Normalizes categories into the expected format { foo: true, bar: false }
const normalizeCategories = (preferences) => {
// Initialize object with rejected categories set to false
const categories = preferences.rejectedCategories.reduce((acc, category) => {
acc[category] = false;
return acc;
}, {});
// Add accepted categories set to true
return preferences.acceptedCategories.reduce((acc, category) => {
acc[category] = true;
return acc;
}, categories);
};
const withCookieChimpCMP = (analytics, options = {}) => {
const wrapper = (0, analytics_consent_tools_1.createWrapper)({
// Wait to load wrapper or call "shouldLoadSegment" until window.CMP exists.
shouldLoadWrapper: () => __awaiter(void 0, void 0, void 0, function* () {
yield (0, analytics_consent_tools_1.resolveWhen)(() => window.CookieChimp !== undefined, 500);
}),
// Allow for control over wrapper + analytics initialization.
// Delay any calls to analytics.load() until this function returns / resolves.
shouldLoadSegment: (ctx) => __awaiter(void 0, void 0, void 0, function* () {
if (options.alwaysLoadSegment) {
return ctx.load({ consentModel: 'opt-out' });
}
if (window.CookieChimp.visitorNeedsConsent) {
yield (0, analytics_consent_tools_1.resolveWhen)(() => window.CookieChimp.validConsent(), 500);
return ctx.load({ consentModel: 'opt-in' });
}
else {
return ctx.load({ consentModel: 'opt-out' });
}
}),
getCategories: () => {
return normalizeCategories(window.CookieChimp.getUserPreferences());
},
registerOnConsentChanged: setCategories => {
window.addEventListener('cc:onUpdate', () => {
setCategories(normalizeCategories(window.CookieChimp.getUserPreferences()));
});
},
});
return wrapper(analytics);
};
exports.withCookieChimpCMP = withCookieChimpCMP;