@guardian/commercial-core 0.39.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,7 +19,9 @@ interface SlotEventStatus {
19
19
  }
20
20
  interface PageEventStatus {
21
21
  commercialStart: boolean;
22
- commercialEnd: boolean;
22
+ commercialExtraModulesLoaded: boolean;
23
+ commercialBaseModulesLoaded: boolean;
24
+ commercialModulesLoaded: boolean;
23
25
  }
24
26
  export declare class EventTimer {
25
27
  private _events;
@@ -29,7 +29,9 @@ class EventTimer {
29
29
  },
30
30
  page: {
31
31
  commercialStart: false,
32
- commercialEnd: false,
32
+ commercialExtraModulesLoaded: false,
33
+ commercialBaseModulesLoaded: false,
34
+ commercialModulesLoaded: false,
33
35
  },
34
36
  };
35
37
  this.gaConfig = {
@@ -45,7 +47,7 @@ class EventTimer {
45
47
  timingLabel: 'Commercial start parse time',
46
48
  },
47
49
  {
48
- timingVariable: 'commercialEnd',
50
+ timingVariable: 'commercialModulesLoaded',
49
51
  timingLabel: 'Commercial end parse time',
50
52
  },
51
53
  ],
@@ -5,7 +5,7 @@ export { twitter } from './third-party-tags/twitter-uwt';
5
5
  export { inizio } from './third-party-tags/inizio';
6
6
  export { remarketing } from './third-party-tags/remarketing';
7
7
  export { EventTimer } from './EventTimer';
8
- export { sendCommercialMetrics } from './sendCommercialMetrics';
8
+ export { bypassCommercialMetricsSampling, initCommercialMetrics, } from './sendCommercialMetrics';
9
9
  export type { ThirdPartyTag } from './types';
10
10
  export { adSizes, getAdSize } from './ad-sizes';
11
11
  export type { SizeKeys, AdSizeString, AdSize } from './ad-sizes';
@@ -14,3 +14,14 @@ export { clearPermutiveSegments, getPermutiveSegments, getPermutivePFPSegments,
14
14
  export { buildAdsConfigWithConsent, disabledAds } from './ad-targeting-youtube';
15
15
  export type { AdsConfig, AdsConfigBasic, AdsConfigDisabled, AdTargetingBuilder, CustomParams, } from './types';
16
16
  export * as constants from './constants';
17
+ export type { ContentTargeting } from './targeting/content';
18
+ export { getContentTargeting } from './targeting/content';
19
+ export type { PersonalisedTargeting } from './targeting/personalised';
20
+ export { getPersonalisedTargeting } from './targeting/personalised';
21
+ export type { SessionTargeting } from './targeting/session';
22
+ export { getSessionTargeting } from './targeting/session';
23
+ export type { SharedTargeting } from './targeting/shared';
24
+ export { getSharedTargeting } from './targeting/shared';
25
+ export type { ViewportTargeting } from './targeting/viewport';
26
+ export { getViewportTargeting } from './targeting/viewport';
27
+ export { pickTargetingValues } from './targeting/pick-targeting-values';
package/dist/cjs/index.js CHANGED
@@ -20,7 +20,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
20
20
  return result;
21
21
  };
22
22
  Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.constants = exports.disabledAds = exports.buildAdsConfigWithConsent = exports.getPermutivePFPSegments = exports.getPermutiveSegments = exports.clearPermutiveSegments = exports.isAdBlockInUse = exports.getAdSize = exports.adSizes = exports.sendCommercialMetrics = exports.EventTimer = exports.remarketing = exports.inizio = exports.twitter = exports.fbPixel = exports.permutive = exports.ias = void 0;
23
+ exports.pickTargetingValues = exports.getViewportTargeting = exports.getSharedTargeting = exports.getSessionTargeting = exports.getPersonalisedTargeting = exports.getContentTargeting = exports.constants = exports.disabledAds = exports.buildAdsConfigWithConsent = exports.getPermutivePFPSegments = exports.getPermutiveSegments = exports.clearPermutiveSegments = exports.isAdBlockInUse = exports.getAdSize = exports.adSizes = exports.initCommercialMetrics = exports.bypassCommercialMetricsSampling = exports.EventTimer = exports.remarketing = exports.inizio = exports.twitter = exports.fbPixel = exports.permutive = exports.ias = void 0;
24
24
  var ias_1 = require("./third-party-tags/ias");
25
25
  Object.defineProperty(exports, "ias", { enumerable: true, get: function () { return ias_1.ias; } });
26
26
  var permutive_1 = require("./third-party-tags/permutive");
