-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRokt-Kit.js
More file actions
415 lines (363 loc) · 13.6 KB
/
Rokt-Kit.js
File metadata and controls
415 lines (363 loc) · 13.6 KB
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
/* eslint-disable no-undef */
// Copyright 2025 mParticle, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var name = 'Rokt';
var moduleId = 181;
var ROKT_EXTENSIONS = {
'Coupon on Signup Extension Detection': 'cos-extension-detection',
'Experiment Monitoring': 'experiment-monitoring',
'Sponsored Payments Apple Pay': 'sponsored-payments-apple-pay',
'Realtime Conversion Promotion': 'realtime-conversion-promotion',
};
var constructor = function () {
var self = this;
self.name = name;
self.moduleId = moduleId;
self.isInitialized = false;
self.launcher = null;
self.filters = {};
self.filteredUser = {};
self.userAttributes = {};
self.testHelpers = null;
/**
* Generates the Rokt launcher script URL with optional extensions
* @param {Array<string>} extensions - List of extension query parameters to append
* @returns {string} The complete launcher script URL
*/
function generateLauncherScript(extensions) {
var baseUrl = 'https://apps.rokt.com/wsdk/integrations/launcher.js';
if (!extensions || extensions.length === 0) {
return baseUrl;
}
return baseUrl + '?extensions=' + extensions.join(',');
}
/**
* Passes attributes to the Rokt Web SDK for client-side hashing
* @see https://docs.rokt.com/developers/integration-guides/web/library/integration-launcher#hash-attributes
* @param {Object} attributes - The attributes to be hashed
* @returns {Promise<Object|null>} A Promise resolving to the
* hashed attributes from the launcher, or `null` if the kit is not initialized
*/
function hashAttributes(attributes) {
if (!isInitialized()) {
console.error('Rokt Kit: Not initialized');
return null;
}
return self.launcher.hashAttributes(attributes);
}
function initForwarder(
settings,
_service,
testMode,
_trackerId,
filteredUserAttributes
) {
var accountId = settings.accountId;
var roktExtensions = extractRoktExtensions(settings.roktExtensions);
self.userAttributes = filteredUserAttributes;
self.onboardingExpProvider = settings.onboardingExpProvider;
if (testMode) {
// Initialize test helpers only in test mode
self.testHelpers = {
generateLauncherScript: generateLauncherScript,
extractRoktExtensions: extractRoktExtensions,
};
attachLauncher(accountId);
return;
}
if (!window.Rokt || !(window.Rokt && window.Rokt.currentLauncher)) {
var target = document.head || document.body;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = generateLauncherScript(roktExtensions);
script.async = true;
script.crossOrigin = 'anonymous';
script.fetchPriority = 'high';
script.id = 'rokt-launcher';
script.onload = function () {
// Once the script loads, ensure the Rokt object is available
if (
window.Rokt &&
typeof window.Rokt.createLauncher === 'function' &&
window.Rokt.currentLauncher === undefined
) {
attachLauncher(accountId);
} else {
console.error(
'Rokt object is not available after script load.'
);
}
};
script.onerror = function (error) {
console.error('Error loading Rokt launcher script:', error);
};
target.appendChild(script);
} else {
console.warn('Unable to find Rokt on the page');
}
}
/**
* Selects placements for Rokt Web SDK with merged attributes, filters, and experimentation options
* @see https://docs.rokt.com/developers/integration-guides/web/library/select-placements-options/
* @param {Object} options - The options object for selecting placements containing:
* - identifier {string}: The placement identifier
* - attributes {Object}: Optional attributes to merge with existing attributes
* @returns {Promise<void>} A Promise resolving to the Rokt launcher's selectPlacements method with processed attributes
*/
function selectPlacements(options) {
var attributes = (options && options.attributes) || {};
var placementAttributes = mergeObjects(self.userAttributes, attributes);
var filters = self.filters || {};
var userAttributeFilters = filters.userAttributeFilters || [];
var filteredUser = filters.filteredUser || {};
var mpid =
filteredUser &&
filteredUser.getMPID &&
typeof filteredUser.getMPID === 'function'
? filteredUser.getMPID()
: null;
var filteredAttributes;
if (!filters) {
console.warn(
'Rokt Kit: No filters available, using user attributes'
);
filteredAttributes = placementAttributes;
} else if (filters.filterUserAttributes) {
filteredAttributes = filters.filterUserAttributes(
placementAttributes,
userAttributeFilters
);
}
self.userAttributes = filteredAttributes;
var experimentAttributes = formatExperimentAttributes(attributes);
var selectPlacementsAttributes = mergeObjects(
filteredAttributes,
experimentAttributes,
{
mpid: mpid,
}
);
var selectPlacementsOptions = mergeObjects(options, {
attributes: selectPlacementsAttributes,
});
self.launcher.selectPlacements(selectPlacementsOptions);
}
/**
* Sets extension data for Rokt Web SDK
* @param {Object} partnerExtensionData - The extension data object containing:
* - [extensionName] {string}: Name of the extension
* - [extensionName].options {Object}: Key-value pairs of options for the extension
* @returns {void} Nothing is returned
*/
function setExtensionData(partnerExtensionData) {
if (!isInitialized()) {
console.error('Rokt Kit: Not initialized');
return;
}
window.Rokt.setExtensionData(partnerExtensionData);
}
function onUserIdentified(filteredUser) {
self.filteredUser = filteredUser;
self.userAttributes = filteredUser.getAllUserAttributes();
}
function setUserAttribute(key, value) {
self.userAttributes[key] = value;
}
function removeUserAttribute(key) {
delete self.userAttributes[key];
}
function attachLauncher(accountId) {
window.Rokt.createLauncher({
accountId: accountId,
integrationName:
'mParticle_' +
'wsdkv_' +
window.mParticle.getVersion() +
'_kitv_' +
process.env.PACKAGE_VERSION,
})
.then(function (launcher) {
// Assign the launcher to a global variable for later access
window.Rokt.currentLauncher = launcher;
// Locally cache the launcher and filters
self.launcher = launcher;
var roktFilters = window.mParticle.Rokt.filters;
if (!roktFilters) {
console.warn('Rokt Kit: No filters have been set.');
} else {
self.filters = roktFilters;
if (!roktFilters.filteredUser) {
console.warn(
'Rokt Kit: No filtered user has been set.'
);
} else {
self.filteredUser = roktFilters.filteredUser;
}
}
// Attaches the kit to the Rokt manager
window.mParticle.Rokt.attachKit(self);
self.isInitialized = true;
})
.catch(function (err) {
console.error('Error creating Rokt launcher:', err);
});
}
function formatExperimentAttributes(attributes) {
var PREFIX = 'rokt.partnerexperiment.';
var EXPERIMENT_ID_KEY = PREFIX + 'experimentid';
var BUCKET_ID_KEY = PREFIX + 'bucketid';
var USER_ID_KEY = PREFIX + 'userid';
if (self.onboardingExpProvider === 'Optimizely') {
return fetchOptimizely(attributes);
}
var result = {};
result[PREFIX + attributes[EXPERIMENT_ID_KEY] + '.bucketid'] =
attributes[BUCKET_ID_KEY];
result['rokt.clientcustomerid'] = attributes[USER_ID_KEY];
return result;
}
// mParticle Kit Callback Methods
function fetchOptimizely() {
var forwarders = window.mParticle
._getActiveForwarders()
.filter(function (forwarder) {
return forwarder.name === 'Optimizely';
});
try {
if (forwarders.length > 0 && window.optimizely) {
// Get the state object
var optimizelyState = window.optimizely.get('state');
if (
!optimizelyState ||
!optimizelyState.getActiveExperimentIds
) {
return {};
}
// Get active experiment IDs
var activeExperimentIds =
optimizelyState.getActiveExperimentIds();
// Get variations for each active experiment
var activeExperiments = activeExperimentIds.reduce(function (
acc,
expId
) {
acc['rokt.partnerexperiment.' + expId + '.bucketid'] =
optimizelyState.getVariationMap()[expId].id;
return acc;
},
{});
var visitorId = window.optimizely.get('visitor').visitorId;
activeExperiments['rokt.clientcustomerid'] = visitorId;
return activeExperiments;
}
} catch (error) {
console.error('Error fetching Optimizely attributes:', error);
}
return {};
}
// Called by the mParticle Rokt Manager
this.selectPlacements = selectPlacements;
this.hashAttributes = hashAttributes;
// Kit Callback Methods
this.init = initForwarder;
this.setExtensionData = setExtensionData;
this.setUserAttribute = setUserAttribute;
this.onUserIdentified = onUserIdentified;
this.removeUserAttribute = removeUserAttribute;
/**
* Checks if the kit is properly initialized and ready for use.
* Both conditions must be true:
* 1. self.isInitialized - Set after successful initialization of the kit
* 2. self.launcher - The Rokt launcher instance must be available
* @returns {boolean} Whether the kit is fully initialized
*/
function isInitialized() {
return !!(self.isInitialized && self.launcher);
}
};
function getId() {
return moduleId;
}
function register(config) {
if (!config) {
window.console.log(
'You must pass a config object to register the kit ' + name
);
return;
}
if (!isObject(config)) {
window.console.log(
"'config' must be an object. You passed in a " + typeof config
);
return;
}
if (isObject(config.kits)) {
config.kits[name] = {
constructor: constructor,
};
} else {
config.kits = {};
config.kits[name] = {
constructor: constructor,
};
}
window.console.log(
'Successfully registered ' + name + ' to your mParticle configuration'
);
}
function isObject(val) {
return (
val != null && typeof val === 'object' && Array.isArray(val) === false
);
}
function mergeObjects() {
var resObj = {};
for (var i = 0; i < arguments.length; i += 1) {
var obj = arguments[i],
keys = Object.keys(obj);
for (var j = 0; j < keys.length; j += 1) {
resObj[keys[j]] = obj[keys[j]];
}
}
return resObj;
}
function parseSettingsString(settingsString) {
try {
return JSON.parse(settingsString.replace(/"/g, '"'));
} catch (error) {
throw new Error('Settings string contains invalid JSON');
}
}
function extractRoktExtensions(settingsString) {
var settings = settingsString ? parseSettingsString(settingsString) : [];
var roktExtensions = [];
for (var i = 0; i < settings.length; i++) {
var extensionName = settings[i].value;
var mappedExtension = ROKT_EXTENSIONS[extensionName];
if (mappedExtension) {
roktExtensions.push(mappedExtension);
}
}
return roktExtensions;
}
if (window && window.mParticle && window.mParticle.addForwarder) {
window.mParticle.addForwarder({
name: name,
constructor: constructor,
getId: getId,
});
}
module.exports = {
register: register,
};