forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubxaiAnalyticsAdapter.js
354 lines (335 loc) · 11 KB
/
pubxaiAnalyticsAdapter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import adapter from '../libraries/analyticsAdapter/AnalyticsAdapter.js';
import {
getGptSlotInfoForAdUnitCode, getGptSlotForAdUnitCode
} from '../libraries/gptUtils/gptUtils.js';
import { getDeviceType, getBrowser, getOS } from '../libraries/userAgentUtils/index.js';
import { MODULE_TYPE_ANALYTICS } from '../src/activities/modules.js';
import adapterManager from '../src/adapterManager.js';
import { sendBeacon } from '../src/ajax.js'
import { EVENTS } from '../src/constants.js';
import { getGlobal } from '../src/prebidGlobal.js';
import { getStorageManager } from '../src/storageManager.js';
import {
deepAccess, parseSizesInput, getWindowLocation, buildUrl, cyrb53Hash
} from '../src/utils.js';
let initOptions;
const emptyUrl = '';
const analyticsType = 'endpoint';
const adapterCode = 'pubxai';
const pubxaiAnalyticsVersion = 'v2.1.0';
const defaultHost = 'api.pbxai.com';
const auctionPath = '/analytics/auction';
const winningBidPath = '/analytics/bidwon';
const storage = getStorageManager({ moduleType: MODULE_TYPE_ANALYTICS, moduleName: adapterCode })
/**
* The sendCache is a global cache object which tracks the pending sends
* back to pubx.ai. The data may be removed from this cache, post send.
*/
export const sendCache = new Proxy(
{},
{
get: (target, name) => {
if (!target.hasOwnProperty(name)) {
target[name] = [];
}
return target[name];
},
}
);
/**
* auctionCache is a global cache object which stores all auction histories
* for the session. When getting a key from the auction cache, any
* information already known about the auction or associated data (floor
* data configured by prebid, browser data, user data etc) is added to
* the cache automatically.
*/
export const auctionCache = new Proxy(
{},
{
get: (target, name) => {
if (!target.hasOwnProperty(name)) {
target[name] = {
bids: [],
auctionDetail: {
refreshRank: Object.keys(target).length,
auctionId: name,
},
floorDetail: {},
pageDetail: {
host: getWindowLocation().host,
path: getWindowLocation().pathname,
search: getWindowLocation().search,
},
deviceDetail: {
platform: navigator.platform,
deviceType: getDeviceType(),
deviceOS: getOS(),
browser: getBrowser(),
},
userDetail: {
userIdTypes: Object.keys(getGlobal().getUserIds?.() || {}),
},
consentDetail: {
consentTypes: Object.keys(getGlobal().getConsentMetadata?.() || {}),
},
pmacDetail: JSON.parse(storage.getDataFromLocalStorage('pubx:pmac')) || {}, // {auction_1: {floor:0.23,maxBid:0.34,bidCount:3},auction_2:{floor:0.13,maxBid:0.14,bidCount:2}
extraData: JSON.parse(storage.getDataFromLocalStorage('pubx:extraData')) || {},
initOptions: {
...initOptions,
auctionId: name, // back-compat
},
sendAs: [],
};
}
return target[name];
},
}
);
/**
* Fetch extra ad server data for a specific ad slot (bid)
* @param {object} bid an output from extractBid
* @returns {object} key value pairs from the adserver
*/
const getAdServerDataForBid = (bid) => {
const gptSlot = getGptSlotForAdUnitCode(bid);
if (gptSlot) {
return Object.fromEntries(
gptSlot
.getTargetingKeys()
.filter(
(key) =>
key.startsWith('pubx-') ||
(key.startsWith('hb_') && (key.match(/_/g) || []).length === 1)
)
.map((key) => [key, gptSlot.getTargeting(key)])
);
}
return {}; // TODO: support more ad servers
};
/**
* extracts and derives valuable data from a prebid bidder bidResponse object
* @param {object} bidResponse a prebid bidder bidResponse (see
* https://docs.prebid.org/dev-docs/publisher-api-reference/getBidResponses.html)
* @returns {object}
*/
const extractBid = (bidResponse) => {
return {
adUnitCode: bidResponse.adUnitCode,
gptSlotCode:
getGptSlotInfoForAdUnitCode(bidResponse.adUnitCode).gptSlot || null,
auctionId: bidResponse.auctionId,
bidderCode: bidResponse.bidder,
cpm: bidResponse.cpm,
creativeId: bidResponse.creativeId,
dealId: bidResponse.dealId,
currency: bidResponse.currency,
floorData: bidResponse.floorData,
mediaType: bidResponse.mediaType,
netRevenue: bidResponse.netRevenue,
requestTimestamp: bidResponse.requestTimestamp,
responseTimestamp: bidResponse.responseTimestamp,
status: bidResponse.status,
sizes: parseSizesInput(bidResponse.size).toString(),
statusMessage: bidResponse.statusMessage,
timeToRespond: bidResponse.timeToRespond,
transactionId: bidResponse.transactionId,
bidId: bidResponse.bidId || bidResponse.requestId,
placementId: bidResponse.params
? deepAccess(bidResponse, 'params.0.placementId')
: null,
source: bidResponse.source || 'null',
};
};
/**
* Track the events emitted by prebid and handle each case. See https://docs.prebid.org/dev-docs/publisher-api-reference/getEvents.html for more info
* @param {object} event the prebid event emmitted
* @param {string} event.eventType the type of the event
* @param {object} event.args the arguments of the emitted event
*/
const track = ({ eventType, args }) => {
switch (eventType) {
// handle invalid bids, and remove them from the adUnit cache
case EVENTS.BID_TIMEOUT:
args.map(extractBid).forEach((bid) => {
bid.bidType = 3;
auctionCache[bid.auctionId].bids.push(bid);
});
break;
// handle valid bid responses and record them as part of an auction
case EVENTS.BID_RESPONSE:
const bid = Object.assign(extractBid(args), { bidType: 2 });
auctionCache[bid.auctionId].bids.push(bid);
break;
case EVENTS.BID_REJECTED:
const rejectedBid = Object.assign(extractBid(args), { bidType: 1 });
auctionCache[rejectedBid.auctionId].bids.push(rejectedBid);
break;
// capture extra information from the auction, and if there were no bids
// (and so no chance of a win) send the auction
case EVENTS.AUCTION_END:
Object.assign(
auctionCache[args.auctionId].floorDetail,
args.adUnits
.map((i) => i?.bids.length && i.bids[0]?.floorData)
.find((i) => i) || {}
);
auctionCache[args.auctionId].deviceDetail.cdep = args.bidderRequests
.map((bidRequest) => bidRequest.ortb2?.device?.ext?.cdep)
.find((i) => i);
Object.assign(auctionCache[args.auctionId].auctionDetail, {
adUnitCodes: args.adUnits.map((i) => i.code),
timestamp: args.timestamp,
});
if (
auctionCache[args.auctionId].bids.every((bid) => [1, 3].includes(bid.bidType))
) {
prepareSend(args.auctionId);
}
break;
// send the prebid winning bid back to pubx
case EVENTS.BID_WON:
const winningBid = extractBid(args);
const floorDetail = auctionCache[winningBid.auctionId].floorDetail;
Object.assign(winningBid, {
floorProvider: floorDetail?.floorProvider || null,
floorFetchStatus: floorDetail?.fetchStatus || null,
floorLocation: floorDetail?.location || null,
floorModelVersion: floorDetail?.modelVersion || null,
floorSkipRate: floorDetail?.skipRate || 0,
isFloorSkipped: floorDetail?.skipped || false,
isWinningBid: true,
renderedSize: args.size,
bidType: 4,
});
winningBid.adServerData = getAdServerDataForBid(winningBid);
auctionCache[winningBid.auctionId].winningBid = winningBid;
prepareSend(winningBid.auctionId);
break;
// do nothing
default:
break;
}
};
/**
* If true, send data back to pubxai
* @param {string} auctionId
* @param {number} samplingRate
* @returns {boolean}
*/
const shouldFireEventRequest = (auctionId, samplingRate = 1) => {
return parseInt(cyrb53Hash(auctionId)) % samplingRate === 0;
};
/**
* prepare the payload for sending auction data back to pubx.ai
* @param {string} auctionId the auction to send
*/
const prepareSend = (auctionId) => {
const auctionData = Object.assign({}, auctionCache[auctionId]);
if (!shouldFireEventRequest(auctionId, initOptions.samplingRate)) {
return;
}
[
{
path: winningBidPath,
requiredKeys: [
'winningBid',
'pageDetail',
'deviceDetail',
'floorDetail',
'auctionDetail',
'userDetail',
'consentDetail',
'pmacDetail',
'extraData',
'initOptions',
],
eventType: 'win',
},
{
path: auctionPath,
requiredKeys: [
'bids',
'pageDetail',
'deviceDetail',
'floorDetail',
'auctionDetail',
'userDetail',
'consentDetail',
'pmacDetail',
'extraData',
'initOptions',
],
eventType: 'auction',
},
].forEach(({ path, requiredKeys, eventType }) => {
const data = Object.fromEntries(
requiredKeys.map((key) => [key, auctionData[key]])
);
if (
auctionCache[auctionId].sendAs.includes(eventType) ||
!requiredKeys.every((key) => !!auctionData[key])
) {
return;
}
const pubxaiAnalyticsRequestUrl = buildUrl({
protocol: 'https',
hostname:
(auctionData.initOptions && auctionData.initOptions.hostName) ||
defaultHost,
pathname: path,
search: {
auctionTimestamp: auctionData.auctionDetail.timestamp,
pubxaiAnalyticsVersion: pubxaiAnalyticsVersion,
prebidVersion: '$prebid.version$',
pubxId: initOptions.pubxId,
},
});
sendCache[pubxaiAnalyticsRequestUrl].push(data);
auctionCache[auctionId].sendAs.push(eventType);
});
};
const send = () => {
const toBlob = (d) => new Blob([JSON.stringify(d)], { type: 'text/json' });
Object.entries(sendCache).forEach(([requestUrl, events]) => {
let payloadStart = 0;
events.forEach((event, index, arr) => {
const payload = arr.slice(payloadStart, index + 2);
const payloadTooLarge = toBlob(payload).size > 65536;
if (payloadTooLarge || index + 1 === arr.length) {
sendBeacon(
requestUrl,
toBlob(payloadTooLarge ? payload.slice(0, -1) : payload)
);
payloadStart = index;
}
});
events.splice(0);
});
};
// register event listener to send logs when user leaves page
if (document.visibilityState) {
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
send();
}
});
}
// declare the analytics adapter
var pubxaiAnalyticsAdapter = Object.assign(
adapter({
emptyUrl,
analyticsType,
}),
{ track }
);
pubxaiAnalyticsAdapter.originEnableAnalytics =
pubxaiAnalyticsAdapter.enableAnalytics;
pubxaiAnalyticsAdapter.enableAnalytics = (config) => {
initOptions = config.options;
pubxaiAnalyticsAdapter.originEnableAnalytics(config);
};
adapterManager.registerAnalyticsAdapter({
adapter: pubxaiAnalyticsAdapter,
code: adapterCode,
});
export default pubxaiAnalyticsAdapter;