forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
permutiveRtdProvider.js
496 lines (421 loc) · 15.8 KB
/
permutiveRtdProvider.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/**
* This module adds permutive provider to the real time data module
* The {@link module:modules/realTimeData} module is required
* The module will add custom segment targeting to ad units of specific bidders
* @module modules/permutiveRtdProvider
* @requires module:modules/realTimeData
*/
import {getGlobal} from '../src/prebidGlobal.js';
import {submodule} from '../src/hook.js';
import {getStorageManager} from '../src/storageManager.js';
import {deepAccess, deepSetValue, isFn, logError, mergeDeep, isPlainObject, safeJSONParse, prefixLog} from '../src/utils.js';
import {includes} from '../src/polyfill.js';
import {MODULE_TYPE_RTD} from '../src/activities/modules.js';
/**
* @typedef {import('../modules/rtdModule/index.js').RtdSubmodule} RtdSubmodule
*/
const MODULE_NAME = 'permutive'
const logger = prefixLog('[PermutiveRTD]')
export const PERMUTIVE_SUBMODULE_CONFIG_KEY = 'permutive-prebid-rtd'
export const PERMUTIVE_STANDARD_KEYWORD = 'p_standard'
export const PERMUTIVE_CUSTOM_COHORTS_KEYWORD = 'permutive'
export const PERMUTIVE_STANDARD_AUD_KEYWORD = 'p_standard_aud'
export const storage = getStorageManager({moduleType: MODULE_TYPE_RTD, moduleName: MODULE_NAME})
function init(moduleConfig, userConsent) {
readPermutiveModuleConfigFromCache()
return true
}
function liftIntoParams(params) {
return isPlainObject(params) ? { params } : {}
}
let cachedPermutiveModuleConfig = {}
/**
* Access the submodules RTD params that are cached to LocalStorage by the Permutive SDK. This lets the RTD submodule
* apply publisher defined params set in the Permutive platform, so they may still be applied if the Permutive SDK has
* not initialised before this submodule is initialised.
*/
function readPermutiveModuleConfigFromCache() {
const params = safeJSONParse(storage.getDataFromLocalStorage(PERMUTIVE_SUBMODULE_CONFIG_KEY))
return cachedPermutiveModuleConfig = liftIntoParams(params)
}
/**
* Access the submodules RTD params attached to the Permutive SDK.
*
* @return The Permutive config available by the Permutive SDK or null if the operation errors.
*/
function getParamsFromPermutive() {
try {
return liftIntoParams(window.permutive.addons.prebid.getPermutiveRtdConfig())
} catch (e) {
return null
}
}
/**
* Merges segments into existing bidder config in reverse priority order. The highest priority is 1.
*
* 1. customModuleConfig <- set by publisher with pbjs.setConfig
* 2. permutiveRtdConfig <- set by the publisher using the Permutive platform
* 3. defaultConfig
*
* As items with a higher priority will be deeply merged into the previous config, deep merges are performed by
* reversing the priority order.
*
* @param {Object} customModuleConfig - Publisher config for module
* @return {Object} Deep merges of the default, Permutive and custom config.
*/
export function getModuleConfig(customModuleConfig) {
// Use the params from Permutive if available, otherwise fallback to the cached value set by Permutive.
const permutiveModuleConfig = getParamsFromPermutive() || cachedPermutiveModuleConfig
return mergeDeep({
waitForIt: false,
params: {
maxSegs: 500,
acBidders: [],
overwrites: {},
},
},
permutiveModuleConfig,
customModuleConfig,
)
}
/**
* Sets ortb2 config for ac bidders
* @param {Object} bidderOrtb2 - The ortb2 object for the all bidders
* @param {Object} moduleConfig - Publisher config for module
* @param {Object} segmentData - Segment data grouped by bidder or type
*/
export function setBidderRtb (bidderOrtb2, moduleConfig, segmentData) {
const acBidders = deepAccess(moduleConfig, 'params.acBidders')
const maxSegs = deepAccess(moduleConfig, 'params.maxSegs')
const transformationConfigs = deepAccess(moduleConfig, 'params.transformations') || []
const ssps = segmentData?.ssp?.ssps ?? []
const sspCohorts = segmentData?.ssp?.cohorts ?? []
const topics = segmentData?.topics ?? {}
const bidders = new Set([...acBidders, ...ssps])
bidders.forEach(function (bidder) {
const currConfig = { ortb2: bidderOrtb2[bidder] || {} }
let cohorts = []
const isAcBidder = acBidders.indexOf(bidder) > -1
if (isAcBidder) {
cohorts = segmentData.ac
}
const isSspBidder = ssps.indexOf(bidder) > -1
if (isSspBidder) {
cohorts = [...new Set([...cohorts, ...sspCohorts])].slice(0, maxSegs)
}
const nextConfig = updateOrtbConfig(bidder, currConfig, cohorts, sspCohorts, topics, transformationConfigs, segmentData)
bidderOrtb2[bidder] = nextConfig.ortb2
})
}
/**
* Updates `user.data` object in existing bidder config with Permutive segments
* @param {string} bidder - The bidder identifier
* @param {Object} currConfig - Current bidder config
* @param {string[]} segmentIDs - Permutive segment IDs
* @param {string[]} sspSegmentIDs - Permutive SSP segment IDs
* @param {Object} topics - Privacy Sandbox Topics, keyed by IAB taxonomy version (600, 601, etc.)
* @param {Object[]} transformationConfigs - array of objects with `id` and `config` properties, used to determine
* the transformations on user data to include the ORTB2 object
* @param {Object} segmentData - The segments available for targeting
* @return {Object} Merged ortb2 object
*/
function updateOrtbConfig(bidder, currConfig, segmentIDs, sspSegmentIDs, topics, transformationConfigs, segmentData) {
logger.logInfo(`Current ortb2 config`, { bidder, config: currConfig })
const customCohortsData = deepAccess(segmentData, bidder) || []
const name = 'permutive.com'
const permutiveUserData = {
name,
segment: segmentIDs.map(segmentId => ({ id: segmentId })),
}
const transformedUserData = transformationConfigs
.filter(({ id }) => ortb2UserDataTransformations.hasOwnProperty(id))
.map(({ id, config }) => ortb2UserDataTransformations[id](permutiveUserData, config))
const customCohortsUserData = {
name: PERMUTIVE_CUSTOM_COHORTS_KEYWORD,
segment: customCohortsData.map(cohortID => ({ id: cohortID })),
}
const ortbConfig = mergeDeep({}, currConfig)
const currentUserData = deepAccess(ortbConfig, 'ortb2.user.data') || []
let topicsUserData = []
for (const [k, value] of Object.entries(topics)) {
topicsUserData.push({
name,
ext: {
segtax: Number(k)
},
segment: value.map(topic => ({ id: topic.toString() })),
})
}
const updatedUserData = currentUserData
.filter(el => el.name !== permutiveUserData.name && el.name !== customCohortsUserData.name)
.concat(permutiveUserData, transformedUserData, customCohortsUserData)
.concat(topicsUserData)
logger.logInfo(`Updating ortb2.user.data`, { bidder, user_data: updatedUserData })
deepSetValue(ortbConfig, 'ortb2.user.data', updatedUserData)
// Set ortb2.user.keywords
const currentKeywords = deepAccess(ortbConfig, 'ortb2.user.keywords')
const keywordGroups = {
[PERMUTIVE_STANDARD_KEYWORD]: segmentIDs,
[PERMUTIVE_STANDARD_AUD_KEYWORD]: sspSegmentIDs,
[PERMUTIVE_CUSTOM_COHORTS_KEYWORD]: customCohortsData,
}
// Transform groups of key-values into a single array of strings
// i.e { permutive: ['1', '2'], p_standard: ['3', '4'] } => ['permutive=1', 'permutive=2', 'p_standard=3',' p_standard=4']
const transformedKeywordGroups = Object.entries(keywordGroups)
.flatMap(([keyword, ids]) => ids.map(id => `${keyword}=${id}`))
const keywords = [
currentKeywords,
...transformedKeywordGroups,
]
.filter(Boolean)
.join(',')
logger.logInfo(`Updating ortb2.user.keywords`, {
bidder,
keywords,
})
deepSetValue(ortbConfig, 'ortb2.user.keywords', keywords)
// Set user extensions
if (segmentIDs.length > 0) {
deepSetValue(ortbConfig, `ortb2.user.ext.data.${PERMUTIVE_STANDARD_KEYWORD}`, segmentIDs)
logger.logInfo(`Extending ortb2.user.ext.data with "${PERMUTIVE_STANDARD_KEYWORD}"`, segmentIDs)
}
if (customCohortsData.length > 0) {
deepSetValue(ortbConfig, `ortb2.user.ext.data.${PERMUTIVE_CUSTOM_COHORTS_KEYWORD}`, customCohortsData.map(String))
logger.logInfo(`Extending ortb2.user.ext.data with "${PERMUTIVE_CUSTOM_COHORTS_KEYWORD}"`, customCohortsData)
}
// Set site extensions
if (segmentIDs.length > 0) {
deepSetValue(ortbConfig, `ortb2.site.ext.permutive.${PERMUTIVE_STANDARD_KEYWORD}`, segmentIDs)
logger.logInfo(`Extending ortb2.site.ext.permutive with "${PERMUTIVE_STANDARD_KEYWORD}"`, segmentIDs)
}
logger.logInfo(`Updated ortb2 config`, { bidder, config: ortbConfig })
return ortbConfig
}
/**
* Set segments on bid request object
* @param {Object} reqBidsConfigObj - Bid request object
* @param {Object} moduleConfig - Module configuration
* @param {Object} segmentData - Segment object
*/
function setSegments (reqBidsConfigObj, moduleConfig, segmentData) {
const adUnits = (reqBidsConfigObj && reqBidsConfigObj.adUnits) || getGlobal().adUnits
const utils = { deepSetValue, deepAccess, isFn, mergeDeep }
const aliasMap = {
appnexusAst: 'appnexus'
}
if (!adUnits) {
return
}
adUnits.forEach(adUnit => {
adUnit.bids.forEach(bid => {
let { bidder } = bid
if (typeof aliasMap[bidder] !== 'undefined') {
bidder = aliasMap[bidder]
}
const acEnabled = isAcEnabled(moduleConfig, bidder)
const customFn = getCustomBidderFn(moduleConfig, bidder)
if (customFn) {
// For backwards compatibility we pass an identity function to any custom bidder function set by a publisher
const bidIdentity = (bid) => bid
customFn(bid, segmentData, acEnabled, utils, bidIdentity)
}
})
})
}
/**
* Catch and log errors
* @param {function} fn - Function to safely evaluate
*/
function makeSafe (fn) {
try {
return fn()
} catch (e) {
logError(e)
}
}
function getCustomBidderFn (moduleConfig, bidder) {
const overwriteFn = deepAccess(moduleConfig, `params.overwrites.${bidder}`)
if (overwriteFn && isFn(overwriteFn)) {
return overwriteFn
} else {
return null
}
}
/**
* Check whether ac is enabled for bidder
* @param {Object} moduleConfig - Module configuration
* @param {string} bidder - Bidder name
* @return {boolean}
*/
export function isAcEnabled (moduleConfig, bidder) {
const acBidders = deepAccess(moduleConfig, 'params.acBidders') || []
return includes(acBidders, bidder)
}
/**
* Check whether Permutive is on page
* @return {boolean}
*/
export function isPermutiveOnPage () {
return typeof window.permutive !== 'undefined' && typeof window.permutive.ready === 'function'
}
/**
* Get all relevant segment IDs in an object
* @param {number} maxSegs - Maximum number of segments to be included
* @return {Object}
*/
export function getSegments(maxSegs) {
const segments = {
ac:
makeSafe(() => {
const legacySegs =
makeSafe(() =>
readSegments('_psegs', [])
.map(Number)
.filter((seg) => seg >= 1000000)
.map(String),
) || [];
const _ppam = makeSafe(() => readSegments('_ppam', []).map(String)) || [];
const _pcrprs = makeSafe(() => readSegments('_pcrprs', []).map(String)) || [];
return [..._pcrprs, ..._ppam, ...legacySegs];
}) || [],
ix:
makeSafe(() => {
const _pindexs = readSegments('_pindexs', []);
return _pindexs.map(String);
}) || [],
rubicon:
makeSafe(() => {
const _prubicons = readSegments('_prubicons', []);
return _prubicons.map(String);
}) || [],
appnexus:
makeSafe(() => {
const _papns = readSegments('_papns', []);
return _papns.map(String);
}) || [],
gam:
makeSafe(() => {
const _pdfps = readSegments('_pdfps', []);
return _pdfps.map(String);
}) || [],
ssp: makeSafe(() => {
const _pssps = readSegments('_pssps', {
cohorts: [],
ssps: [],
});
return {
cohorts: makeSafe(() => _pssps.cohorts.map(String)) || [],
ssps: makeSafe(() => _pssps.ssps.map(String)) || [],
};
}),
topics:
makeSafe(() => {
const _ppsts = readSegments('_ppsts', {});
const topics = {};
for (const [k, value] of Object.entries(_ppsts)) {
topics[k] = makeSafe(() => value.map(String)) || [];
}
return topics;
}) || {},
};
for (const bidder in segments) {
if (bidder === 'ssp') {
if (segments[bidder].cohorts && Array.isArray(segments[bidder].cohorts)) {
segments[bidder].cohorts = segments[bidder].cohorts.slice(0, maxSegs)
}
} else if (bidder === 'topics') {
for (const taxonomy in segments[bidder]) {
segments[bidder][taxonomy] = segments[bidder][taxonomy].slice(0, maxSegs)
}
} else {
segments[bidder] = segments[bidder].slice(0, maxSegs)
}
}
logger.logInfo(`Read segments`, segments)
return segments;
}
/**
* Gets an array of segment IDs from LocalStorage
* or return the default value provided.
* @template A
* @param {string} key
* @param {A} defaultValue
* @return {A}
*/
function readSegments (key, defaultValue) {
try {
return JSON.parse(storage.getDataFromLocalStorage(key)) || defaultValue
} catch (e) {
return defaultValue
}
}
const unknownIabSegmentId = '_unknown_'
/**
* Functions to apply to ORT2B2 `user.data` objects.
* Each function should return an a new object containing a `name`, (optional) `ext` and `segment`
* properties. The result of the each transformation defined here will be appended to the array
* under `user.data` in the bid request.
*/
const ortb2UserDataTransformations = {
iab: (userData, config) => ({
name: userData.name,
ext: { segtax: config.segtax },
segment: (userData.segment || [])
.map(segment => ({ id: iabSegmentId(segment.id, config.iabIds) }))
.filter(segment => segment.id !== unknownIabSegmentId)
})
}
/**
* Transform a Permutive segment ID into an IAB audience taxonomy ID.
* @param {string} permutiveSegmentId
* @param {Object} iabIds object of mappings between Permutive and IAB segment IDs (key: permutive ID, value: IAB ID)
* @return {string} IAB audience taxonomy ID associated with the Permutive segment ID
*/
function iabSegmentId(permutiveSegmentId, iabIds) {
return iabIds[permutiveSegmentId] || unknownIabSegmentId
}
/**
* Pull the latest configuration and cohort information and update accordingly.
*
* @param reqBidsConfigObj - Bidder provided config for request
* @param moduleConfig - Publisher provided config
*/
export function readAndSetCohorts(reqBidsConfigObj, moduleConfig) {
const segmentData = getSegments(deepAccess(moduleConfig, 'params.maxSegs'))
makeSafe(function () {
// Legacy route with custom parameters
// ACK policy violation, in process of removing
setSegments(reqBidsConfigObj, moduleConfig, segmentData)
});
makeSafe(function () {
// Route for bidders supporting ORTB2
setBidderRtb(reqBidsConfigObj.ortb2Fragments?.bidder, moduleConfig, segmentData)
})
}
let permutiveSDKInRealTime = false
/** @type {RtdSubmodule} */
export const permutiveSubmodule = {
name: MODULE_NAME,
getBidRequestData: function (reqBidsConfigObj, callback, customModuleConfig) {
const completeBidRequestData = () => {
logger.logInfo(`Request data updated`)
callback()
}
const moduleConfig = getModuleConfig(customModuleConfig)
readAndSetCohorts(reqBidsConfigObj, moduleConfig)
makeSafe(function () {
if (permutiveSDKInRealTime || !(moduleConfig.waitForIt && isPermutiveOnPage())) {
return completeBidRequestData()
}
window.permutive.ready(function () {
logger.logInfo(`SDK is realtime, updating cohorts`)
permutiveSDKInRealTime = true
readAndSetCohorts(reqBidsConfigObj, getModuleConfig(customModuleConfig))
completeBidRequestData()
}, 'realtime')
logger.logInfo(`Registered cohort update when SDK is realtime`)
})
},
init: init
}
submodule('realTimeData', permutiveSubmodule)