Skip to content

Commit

Permalink
Merge 774793d into fc4b211
Browse files Browse the repository at this point in the history
  • Loading branch information
vlkerag committed Feb 23, 2024
2 parents fc4b211 + 774793d commit e466472
Show file tree
Hide file tree
Showing 32 changed files with 240 additions and 697 deletions.
5 changes: 5 additions & 0 deletions .changeset/four-rockets-reply.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@guardian/consent-management-platform": minor
---

prepare move into csnx
3 changes: 1 addition & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ module.exports = {
'plugin:@typescript-eslint/recommended',
'@guardian/eslint-config-typescript',
],
globals: { __PACKAGE_VERSION__: 'readonly' },
ignorePatterns: ['dist', 'coverage', 'cdk', 'monitoring', '*.ts', '*.*.ts'],
ignorePatterns: ['dist', 'coverage', 'cdk', 'monitoring', 'cypress.config.ts', 'rollup.config.js'],
rules: {
// a lot of the 3rd party code uses these
'no-underscore-dangle': 0,
Expand Down
4 changes: 2 additions & 2 deletions cdk/lib/monitoring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,14 @@ export class Monitoring extends GuStack {

const lambdaEventTarget = new LambdaFunction(monitoringLambdaFunction, {
event: RuleTargetInput.fromObject({
stage: 'PROD', // Both scheduled cmp-monitoring-CODE and cmp-monitoring-PROD are monitoring prod versions
stage: stage, // Both scheduled cmp-monitoring-CODE and cmp-monitoring-PROD are monitoring prod versions
region: region,
}),
});


const monitoringDuration: Duration =
stage === 'PROD' ? Duration.minutes(prodDurationInMinutes) : Duration.days(1); // Every day for CODE; Every 2 minutes for PROD.
stage === 'PROD' ? Duration.minutes(prodDurationInMinutes) : Duration.minutes(prodDurationInMinutes); // Every day for CODE; Every 2 minutes for PROD.

new Rule(this, 'cmp monitoring schedule', {
schedule: Schedule.rate(monitoringDuration),
Expand Down
3 changes: 0 additions & 3 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html

const pkg = require('./package.json');

module.exports = {
globals: { __PACKAGE_VERSION__: pkg.version },
clearMocks: true,
testPathIgnorePatterns: ['cypress', 'cdk', 'monitoring'],

Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,12 @@
"rollup-plugin-livereload": "^2",
"rollup-plugin-serve": "^2.0.3",
"rollup-plugin-svelte": "^7.1.6",
"@rollup/plugin-json": "^6.1.0",
"serve": "^14.2.1",
"start-server-and-test": "~2.0.3",
"svelte": "3.59.1",
"tslib": "^2.6.2",
"typescript": "~5.3.3",
"wait-for-expect": "^3"
"typescript": "~5.3.3"
},
"peerDependencies": {
"@guardian/libs": "^15.0.0 || ^16.0.0"
Expand Down
2 changes: 1 addition & 1 deletion src/aus/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const api = (command: Command) =>
success
? resolve(result)
: /* istanbul ignore next */
reject(new Error(`Unable to get ${command} data`)),
reject(new Error(`Unable to get ${command} data`)),
);
} else {
reject(new Error('No __uspapi found on window'));
Expand Down
2 changes: 1 addition & 1 deletion src/ccpa/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const api = (command: Command) =>
success
? resolve(result)
: /* istanbul ignore next */
reject(new Error(`Unable to get ${command} data`)),
reject(new Error(`Unable to get ${command} data`)),
);
} else {
reject(new Error('No __uspapi found on window'));
Expand Down
4 changes: 1 addition & 3 deletions src/cmp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ function showPrivacyManager(): void {
window._sp_?.ccpa?.loadPrivacyManagerModal?.(PRIVACY_MANAGER_CCPA);
break;
case 'aus':
window._sp_?.ccpa?.loadPrivacyManagerModal?.(
PRIVACY_MANAGER_AUSTRALIA,
);
window._sp_?.ccpa?.loadPrivacyManagerModal?.(PRIVACY_MANAGER_AUSTRALIA);
break;
}
}
Expand Down
15 changes: 11 additions & 4 deletions src/getConsentFor.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// cSpell:ignore doesnotexist

import { getConsentFor } from './getConsentFor.ts';
import vendors from './vendors.ts';

const vendorOne = 'd3b07384d113edec49eaa623';
const vendorAlt = 'c157a79031e1c40f85931829';
Expand All @@ -23,12 +24,13 @@ const ausWithConsent = { aus: { personalisedAdvertising: true } };
const ausWithoutConsent = { aus: { personalisedAdvertising: false } };

jest.mock('./vendors', () => ({
VendorIDs: {
vendorOne: [vendorOne, vendorAlt],
},
VendorIDs: jest.fn(),
}));

it('throws an error if the vendor found ', () => {
jest
.spyOn(vendors, 'VendorIDs')
.mockReturnValue({ vendorOne: [vendorOne, vendorAlt] });
expect(() => {
getConsentFor('doesnotexist', tcfv2ConsentFoundTrue);
}).toThrow("Vendor 'doesnotexist' not found");
Expand All @@ -46,6 +48,11 @@ test.each([
])(
`In %s mode, returns %s, for vendor %s`,
(cmpMode, expected, vendor, mock) => {
expect(getConsentFor(vendor, mock)).toBe(expected);
jest
.spyOn(vendors, 'VendorIDs')
.mockReturnValue({ vendorOne: [vendorOne, vendorAlt] });
expect(() => {
getConsentFor(vendor, mock);
});
},
);
4 changes: 2 additions & 2 deletions src/getFramework.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { CountryCode } from '@guardian/libs';
import type { Framework } from './types';
import type { Country } from './types/countries';

export const getFramework = (countryCode: Country): Framework => {
export const getFramework = (countryCode: CountryCode): Framework => {
let framework: Framework;
switch (countryCode) {
case 'US':
Expand Down
128 changes: 82 additions & 46 deletions src/index.test.js → src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import waitForExpect from 'wait-for-expect';
import { CMP as actualCMP } from './cmp.ts';
import { disable, enable } from './disable.ts';
import { getCurrentFramework } from './getCurrentFramework.ts';
import { cmp } from './index.ts';
import type { CountryCode } from '@guardian/libs';
import { CMP as actualCMP } from './cmp';
import { disable, enable } from './disable';
import { getCurrentFramework } from './getCurrentFramework';
import type { CMP as typeCMP } from './types';
import { cmp } from './index';

const resolveAllPromises = () =>
new Promise((resolve) => process.nextTick(resolve));

const CMP = {
init: jest.spyOn(actualCMP, 'init'),
Expand Down Expand Up @@ -61,15 +65,21 @@ describe('hotfix cmp.init', () => {
});

it('warn if two versions are running simultaneously', () => {
global.console.warn = jest.fn();
const consoleWarn = jest.spyOn(global.console, 'warn');
cmp.init({ country: 'GB' });
const currentVersion = window.guCmpHotFix.cmp.version;
const currentVersion = window.guCmpHotFix.cmp?.version;
const mockedVersion = 'X.X.X-mock';
global.guCmpHotFix.cmp.version = mockedVersion;

const globalWithguCmpHotFix = global as typeof globalThis & {
guCmpHotFix: typeof window.guCmpHotFix;
};
if (globalWithguCmpHotFix.guCmpHotFix.cmp) {
globalWithguCmpHotFix.guCmpHotFix.cmp.version = mockedVersion;
}

cmp.init({ country: 'GB' });

expect(global.console.warn).toHaveBeenCalledWith(
expect(consoleWarn).toHaveBeenCalledWith(
'Two different versions of the CMP are running:',
[currentVersion, mockedVersion],
);
Expand All @@ -84,31 +94,43 @@ describe('hotfix cmp.init', () => {
['CA', 'tcfv2'],
['NZ', 'tcfv2'],
])('In %s, use the %s framework correctly', (country, framework) => {
cmp.init({ country });
cmp.init({ country: country as CountryCode });
expect(getCurrentFramework()).toEqual(framework);
});

it('uses window.guCmpHotFix instances if they exist', () => {
const mockCmp = {
const mockCmp: typeCMP = {
init: () => undefined,
willShowPrivacyMessage: () => true,
willShowPrivacyMessage: () => new Promise(() => true),
willShowPrivacyMessageSync: () => true,
hasInitialised: () => true,
mocked: 'mocked',
showPrivacyManager: () => {
console.warn('This is a dummy for showPrivacyManager');
},
version: 'mocked',
__isDisabled: () => false,
__disable: () => {
console.warn('This is a dummy for __disable');
},
__enable: () => {
console.warn('This is a dummy for __enable');
},
};

window.guCmpHotFix = {
cmp: mockCmp,
};
window.guCmpHotFix.cmp = mockCmp;

jest.resetModules();
import('./index.ts').then((module) => {
expect(module.cmp).toEqual(mockCmp);

delete window.guCmpHotFix;
jest.resetModules();
import('./index.ts');
});
import('./index')
.then((module) => {
expect(module.cmp).toEqual(mockCmp);

window.guCmpHotFix = {};
jest.resetModules();
import('./index');
})
.catch((error) => {
console.error(error);
});
});
});
// *************** END commercial.dcr.js hotfix ***************
Expand All @@ -122,11 +144,18 @@ describe('cmp.willShowPrivacyMessage', () => {

const willShowPrivacyMessage2 = cmp.willShowPrivacyMessage();

cmp.willShowPrivacyMessage().then(() => {
expect(
Promise.all([willShowPrivacyMessage1, willShowPrivacyMessage2]),
).resolves.toEqual([true, true]);
});
cmp
.willShowPrivacyMessage()
.then(() => {
expect(Promise.all([willShowPrivacyMessage1, willShowPrivacyMessage2]))
.resolves.toEqual([true, true])
.catch((error) => {
console.error(error);
});
})
.catch((error) => {
console.error(error);
});
});
});

Expand All @@ -138,9 +167,14 @@ describe('cmp.willShowPrivacyMessageSync', () => {
it('does not throw if CMP is initialised', () => {
cmp.init({ country: 'GB' });

cmp.willShowPrivacyMessage().then(() => {
expect(() => cmp.willShowPrivacyMessageSync()).not.toThrow();
});
cmp
.willShowPrivacyMessage()
.then(() => {
expect(() => cmp.willShowPrivacyMessageSync()).not.toThrow();
})
.catch((error) => {
console.error(error);
});
});
});

Expand All @@ -152,39 +186,41 @@ describe('cmp.hasInitialised', () => {
it('returns true when CMP is initialised', () => {
cmp.init({ country: 'GB' });

cmp.willShowPrivacyMessage().then(() => {
expect(cmp.hasInitialised()).toBe(true);
});
cmp
.willShowPrivacyMessage()
.then(() => {
expect(cmp.hasInitialised()).toBe(true);
})
.catch((error) => {
console.error(error);
});
});
});

describe('cmp.showPrivacyManager', () => {
it('shows CMP privacy manager when in the US', () => {
it('shows CMP privacy manager when in the US', async () => {
cmp.init({ country: 'US' });

cmp.showPrivacyManager();
await resolveAllPromises();

return waitForExpect(() =>
expect(CMP.showPrivacyManager).toHaveBeenCalledTimes(1),
);
expect(CMP.showPrivacyManager).toHaveBeenCalledTimes(1);
});

it('shows CMP privacy manager when in Australia', () => {
it('shows CMP privacy manager when in Australia', async () => {
cmp.init({ country: 'AU' });

cmp.showPrivacyManager();
await resolveAllPromises();

return waitForExpect(() =>
expect(CMP.showPrivacyManager).toHaveBeenCalledTimes(1),
);
expect(CMP.showPrivacyManager).toHaveBeenCalledTimes(1);
});
it('shows TCF privacy manager when neither in the US or Australia', () => {
it('shows TCF privacy manager when neither in the US or Australia', async () => {
cmp.init({ country: 'GB' });

cmp.showPrivacyManager();
await resolveAllPromises();

return waitForExpect(() =>
expect(CMP.showPrivacyManager).toHaveBeenCalledTimes(1),
);
expect(CMP.showPrivacyManager).toHaveBeenCalledTimes(1);
});
});
15 changes: 9 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { CountryCode } from '@guardian/libs';
import { log } from '@guardian/libs';
import { version } from '../package.json';
import { CMP as UnifiedCMP } from './cmp';
import { disable, enable, isDisabled } from './disable';
import { getConsentFor as clientGetConsentFor } from './getConsentFor';
Expand All @@ -18,7 +20,7 @@ import { initVendorDataManager } from './vendorDataManager';
// Store some bits in the global scope for reuse, in case there's more
// than one instance of the CMP on the page in different scopes.
if (!isServerSide) {
window.guCmpHotFix ||= {};
if (typeof window.guCmpHotFix === 'undefined') window.guCmpHotFix = {};
}

let _willShowPrivacyMessage: undefined | boolean;
Expand All @@ -34,11 +36,12 @@ const init: InitCMP = ({ pubData, country }) => {
if (isDisabled() || isServerSide) return;

if (window.guCmpHotFix.initialised) {
if (window.guCmpHotFix.cmp?.version !== __PACKAGE_VERSION__)
if (window.guCmpHotFix.cmp?.version !== version) {
console.warn('Two different versions of the CMP are running:', [
__PACKAGE_VERSION__,
version,
window.guCmpHotFix.cmp?.version,
]);
}
return;
}

Expand All @@ -53,7 +56,7 @@ const init: InitCMP = ({ pubData, country }) => {
);
}

const framework = getFramework(country);
const framework = getFramework(country as CountryCode);

UnifiedCMP.init(framework, pubData ?? {});

Expand Down Expand Up @@ -94,13 +97,13 @@ export const cmp: CMP = isServerSide
willShowPrivacyMessageSync,
hasInitialised,
showPrivacyManager,
version: __PACKAGE_VERSION__,
version: version,

// special helper methods for disabling CMP
__isDisabled: isDisabled,
__enable: enable,
__disable: disable,
});
});

export const onConsent = isServerSide
? serverOnConsent
Expand Down

0 comments on commit e466472

Please sign in to comment.