@@ -36,7 +36,8 @@ Object.defineProperty(exports, "remarketing", { enumerable: true, get: function
36
36
  var EventTimer_1 = require("./EventTimer");
37
37
  Object.defineProperty(exports, "EventTimer", { enumerable: true, get: function () { return EventTimer_1.EventTimer; } });
38
38
  var sendCommercialMetrics_1 = require("./sendCommercialMetrics");
39
- Object.defineProperty(exports, "sendCommercialMetrics", { enumerable: true, get: function () { return sendCommercialMetrics_1.sendCommercialMetrics; } });
39
+ Object.defineProperty(exports, "bypassCommercialMetricsSampling", { enumerable: true, get: function () { return sendCommercialMetrics_1.bypassCommercialMetricsSampling; } });
40
+ Object.defineProperty(exports, "initCommercialMetrics", { enumerable: true, get: function () { return sendCommercialMetrics_1.initCommercialMetrics; } });
40
41
  var ad_sizes_1 = require("./ad-sizes");
41
42
  Object.defineProperty(exports, "adSizes", { enumerable: true, get: function () { return ad_sizes_1.adSizes; } });
42
43
  Object.defineProperty(exports, "getAdSize", { enumerable: true, get: function () { return ad_sizes_1.getAdSize; } });
@@ -50,3 +51,15 @@ var ad_targeting_youtube_1 = require("./ad-targeting-youtube");
50
51
  Object.defineProperty(exports, "buildAdsConfigWithConsent", { enumerable: true, get: function () { return ad_targeting_youtube_1.buildAdsConfigWithConsent; } });
51
52
  Object.defineProperty(exports, "disabledAds", { enumerable: true, get: function () { return ad_targeting_youtube_1.disabledAds; } });
52
53
  exports.constants = __importStar(require("./constants"));
54
+ var content_1 = require("./targeting/content");
55
+ Object.defineProperty(exports, "getContentTargeting", { enumerable: true, get: function () { return content_1.getContentTargeting; } });
56
+ var personalised_1 = require("./targeting/personalised");
57
+ Object.defineProperty(exports, "getPersonalisedTargeting", { enumerable: true, get: function () { return personalised_1.getPersonalisedTargeting; } });
58
+ var session_1 = require("./targeting/session");
59
+ Object.defineProperty(exports, "getSessionTargeting", { enumerable: true, get: function () { return session_1.getSessionTargeting; } });
60
+ var shared_1 = require("./targeting/shared");
61
+ Object.defineProperty(exports, "getSharedTargeting", { enumerable: true, get: function () { return shared_1.getSharedTargeting; } });
62
+ var viewport_1 = require("./targeting/viewport");
63
+ Object.defineProperty(exports, "getViewportTargeting", { enumerable: true, get: function () { return viewport_1.getViewportTargeting; } });
64
+ var pick_targeting_values_1 = require("./targeting/pick-targeting-values");
65
+ Object.defineProperty(exports, "pickTargetingValues", { enumerable: true, get: function () { return pick_targeting_values_1.pickTargetingValues; } });
@@ -1 +1,55 @@
1
- export declare function sendCommercialMetrics(pageViewId: string, browserId: string | undefined, isDev: boolean, adBlockerInUse?: boolean): boolean;
1
+ declare type Metric = {
2
+ name: string;
3
+ value: number;
4
+ };
5
+ declare type Property = {
6
+ name: string;
7
+ value: string;
8
+ };
9
+ declare type TimedEvent = {
10
+ name: string;
11
+ ts: number;
12
+ };
13
+ declare type EventProperties = {
14
+ type?: ConnectionType;
15
+ downlink?: number;
16
+ effectiveType?: string;
17
+ };
18
+ declare enum Endpoints {
19
+ CODE = "//performance-events.code.dev-guardianapis.com/commercial-metrics",
20
+ PROD = "//performance-events.guardianapis.com/commercial-metrics"
21
+ }
22
+ /**
23
+ * A method to asynchronously send metrics after initialization.
24
+ */
25
+ export declare function bypassCommercialMetricsSampling(): void;
26
+ interface InitCommercialMetricsArgs {
27
+ pageViewId: string;
28
+ browserId: string | undefined;
29
+ isDev: boolean;
30
+ adBlockerInUse?: boolean;
31
+ adSlotsInline?: number;
32
+ adSlotsTotal?: number;
33
+ sampling?: number;
34
+ }
35
+ /**
36
+ * A method to initialise metrics.
37
+ * @param init.pageViewId - identifies the page view. Usually available on `guardian.config.ophan.pageViewId`. Defaults to `null`
38
+ * @param init.browserId - identifies the browser. Usually available via `getCookie({ name: 'bwid' })`. Defaults to `null`
39
+ * @param init.isDev - used to determine whether to use CODE or PROD endpoints.
40
+ * @param init.adBlockerInUse - indicates whether or not an adblocker is being used.
41
+ * @param init.adSlotsInline - the number of inline ad slots on the page
42
+ * @param init.adSlotsTotal - the total number of ad slots on the page
43
+ * @param init.sampling - rate at which to sample commercial metrics - the default is to send for 1% of pageviews
44
+ */
45
+ export declare function initCommercialMetrics({ pageViewId, browserId, isDev, adBlockerInUse, adSlotsInline, adSlotsTotal, sampling, }: InitCommercialMetricsArgs): boolean;
46
+ export declare const _: {
47
+ Endpoints: typeof Endpoints;
48
+ setEndpoint: (isDev: boolean) => Endpoints;
49
+ filterUndefinedProperties: <T>(transformedProperties: [string, T | undefined][]) => [string, T][];
50
+ mapEventTimerPropertiesToString: (properties: Array<[string, string | number]>) => Property[];
51
+ roundTimeStamp: (events: TimedEvent[]) => Metric[];
52
+ transformToObjectEntries: (eventTimerProperties: EventProperties) => Array<[string, string | number | undefined]>;
53
+ reset: () => void;
54
+ };
55
+ export type { Property, TimedEvent, Metric };
@@ -1,44 +1,175 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.sendCommercialMetrics = void 0;
3
+ exports._ = exports.initCommercialMetrics = exports.bypassCommercialMetricsSampling = void 0;
4
4
  const libs_1 = require("@guardian/libs");
5
5
  const EventTimer_1 = require("./EventTimer");
6
- function sendCommercialMetrics(pageViewId, browserId, isDev, adBlockerInUse) {
7
- const devProperties = isDev
8
- ? [{ name: 'isDev', value: window.location.hostname }]
6
+ var Endpoints;
7
+ (function (Endpoints) {
8
+ Endpoints["CODE"] = "//performance-events.code.dev-guardianapis.com/commercial-metrics";
9
+ Endpoints["PROD"] = "//performance-events.guardianapis.com/commercial-metrics";
10
+ })(Endpoints || (Endpoints = {}));
11
+ let commercialMetricsPayload = {
12
+ page_view_id: undefined,
13
+ browser_id: undefined,
14
+ platform: 'NEXT_GEN',
15
+ metrics: [],
16
+ properties: [],
17
+ };
18
+ let devProperties = [];
19
+ let adBlockerProperties = [];
20
+ let adSlotProperties = [];
21
+ let initialised = false;
22
+ let endpoint;
23
+ const setEndpoint = (isDev) => (endpoint = isDev ? Endpoints.CODE : Endpoints.PROD);
24
+ const setDevProperties = (isDev) => (devProperties = isDev
25
+ ? [{ name: 'isDev', value: window.location.hostname }]
26
+ : []);
27
+ const setAdBlockerProperties = (adBlockerInUse) => {
28
+ adBlockerProperties =
29
+ adBlockerInUse !== undefined
30
+ ? [
31
+ {
32
+ name: 'adBlockerInUse',
33
+ value: adBlockerInUse.toString(),
34
+ },
35
+ ]
36
+ : [];
37
+ };
38
+ const setAdSlotProperties = (adSlotsInline, adSlotsTotal) => {
39
+ const adSlotsInlineProperties = adSlotsInline !== undefined
40
+ ? [
41
+ {
42
+ name: 'adSlotsInline',
43
+ value: adSlotsInline.toString(),
44
+ },
45
+ ]
9
46
  : [];
10
- const adBlockerProperties = adBlockerInUse !== undefined
47
+ const adSlotsTotalProperties = adSlotsTotal !== undefined
11
48
  ? [
12
49
  {
13
- name: 'adBlockerInUse',
14
- value: adBlockerInUse.toString(),
50
+ name: 'adSlotsTotal',
51
+ value: adSlotsTotal.toString(),
15
52
  },
16
53
  ]
17
54
  : [];
18
- const endpoint = isDev
19
- ? '//performance-events.code.dev-guardianapis.com/commercial-metrics'
20
- : '//performance-events.guardianapis.com/commercial-metrics';
21
- if (document.visibilityState !== 'hidden')
22
- return false;
23
- const eventTimer = EventTimer_1.EventTimer.get();
24
- const events = eventTimer.events;
25
- const properties = Object.entries(eventTimer.properties)
26
- .filter(([, value]) => typeof value !== 'undefined')
27
- .map(([name, value]) => ({ name, value: String(value) }))
28
- .concat(devProperties)
29
- .concat(adBlockerProperties);
30
- const metrics = events.map(({ name, ts }) => ({
55
+ adSlotProperties = adSlotsInlineProperties.concat(adSlotsTotalProperties);
56
+ };
57
+ const transformToObjectEntries = (eventTimerProperties) => {
58
+ // Transforms object {key: value} pairs into an array of [key, value] arrays
59
+ return Object.entries(eventTimerProperties);
60
+ };
61
+ const filterUndefinedProperties = (transformedProperties) => transformedProperties.reduce((acc, [key, value]) => {
62
+ if (typeof value !== 'undefined') {
63
+ acc.push([key, value]);
64
+ }
65
+ return acc;
66
+ }, []);
67
+ const mapEventTimerPropertiesToString = (properties) => {
68
+ return properties.map(([name, value]) => ({
69
+ name: String(name),
70
+ value: String(value),
71
+ }));
72
+ };
73
+ const roundTimeStamp = (events) => {
74
+ return events.map(({ name, ts }) => ({
31
75
  name,
32
76
  value: Math.ceil(ts),
33
77
  }));
34
- const commercialMetrics = {
35
- browser_id: browserId,
36
- page_view_id: pageViewId,
37
- platform: 'NEXT_GEN',
38
- metrics,
39
- properties,
40
- };
41
- (0, libs_1.log)('commercial', 'About to send commercial metrics', commercialMetrics);
42
- return navigator.sendBeacon(endpoint, JSON.stringify(commercialMetrics));
78
+ };
79
+ function sendMetrics() {
80
+ (0, libs_1.log)('commercial', 'About to send commercial metrics', commercialMetricsPayload);
81
+ return navigator.sendBeacon(endpoint, JSON.stringify(commercialMetricsPayload));
82
+ }
83
+ function gatherMetricsOnPageUnload() {
84
+ // Assemble commercial properties and metrics
85
+ const eventTimer = EventTimer_1.EventTimer.get();
86
+ const transformedEntries = transformToObjectEntries(eventTimer.properties);
87
+ const filteredEventTimerProperties = filterUndefinedProperties(transformedEntries);
88
+ const mappedEventTimerProperties = mapEventTimerPropertiesToString(filteredEventTimerProperties);
89
+ const properties = mappedEventTimerProperties
90
+ .concat(devProperties)
91
+ .concat(adBlockerProperties)
92
+ .concat(adSlotProperties);
93
+ commercialMetricsPayload.properties = properties;
94
+ const metrics = roundTimeStamp(eventTimer.events);
95
+ commercialMetricsPayload.metrics = metrics;
96
+ sendMetrics();
97
+ }
98
+ const listener = (e) => {
99
+ switch (e.type) {
100
+ case 'visibilitychange':
101
+ if (document.visibilityState === 'hidden') {
102
+ gatherMetricsOnPageUnload();
103
+ }
104
+ return;
105
+ case 'pagehide':
106
+ gatherMetricsOnPageUnload();
107
+ return;
108
+ }
109
+ };
110
+ const addVisibilityListeners = () => {
111
+ // Report all available metrics when the page is unloaded or in background.
112
+ window.addEventListener('visibilitychange', listener);
113
+ // Safari does not reliably fire the `visibilitychange` on page unload.
114
+ window.addEventListener('pagehide', listener);
115
+ };
116
+ /**
117
+ * A method to asynchronously send metrics after initialization.
118
+ */
119
+ function bypassCommercialMetricsSampling() {
120
+ if (!initialised) {
121
+ console.warn('initCommercialMetrics not yet initialised');
122
+ return;
123
+ }
124
+ addVisibilityListeners();
125
+ }
126
+ exports.bypassCommercialMetricsSampling = bypassCommercialMetricsSampling;
127
+ /**
128
+ * A method to initialise metrics.
129
+ * @param init.pageViewId - identifies the page view. Usually available on `guardian.config.ophan.pageViewId`. Defaults to `null`
130
+ * @param init.browserId - identifies the browser. Usually available via `getCookie({ name: 'bwid' })`. Defaults to `null`
131
+ * @param init.isDev - used to determine whether to use CODE or PROD endpoints.
132
+ * @param init.adBlockerInUse - indicates whether or not an adblocker is being used.
133
+ * @param init.adSlotsInline - the number of inline ad slots on the page
134
+ * @param init.adSlotsTotal - the total number of ad slots on the page
135
+ * @param init.sampling - rate at which to sample commercial metrics - the default is to send for 1% of pageviews
136
+ */
137
+ function initCommercialMetrics({ pageViewId, browserId, isDev, adBlockerInUse, adSlotsInline, adSlotsTotal, sampling = 1 / 100, }) {
138
+ commercialMetricsPayload.page_view_id = pageViewId;
139
+ commercialMetricsPayload.browser_id = browserId;
140
+ setEndpoint(isDev);
141
+ setDevProperties(isDev);
142
+ setAdBlockerProperties(adBlockerInUse);
143
+ setAdSlotProperties(adSlotsInline, adSlotsTotal);
144
+ if (initialised) {
145
+ return false;
146
+ }
147
+ initialised = true;
148
+ const userIsInSamplingGroup = Math.random() <= sampling;
149
+ if (isDev || userIsInSamplingGroup) {
150
+ addVisibilityListeners();
151
+ return true;
152
+ }
153
+ return false;
43
154
  }
44
- exports.sendCommercialMetrics = sendCommercialMetrics;
155
+ exports.initCommercialMetrics = initCommercialMetrics;
156
+ exports._ = {
157
+ Endpoints,
158
+ setEndpoint,
159
+ filterUndefinedProperties,
160
+ mapEventTimerPropertiesToString,
161
+ roundTimeStamp,
162
+ transformToObjectEntries,
163
+ reset: () => {
164
+ initialised = false;
165
+ commercialMetricsPayload = {
166
+ page_view_id: undefined,
167
+ browser_id: undefined,
168
+ platform: 'NEXT_GEN',
169
+ metrics: [],
170
+ properties: [],
171
+ };
172
+ removeEventListener('visibilitychange', listener);
173
+ removeEventListener('pagehide', listener);
174
+ },
175
+ };
@@ -39,4 +39,9 @@ export declare type ViewportTargeting = {
39
39
  */
40
40
  skinsize: 'l' | 's';
41
41
  };
42
- export declare const getViewportTargeting: (viewPortWidth: number, cmpBannerWillShow: boolean) => ViewportTargeting;
42
+ declare type Viewport = {
43
+ viewPortWidth: number;
44
+ cmpBannerWillShow: boolean;
45
+ };
46
+ export declare const getViewportTargeting: ({ viewPortWidth, cmpBannerWillShow, }: Viewport) => ViewportTargeting;
47
+ export {};
@@ -9,8 +9,7 @@ const findBreakpoint = (width) => {
9
9
  return 'tablet';
10
10
  return 'mobile';
11
11
  };
12
- /* -- Targeting -- */
13
- const getViewportTargeting = (viewPortWidth, cmpBannerWillShow) => {
12
+ const getViewportTargeting = ({ viewPortWidth, cmpBannerWillShow, }) => {
14
13
  // Don’t show inskin if if a privacy message will be shown
15
14
  const inskin = cmpBannerWillShow ? 'f' : 't';
16
15
  return {
@@ -19,7 +19,9 @@ interface SlotEventStatus {
19
19
  }
20
20
  interface PageEventStatus {
21
21
  commercialStart: boolean;
22
- commercialEnd: boolean;
22
+ commercialExtraModulesLoaded: boolean;
23
+ commercialBaseModulesLoaded: boolean;
24
+ commercialModulesLoaded: boolean;
23
25
  }
24
26
  export declare class EventTimer {
25
27
  private _events;
@@ -26,7 +26,9 @@ export class EventTimer {
26
26
  },
27
27
  page: {
28
28
  commercialStart: false,
29
- commercialEnd: false,
29
+ commercialExtraModulesLoaded: false,
30
+ commercialBaseModulesLoaded: false,
31
+ commercialModulesLoaded: false,
30
32
  },
31
33
  };
32
34
  this.gaConfig = {
@@ -42,7 +44,7 @@ export class EventTimer {
42
44
  timingLabel: 'Commercial start parse time',
43
45
  },
44
46
  {
45
- timingVariable: 'commercialEnd',
47
+ timingVariable: 'commercialModulesLoaded',
46
48
  timingLabel: 'Commercial end parse time',
47
49
  },
48
50
  ],
@@ -5,7 +5,7 @@ export { twitter } from './third-party-tags/twitter-uwt';
5
5
  export { inizio } from './third-party-tags/inizio';
6
6
  export { remarketing } from './third-party-tags/remarketing';
7
7
  export { EventTimer } from './EventTimer';
8
- export { sendCommercialMetrics } from './sendCommercialMetrics';
8
+ export { bypassCommercialMetricsSampling, initCommercialMetrics, } from './sendCommercialMetrics';
9
9
  export type { ThirdPartyTag } from './types';
10
10
  export { adSizes, getAdSize } from './ad-sizes';
11
11
  export type { SizeKeys, AdSizeString, AdSize } from './ad-sizes';
@@ -14,3 +14,14 @@ export { clearPermutiveSegments, getPermutiveSegments, getPermutivePFPSegments,
14
14
  export { buildAdsConfigWithConsent, disabledAds } from './ad-targeting-youtube';
15
15
  export type { AdsConfig, AdsConfigBasic, AdsConfigDisabled, AdTargetingBuilder, CustomParams, } from './types';
16
16
  export * as constants from './constants';
17
+ export type { ContentTargeting } from './targeting/content';
18
+ export { getContentTargeting } from './targeting/content';
19
+ export type { PersonalisedTargeting } from './targeting/personalised';
20
+ export { getPersonalisedTargeting } from './targeting/personalised';
21
+ export type { SessionTargeting } from './targeting/session';
22
+ export { getSessionTargeting } from './targeting/session';
23
+ export type { SharedTargeting } from './targeting/shared';
24
+ export { getSharedTargeting } from './targeting/shared';
25
+ export type { ViewportTargeting } from './targeting/viewport';
26
+ export { getViewportTargeting } from './targeting/viewport';
27
+ export { pickTargetingValues } from './targeting/pick-targeting-values';
package/dist/esm/index.js CHANGED
@@ -6,10 +6,16 @@ export { twitter } from './third-party-tags/twitter-uwt';
6
6
  export { inizio } from './third-party-tags/inizio';
7
7
  export { remarketing } from './third-party-tags/remarketing';
8
8
  export { EventTimer } from './EventTimer';
9
- export { sendCommercialMetrics } from './sendCommercialMetrics';
9
+ export { bypassCommercialMetricsSampling, initCommercialMetrics, } from './sendCommercialMetrics';
10
10
  export { adSizes, getAdSize } from './ad-sizes';
11
11
  export { isAdBlockInUse } from './detectAdBlocker';
12
12
  export { clearPermutiveSegments, getPermutiveSegments, getPermutivePFPSegments, } from './permutive';
13
13
  export { buildAdsConfigWithConsent, disabledAds } from './ad-targeting-youtube';
14
14
  import * as constants_1 from './constants';
15
15
  export { constants_1 as constants };
16
+ export { getContentTargeting } from './targeting/content';
17
+ export { getPersonalisedTargeting } from './targeting/personalised';
18
+ export { getSessionTargeting } from './targeting/session';
19
+ export { getSharedTargeting } from './targeting/shared';
20
+ export { getViewportTargeting } from './targeting/viewport';
21
+ export { pickTargetingValues } from './targeting/pick-targeting-values';
@@ -1 +1,55 @@
1
- export declare function sendCommercialMetrics(pageViewId: string, browserId: string | undefined, isDev: boolean, adBlockerInUse?: boolean): boolean;
1
+ declare type Metric = {
2
+ name: string;
3
+ value: number;
4
+ };
5
+ declare type Property = {
6
+ name: string;
7
+ value: string;
8
+ };
9
+ declare type TimedEvent = {
10
+ name: string;
11
+ ts: number;
12
+ };
13
+ declare type EventProperties = {
14
+ type?: ConnectionType;
15
+ downlink?: number;
16
+ effectiveType?: string;
17
+ };
18
+ declare enum Endpoints {
19
+ CODE = "//performance-events.code.dev-guardianapis.com/commercial-metrics",
20
+ PROD = "//performance-events.guardianapis.com/commercial-metrics"
21
+ }
22
+ /**
23
+ * A method to asynchronously send metrics after initialization.
24
+ */
25
+ export declare function bypassCommercialMetricsSampling(): void;
26
+ interface InitCommercialMetricsArgs {
27
+ pageViewId: string;
28
+ browserId: string | undefined;
29
+ isDev: boolean;
30
+ adBlockerInUse?: boolean;
31
+ adSlotsInline?: number;
32
+ adSlotsTotal?: number;
33
+ sampling?: number;
34
+ }
35
+ /**
36
+ * A method to initialise metrics.
37
+ * @param init.pageViewId - identifies the page view. Usually available on `guardian.config.ophan.pageViewId`. Defaults to `null`
38
+ * @param init.browserId - identifies the browser. Usually available via `getCookie({ name: 'bwid' })`. Defaults to `null`
39
+ * @param init.isDev - used to determine whether to use CODE or PROD endpoints.
40
+ * @param init.adBlockerInUse - indicates whether or not an adblocker is being used.
41
+ * @param init.adSlotsInline - the number of inline ad slots on the page
42
+ * @param init.adSlotsTotal - the total number of ad slots on the page
43
+ * @param init.sampling - rate at which to sample commercial metrics - the default is to send for 1% of pageviews
44
+ */
45
+ export declare function initCommercialMetrics({ pageViewId, browserId, isDev, adBlockerInUse, adSlotsInline, adSlotsTotal, sampling, }: InitCommercialMetricsArgs): boolean;
46
+ export declare const _: {
47
+ Endpoints: typeof Endpoints;
48
+ setEndpoint: (isDev: boolean) => Endpoints;
49
+ filterUndefinedProperties: <T>(transformedProperties: [string, T | undefined][]) => [string, T][];
50
+ mapEventTimerPropertiesToString: (properties: Array<[string, string | number]>) => Property[];
51
+ roundTimeStamp: (events: TimedEvent[]) => Metric[];
52
+ transformToObjectEntries: (eventTimerProperties: EventProperties) => Array<[string, string | number | undefined]>;
53
+ reset: () => void;
54
+ };
55
+ export type { Property, TimedEvent, Metric };
@@ -1,40 +1,170 @@
1
1
  import { log } from '@guardian/libs';
2
2
  import { EventTimer } from './EventTimer';
3
- export function sendCommercialMetrics(pageViewId, browserId, isDev, adBlockerInUse) {
4
- const devProperties = isDev
5
- ? [{ name: 'isDev', value: window.location.hostname }]
3
+ var Endpoints;
4
+ (function (Endpoints) {
5
+ Endpoints["CODE"] = "//performance-events.code.dev-guardianapis.com/commercial-metrics";
6
+ Endpoints["PROD"] = "//performance-events.guardianapis.com/commercial-metrics";
7
+ })(Endpoints || (Endpoints = {}));
8
+ let commercialMetricsPayload = {
9
+ page_view_id: undefined,
10
+ browser_id: undefined,
11
+ platform: 'NEXT_GEN',
12
+ metrics: [],
13
+ properties: [],
14
+ };
15
+ let devProperties = [];
16
+ let adBlockerProperties = [];
17
+ let adSlotProperties = [];
18
+ let initialised = false;
19
+ let endpoint;
20
+ const setEndpoint = (isDev) => (endpoint = isDev ? Endpoints.CODE : Endpoints.PROD);
21
+ const setDevProperties = (isDev) => (devProperties = isDev
22
+ ? [{ name: 'isDev', value: window.location.hostname }]
23
+ : []);
24
+ const setAdBlockerProperties = (adBlockerInUse) => {
25
+ adBlockerProperties =
26
+ adBlockerInUse !== undefined
27
+ ? [
28
+ {
29
+ name: 'adBlockerInUse',
30
+ value: adBlockerInUse.toString(),
31
+ },
32
+ ]
33
+ : [];
34
+ };
35
+ const setAdSlotProperties = (adSlotsInline, adSlotsTotal) => {
36
+ const adSlotsInlineProperties = adSlotsInline !== undefined
37
+ ? [
38
+ {
39
+ name: 'adSlotsInline',
40
+ value: adSlotsInline.toString(),
41
+ },
42
+ ]
6
43
  : [];
7
- const adBlockerProperties = adBlockerInUse !== undefined
44
+ const adSlotsTotalProperties = adSlotsTotal !== undefined
8
45
  ? [
9
46
  {
10
- name: 'adBlockerInUse',
11
- value: adBlockerInUse.toString(),
47
+ name: 'adSlotsTotal',
48
+ value: adSlotsTotal.toString(),
12
49
  },
13
50
  ]
14
51
  : [];
15
- const endpoint = isDev
16
- ? '//performance-events.code.dev-guardianapis.com/commercial-metrics'
17
- : '//performance-events.guardianapis.com/commercial-metrics';
18
- if (document.visibilityState !== 'hidden')
19
- return false;
20
- const eventTimer = EventTimer.get();
21
- const events = eventTimer.events;
22
- const properties = Object.entries(eventTimer.properties)
23
- .filter(([, value]) => typeof value !== 'undefined')
24
- .map(([name, value]) => ({ name, value: String(value) }))
25
- .concat(devProperties)
26
- .concat(adBlockerProperties);
27
- const metrics = events.map(({ name, ts }) => ({
52
+ adSlotProperties = adSlotsInlineProperties.concat(adSlotsTotalProperties);
53
+ };
54
+ const transformToObjectEntries = (eventTimerProperties) => {
55
+ // Transforms object {key: value} pairs into an array of [key, value] arrays
56
+ return Object.entries(eventTimerProperties);
57
+ };
58
+ const filterUndefinedProperties = (transformedProperties) => transformedProperties.reduce((acc, [key, value]) => {
59
+ if (typeof value !== 'undefined') {
60
+ acc.push([key, value]);
61
+ }
62
+ return acc;
63
+ }, []);
64
+ const mapEventTimerPropertiesToString = (properties) => {
65
+ return properties.map(([name, value]) => ({
66
+ name: String(name),
67
+ value: String(value),
68
+ }));
69
+ };
70
+ const roundTimeStamp = (events) => {
71
+ return events.map(({ name, ts }) => ({
28
72
  name,
29
73
  value: Math.ceil(ts),
30
74
  }));
31
- const commercialMetrics = {
32
- browser_id: browserId,
33
- page_view_id: pageViewId,
34
- platform: 'NEXT_GEN',
35
- metrics,
36
- properties,
37
- };
38
- log('commercial', 'About to send commercial metrics', commercialMetrics);
39
- return navigator.sendBeacon(endpoint, JSON.stringify(commercialMetrics));
75
+ };
76
+ function sendMetrics() {
77
+ log('commercial', 'About to send commercial metrics', commercialMetricsPayload);
78
+ return navigator.sendBeacon(endpoint, JSON.stringify(commercialMetricsPayload));
79
+ }
80
+ function gatherMetricsOnPageUnload() {
81
+ // Assemble commercial properties and metrics
82
+ const eventTimer = EventTimer.get();
83
+ const transformedEntries = transformToObjectEntries(eventTimer.properties);
84
+ const filteredEventTimerProperties = filterUndefinedProperties(transformedEntries);
85
+ const mappedEventTimerProperties = mapEventTimerPropertiesToString(filteredEventTimerProperties);
86
+ const properties = mappedEventTimerProperties
87
+ .concat(devProperties)
88
+ .concat(adBlockerProperties)
89
+ .concat(adSlotProperties);
90
+ commercialMetricsPayload.properties = properties;
91
+ const metrics = roundTimeStamp(eventTimer.events);
92
+ commercialMetricsPayload.metrics = metrics;
93
+ sendMetrics();
94
+ }
95
+ const listener = (e) => {
96
+ switch (e.type) {
97
+ case 'visibilitychange':
98
+ if (document.visibilityState === 'hidden') {
99
+ gatherMetricsOnPageUnload();
100
+ }
101
+ return;
102
+ case 'pagehide':
103
+ gatherMetricsOnPageUnload();
104
+ return;
105
+ }
106
+ };
107
+ const addVisibilityListeners = () => {
108
+ // Report all available metrics when the page is unloaded or in background.
109
+ window.addEventListener('visibilitychange', listener);
110
+ // Safari does not reliably fire the `visibilitychange` on page unload.
111
+ window.addEventListener('pagehide', listener);
112
+ };
113
+ /**
114
+ * A method to asynchronously send metrics after initialization.
115
+ */
116
+ export function bypassCommercialMetricsSampling() {
117
+ if (!initialised) {
118
+ console.warn('initCommercialMetrics not yet initialised');
119
+ return;
120
+ }
121
+ addVisibilityListeners();
122
+ }
123
+ /**
124
+ * A method to initialise metrics.
125
+ * @param init.pageViewId - identifies the page view. Usually available on `guardian.config.ophan.pageViewId`. Defaults to `null`
126
+ * @param init.browserId - identifies the browser. Usually available via `getCookie({ name: 'bwid' })`. Defaults to `null`
127
+ * @param init.isDev - used to determine whether to use CODE or PROD endpoints.
128
+ * @param init.adBlockerInUse - indicates whether or not an adblocker is being used.
129
+ * @param init.adSlotsInline - the number of inline ad slots on the page
130
+ * @param init.adSlotsTotal - the total number of ad slots on the page
131
+ * @param init.sampling - rate at which to sample commercial metrics - the default is to send for 1% of pageviews
132
+ */
133
+ export function initCommercialMetrics({ pageViewId, browserId, isDev, adBlockerInUse, adSlotsInline, adSlotsTotal, sampling = 1 / 100, }) {
134
+ commercialMetricsPayload.page_view_id = pageViewId;
135
+ commercialMetricsPayload.browser_id = browserId;
136
+ setEndpoint(isDev);
137
+ setDevProperties(isDev);
138
+ setAdBlockerProperties(adBlockerInUse);
139
+ setAdSlotProperties(adSlotsInline, adSlotsTotal);
140
+ if (initialised) {
141
+ return false;
142
+ }
143
+ initialised = true;
144
+ const userIsInSamplingGroup = Math.random() <= sampling;
145
+ if (isDev || userIsInSamplingGroup) {
146
+ addVisibilityListeners();
147
+ return true;
148
+ }
149
+ return false;
40
150
  }
151
+ export const _ = {
152
+ Endpoints,
153
+ setEndpoint,
154
+ filterUndefinedProperties,
155
+ mapEventTimerPropertiesToString,
156
+ roundTimeStamp,
157
+ transformToObjectEntries,
158
+ reset: () => {
159
+ initialised = false;
160
+ commercialMetricsPayload = {
161
+ page_view_id: undefined,
162
+ browser_id: undefined,
163
+ platform: 'NEXT_GEN',
164
+ metrics: [],
165
+ properties: [],
166
+ };
167
+ removeEventListener('visibilitychange', listener);
168
+ removeEventListener('pagehide', listener);
169
+ },
170
+ };
@@ -39,4 +39,9 @@ export declare type ViewportTargeting = {
39
39
  */
40
40
  skinsize: 'l' | 's';
41
41
  };
42
- export declare const getViewportTargeting: (viewPortWidth: number, cmpBannerWillShow: boolean) => ViewportTargeting;
42
+ declare type Viewport = {
43
+ viewPortWidth: number;
44
+ cmpBannerWillShow: boolean;
45
+ };
46
+ export declare const getViewportTargeting: ({ viewPortWidth, cmpBannerWillShow, }: Viewport) => ViewportTargeting;
47
+ export {};
@@ -6,8 +6,7 @@ const findBreakpoint = (width) => {
6
6
  return 'tablet';
7
7
  return 'mobile';
8
8
  };
9
- /* -- Targeting -- */
10
- export const getViewportTargeting = (viewPortWidth, cmpBannerWillShow) => {
9
+ export const getViewportTargeting = ({ viewPortWidth, cmpBannerWillShow, }) => {
11
10
  // Don’t show inskin if if a privacy message will be shown
12
11
  const inskin = cmpBannerWillShow ? 'f' : 't';
13
12
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guardian/commercial-core",
3
- "version": "0.39.1",
3
+ "version": "2.0.0",
4
4
  "description": "Guardian advertising business logic",
5
5
  "homepage": "https://github.com/guardian/commercial-core#readme",
6
6
  "bugs": {
@@ -26,6 +26,7 @@
26
26
  "precommit:lint": "lint-staged",
27
27
  "prepush:test": "jest --verbose --runInBand --onlyChanged",
28
28
  "test": "jest",
29
+ "test:watch": "jest --watch",
29
30
  "test:ci": "jest --coverage --ci",
30
31
  "tsc": "tsc --noEmit",
31
32
  "validate": "npm-run-all tsc lint test build",
@@ -45,7 +46,7 @@
45
46
  "@commitlint/config-conventional": "^16.0.0",
46
47
  "@guardian/ab-core": "^2.0.0",
47
48
  "@guardian/consent-management-platform": "^10.1.0",
48
- "@guardian/eslint-config-typescript": "^0.7.0",
49
+ "@guardian/eslint-config-typescript": "^1.0.0",
49
50
  "@guardian/libs": "3.6.1",
50
51
  "@guardian/prettier": "^0.7.0",
51
52
  "@octokit/core": "^3.5.1",