@mparticle/web-rokt-kit 1.22.0 → 1.24.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.
@@ -1,1287 +1,2 @@
1
- var RoktKit = (function (exports) {
2
- 'use strict';
3
-
4
- /* eslint-disable no-undef */
5
- // Copyright 2025 mParticle, Inc.
6
- //
7
- // Licensed under the Apache License, Version 2.0 (the "License");
8
- // you may not use this file except in compliance with the License.
9
- // You may obtain a copy of the License at
10
- //
11
- // http://www.apache.org/licenses/LICENSE-2.0
12
- //
13
- // Unless required by applicable law or agreed to in writing, software
14
- // distributed under the License is distributed on an "AS IS" BASIS,
15
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
- // See the License for the specific language governing permissions and
17
- // limitations under the License.
18
-
19
- var name = 'Rokt';
20
- var moduleId = 181;
21
- var EVENT_NAME_SELECT_PLACEMENTS = 'selectPlacements';
22
-
23
- var constructor = function () {
24
- var self = this;
25
- var PerformanceMarks = {
26
- RoktScriptAppended: 'mp:RoktScriptAppended',
27
- };
28
-
29
- var EMAIL_SHA256_KEY = 'emailsha256';
30
-
31
- // Dynamic identity type for Rokt's emailsha256 identity value which MP doesn't natively support - will be set during initialization
32
- var mappedEmailSha256Key;
33
-
34
- self.name = name;
35
- self.moduleId = moduleId;
36
- self.isInitialized = false;
37
-
38
- self.launcher = null;
39
- self.filters = {};
40
- self.userAttributes = {};
41
- self.testHelpers = null;
42
- self.placementEventMappingLookup = {};
43
- self.placementEventAttributeMappingLookup = {};
44
- self.eventQueue = [];
45
- self.eventStreamQueue = [];
46
- self.integrationName = null;
47
-
48
- function getEventAttributeValue(event, eventAttributeKey) {
49
- var attributes = event && event.EventAttributes;
50
- if (!attributes) {
51
- return null;
52
- }
53
-
54
- if (typeof attributes[eventAttributeKey] === 'undefined') {
55
- return null;
56
- }
57
-
58
- return attributes[eventAttributeKey];
59
- }
60
-
61
- function doesEventAttributeConditionMatch(condition, actualValue) {
62
- if (!condition || !isString(condition.operator)) {
63
- return false;
64
- }
65
-
66
- var operator = condition.operator.toLowerCase();
67
- var expectedValue = condition.attributeValue;
68
-
69
- if (operator === 'exists') {
70
- return actualValue !== null;
71
- }
72
-
73
- if (actualValue == null) {
74
- return false;
75
- }
76
-
77
- if (operator === 'equals') {
78
- return String(actualValue) === String(expectedValue);
79
- }
80
-
81
- if (operator === 'contains') {
82
- return String(actualValue).indexOf(String(expectedValue)) !== -1;
83
- }
84
-
85
- return false;
86
- }
87
-
88
- function doesEventMatchRule(event, rule) {
89
- if (!rule || !isString(rule.eventAttributeKey)) {
90
- return false;
91
- }
92
-
93
- var conditions = rule.conditions;
94
- if (!Array.isArray(conditions)) {
95
- return false;
96
- }
97
-
98
- var actualValue = getEventAttributeValue(event, rule.eventAttributeKey);
99
-
100
- if (conditions.length === 0) {
101
- return actualValue !== null;
102
- }
103
- for (var i = 0; i < conditions.length; i++) {
104
- if (!doesEventAttributeConditionMatch(conditions[i], actualValue)) {
105
- return false;
106
- }
107
- }
108
-
109
- return true;
110
- }
111
-
112
- function generateMappedEventAttributeLookup(
113
- placementEventAttributeMapping
114
- ) {
115
- var mappedAttributeKeys = {};
116
- if (!Array.isArray(placementEventAttributeMapping)) {
117
- return mappedAttributeKeys;
118
- }
119
- for (var i = 0; i < placementEventAttributeMapping.length; i++) {
120
- var mapping = placementEventAttributeMapping[i];
121
- if (
122
- !mapping ||
123
- !isString(mapping.value) ||
124
- !isString(mapping.map)
125
- ) {
126
- continue;
127
- }
128
-
129
- var mappedAttributeKey = mapping.value;
130
- var eventAttributeKey = mapping.map;
131
-
132
- if (!mappedAttributeKeys[mappedAttributeKey]) {
133
- mappedAttributeKeys[mappedAttributeKey] = [];
134
- }
135
-
136
- mappedAttributeKeys[mappedAttributeKey].push({
137
- eventAttributeKey: eventAttributeKey,
138
- conditions: Array.isArray(mapping.conditions)
139
- ? mapping.conditions
140
- : [],
141
- });
142
- }
143
- return mappedAttributeKeys;
144
- }
145
-
146
- function applyPlacementEventAttributeMapping(event) {
147
- var mappedAttributeKeys = Object.keys(
148
- self.placementEventAttributeMappingLookup
149
- );
150
- for (var i = 0; i < mappedAttributeKeys.length; i++) {
151
- var mappedAttributeKey = mappedAttributeKeys[i];
152
- var rulesForMappedAttributeKey =
153
- self.placementEventAttributeMappingLookup[mappedAttributeKey];
154
- if (isEmpty(rulesForMappedAttributeKey)) {
155
- continue;
156
- }
157
-
158
- // Require ALL rules for the same key to match (AND).
159
- var allMatch = true;
160
- for (var j = 0; j < rulesForMappedAttributeKey.length; j++) {
161
- if (!doesEventMatchRule(event, rulesForMappedAttributeKey[j])) {
162
- allMatch = false;
163
- break;
164
- }
165
- }
166
- if (!allMatch) {
167
- continue;
168
- }
169
-
170
- window.mParticle.Rokt.setLocalSessionAttribute(
171
- mappedAttributeKey,
172
- true
173
- );
174
- }
175
- }
176
-
177
- /**
178
- * Generates the Rokt launcher script URL with optional domain override and extensions
179
- * @param {string} domain - The CNAME domain to use for overriding the launcher url
180
- * @param {Array<string>} extensions - List of extension query parameters to append
181
- * @returns {string} The complete launcher script URL
182
- */
183
- function generateLauncherScript(_domain, extensions) {
184
- // Override domain if a customer is using a CNAME
185
- // If a customer is using a CNAME, a domain will be passed. If not, we use the default domain.
186
- var domain = typeof _domain !== 'undefined' ? _domain : 'apps.rokt.com';
187
- var protocol = 'https://';
188
- var launcherPath = '/wsdk/integrations/launcher.js';
189
- var baseUrl = [protocol, domain, launcherPath].join('');
190
-
191
- if (!extensions || extensions.length === 0) {
192
- return baseUrl;
193
- }
194
- return baseUrl + '?extensions=' + extensions.join(',');
195
- }
196
-
197
- /**
198
- * Checks if Rokt launcher is available and ready to attach
199
- * @returns {boolean} True if launcher can be attached
200
- */
201
- function isLauncherReadyToAttach() {
202
- return window.Rokt && typeof window.Rokt.createLauncher === 'function';
203
- }
204
-
205
- /**
206
- * Passes attributes to the Rokt Web SDK for client-side hashing
207
- * @see https://docs.rokt.com/developers/integration-guides/web/library/integration-launcher#hash-attributes
208
- * @param {Object} attributes - The attributes to be hashed
209
- * @returns {Promise<Object|null>} A Promise resolving to the
210
- * hashed attributes from the launcher, or `null` if the kit is not initialized
211
- */
212
- function hashAttributes(attributes) {
213
- if (!isKitReady()) {
214
- console.error('Rokt Kit: Not initialized');
215
- return null;
216
- }
217
- return self.launcher.hashAttributes(attributes);
218
- }
219
-
220
- function initForwarder(
221
- settings,
222
- _service,
223
- testMode,
224
- _trackerId,
225
- filteredUserAttributes
226
- ) {
227
- var accountId = settings.accountId;
228
- var roktExtensions = extractRoktExtensions(settings.roktExtensions);
229
- self.userAttributes = filteredUserAttributes || {};
230
- self.onboardingExpProvider = settings.onboardingExpProvider;
231
-
232
- var placementEventMapping = parseSettingsString(
233
- settings.placementEventMapping
234
- );
235
- self.placementEventMappingLookup = generateMappedEventLookup(
236
- placementEventMapping
237
- );
238
-
239
- var placementEventAttributeMapping = parseSettingsString(
240
- settings.placementEventAttributeMapping
241
- );
242
- self.placementEventAttributeMappingLookup =
243
- generateMappedEventAttributeLookup(placementEventAttributeMapping);
244
-
245
- // Set dynamic OTHER_IDENTITY based on server settings
246
- // Convert to lowercase since server sends TitleCase (e.g., 'Other' -> 'other')
247
- if (settings.hashedEmailUserIdentityType) {
248
- mappedEmailSha256Key =
249
- settings.hashedEmailUserIdentityType.toLowerCase();
250
- }
251
-
252
- var domain = window.mParticle.Rokt.domain;
253
- var launcherOptions = mergeObjects(
254
- {},
255
- window.mParticle.Rokt.launcherOptions || {}
256
- );
257
- self.integrationName = generateIntegrationName(
258
- launcherOptions.integrationName
259
- );
260
- launcherOptions.integrationName = self.integrationName;
261
-
262
- self.domain = domain;
263
-
264
- // Register reporting services with the core SDK
265
- var reportingConfig = {
266
- loggingUrl: settings.loggingUrl,
267
- errorUrl: settings.errorUrl,
268
- isLoggingEnabled:
269
- settings.isLoggingEnabled === 'true' ||
270
- settings.isLoggingEnabled === true,
271
- };
272
- var errorReportingService = new ErrorReportingService(
273
- reportingConfig,
274
- self.integrationName,
275
- window.__rokt_li_guid__,
276
- settings.accountId
277
- );
278
- var loggingService = new LoggingService(
279
- reportingConfig,
280
- errorReportingService,
281
- self.integrationName,
282
- window.__rokt_li_guid__,
283
- settings.accountId
284
- );
285
-
286
- self.errorReportingService = errorReportingService;
287
- self.loggingService = loggingService;
288
-
289
- if (
290
- window.mParticle &&
291
- window.mParticle._registerErrorReportingService
292
- ) {
293
- window.mParticle._registerErrorReportingService(
294
- errorReportingService
295
- );
296
- }
297
- if (window.mParticle && window.mParticle._registerLoggingService) {
298
- window.mParticle._registerLoggingService(loggingService);
299
- }
300
-
301
- if (testMode) {
302
- self.testHelpers = {
303
- generateLauncherScript: generateLauncherScript,
304
- extractRoktExtensions: extractRoktExtensions,
305
- hashEventMessage: hashEventMessage,
306
- parseSettingsString: parseSettingsString,
307
- generateMappedEventLookup: generateMappedEventLookup,
308
- generateMappedEventAttributeLookup:
309
- generateMappedEventAttributeLookup,
310
- sendAdBlockMeasurementSignals: sendAdBlockMeasurementSignals,
311
- createAutoRemovedIframe: createAutoRemovedIframe,
312
- djb2: djb2,
313
- setAllowedOriginHashes: function (hashes) {
314
- _allowedOriginHashes = hashes;
315
- },
316
- ReportingTransport: ReportingTransport,
317
- ErrorReportingService: ErrorReportingService,
318
- LoggingService: LoggingService,
319
- RateLimiter: RateLimiter,
320
- ErrorCodes: ErrorCodes,
321
- WSDKErrorSeverity: WSDKErrorSeverity,
322
- };
323
- attachLauncher(accountId, launcherOptions);
324
- return;
325
- }
326
-
327
- if (isLauncherReadyToAttach()) {
328
- attachLauncher(accountId, launcherOptions);
329
- } else {
330
- var target = document.head || document.body;
331
- var script = document.createElement('script');
332
- script.type = 'text/javascript';
333
- script.src = generateLauncherScript(domain, roktExtensions);
334
- script.async = true;
335
- script.crossOrigin = 'anonymous';
336
- script.fetchPriority = 'high';
337
- script.id = 'rokt-launcher';
338
-
339
- script.onload = function () {
340
- if (isLauncherReadyToAttach()) {
341
- attachLauncher(accountId, launcherOptions);
342
- } else {
343
- console.error(
344
- 'Rokt object is not available after script load.'
345
- );
346
- }
347
- };
348
-
349
- script.onerror = function (error) {
350
- console.error('Error loading Rokt launcher script:', error);
351
- };
352
-
353
- target.appendChild(script);
354
- captureTiming(PerformanceMarks.RoktScriptAppended);
355
- }
356
- }
357
- /**
358
- * Returns the user identities from the filtered user, if any
359
- * @param {Object} filteredUser - The filtered user object containing identities
360
- * @returns {Object} The user identities from the filtered user
361
- */
362
- function returnUserIdentities(filteredUser) {
363
- if (!filteredUser || !filteredUser.getUserIdentities) {
364
- return {};
365
- }
366
-
367
- var userIdentities = filteredUser.getUserIdentities().userIdentities;
368
-
369
- return replaceOtherIdentityWithEmailsha256(userIdentities);
370
- }
371
-
372
- function returnLocalSessionAttributes() {
373
- if (
374
- !window.mParticle.Rokt ||
375
- typeof window.mParticle.Rokt.getLocalSessionAttributes !==
376
- 'function'
377
- ) {
378
- return {};
379
- }
380
- if (
381
- isEmpty(self.placementEventMappingLookup) &&
382
- isEmpty(self.placementEventAttributeMappingLookup)
383
- ) {
384
- return {};
385
- }
386
- return window.mParticle.Rokt.getLocalSessionAttributes();
387
- }
388
-
389
- function replaceOtherIdentityWithEmailsha256(userIdentities) {
390
- var newUserIdentities = mergeObjects({}, userIdentities || {});
391
- if (userIdentities[mappedEmailSha256Key]) {
392
- newUserIdentities[EMAIL_SHA256_KEY] =
393
- userIdentities[mappedEmailSha256Key];
394
- }
395
- delete newUserIdentities[mappedEmailSha256Key];
396
-
397
- return newUserIdentities;
398
- }
399
-
400
- /**
401
- * Selects placements for Rokt Web SDK with merged attributes, filters, and experimentation options
402
- * @see https://docs.rokt.com/developers/integration-guides/web/library/select-placements-options/
403
- * @param {Object} options - The options object for selecting placements containing:
404
- * - identifier {string}: The placement identifier
405
- * - attributes {Object}: Optional attributes to merge with existing attributes
406
- * @returns {Promise<void>} A Promise resolving to the Rokt launcher's selectPlacements method with processed attributes
407
- */
408
- function selectPlacements(options) {
409
- var attributes = (options && options.attributes) || {};
410
- var placementAttributes = mergeObjects(self.userAttributes, attributes);
411
-
412
- var filters = self.filters || {};
413
- var userAttributeFilters = filters.userAttributeFilters || [];
414
- var filteredUser = filters.filteredUser || {};
415
- var mpid =
416
- filteredUser &&
417
- filteredUser.getMPID &&
418
- typeof filteredUser.getMPID === 'function'
419
- ? filteredUser.getMPID()
420
- : null;
421
-
422
- var filteredAttributes;
423
-
424
- if (!filters) {
425
- console.warn(
426
- 'Rokt Kit: No filters available, using user attributes'
427
- );
428
-
429
- filteredAttributes = placementAttributes;
430
- } else if (filters.filterUserAttributes) {
431
- filteredAttributes = filters.filterUserAttributes(
432
- placementAttributes,
433
- userAttributeFilters
434
- );
435
- }
436
-
437
- self.userAttributes = filteredAttributes;
438
-
439
- var optimizelyAttributes =
440
- self.onboardingExpProvider === 'Optimizely'
441
- ? fetchOptimizely()
442
- : {};
443
-
444
- var filteredUserIdentities = returnUserIdentities(filteredUser);
445
-
446
- var localSessionAttributes = returnLocalSessionAttributes();
447
-
448
- var selectPlacementsAttributes = mergeObjects(
449
- filteredUserIdentities,
450
- filteredAttributes,
451
- optimizelyAttributes,
452
- localSessionAttributes,
453
- {
454
- mpid: mpid,
455
- }
456
- );
457
-
458
- var selectPlacementsOptions = mergeObjects(options, {
459
- attributes: selectPlacementsAttributes,
460
- });
461
-
462
- var selection = self.launcher.selectPlacements(selectPlacementsOptions);
463
-
464
- // After selection resolves, sync the Rokt session ID back to mParticle
465
- // as an integration attribute so server-side integrations can link events.
466
- // We log the custom event AFTER setting the attribute because
467
- // setIntegrationAttribute alone doesn't fire a network request —
468
- // if the user closes the page before another event fires, the server
469
- // would never receive the session ID.
470
- if (selection && typeof selection.then === 'function') {
471
- selection
472
- .then(function (sel) {
473
- if (sel && sel.context && sel.context.sessionId) {
474
- sel.context.sessionId
475
- .then(function (sessionId) {
476
- _setRoktSessionId(sessionId);
477
- logSelectPlacementsEvent(
478
- selectPlacementsAttributes
479
- );
480
- })
481
- .catch(function () {
482
- logSelectPlacementsEvent(
483
- selectPlacementsAttributes
484
- );
485
- });
486
- } else {
487
- logSelectPlacementsEvent(selectPlacementsAttributes);
488
- }
489
- })
490
- .catch(function () {
491
- logSelectPlacementsEvent(selectPlacementsAttributes);
492
- });
493
- } else {
494
- logSelectPlacementsEvent(selectPlacementsAttributes);
495
- }
496
-
497
- return selection;
498
- }
499
-
500
- /**
501
- * Logs a custom event when selectPlacements is called
502
- * This enables visibility and troubleshooting
503
- * @param {Object} attributes - The attributes sent to Rokt
504
- */
505
- function logSelectPlacementsEvent(attributes) {
506
- if (
507
- !window.mParticle ||
508
- typeof window.mParticle.logEvent !== 'function'
509
- ) {
510
- return;
511
- }
512
-
513
- if (!isObject(attributes)) {
514
- return;
515
- }
516
-
517
- var EVENT_TYPE_OTHER = window.mParticle.EventType.Other;
518
-
519
- window.mParticle.logEvent(
520
- EVENT_NAME_SELECT_PLACEMENTS,
521
- EVENT_TYPE_OTHER,
522
- attributes
523
- );
524
- }
525
-
526
- /**
527
- * Enables optional Integration Launcher extensions before selecting placements
528
- * @param {string} extensionName - Name of the extension to enable
529
- * @returns {Promise<*>} A Promise resolving to the extension API if available
530
- */
531
- function use(extensionName) {
532
- if (!isKitReady()) {
533
- console.error('Rokt Kit: Not initialized');
534
- return Promise.reject(new Error('Rokt Kit: Not initialized'));
535
- }
536
- if (!extensionName || !isString(extensionName)) {
537
- return Promise.reject(
538
- new Error('Rokt Kit: Invalid extension name')
539
- );
540
- }
541
- return self.launcher.use(extensionName);
542
- }
543
-
544
- /**
545
- * Sets extension data for Rokt Web SDK
546
- * @param {Object} partnerExtensionData - The extension data object containing:
547
- * - [extensionName] {string}: Name of the extension
548
- * - [extensionName].options {Object}: Key-value pairs of options for the extension
549
- * @returns {void} Nothing is returned
550
- */
551
- function setExtensionData(partnerExtensionData) {
552
- if (!isKitReady()) {
553
- console.error('Rokt Kit: Not initialized');
554
- return;
555
- }
556
-
557
- window.Rokt.setExtensionData(partnerExtensionData);
558
- }
559
-
560
- function processEventQueue() {
561
- self.eventQueue.forEach(function (event) {
562
- processEvent(event);
563
- });
564
- self.eventQueue = [];
565
- }
566
-
567
- function processEvent(event) {
568
- if (!isKitReady()) {
569
- self.eventQueue.push(event);
570
- return;
571
- }
572
-
573
- _sendEventStream(event);
574
-
575
- if (
576
- typeof window.mParticle.Rokt.setLocalSessionAttribute !== 'function'
577
- ) {
578
- return;
579
- }
580
-
581
- if (!isEmpty(self.placementEventAttributeMappingLookup)) {
582
- applyPlacementEventAttributeMapping(event);
583
- }
584
-
585
- if (isEmpty(self.placementEventMappingLookup)) {
586
- return;
587
- }
588
-
589
- var hashedEvent = hashEventMessage(
590
- event.EventDataType,
591
- event.EventCategory,
592
- event.EventName
593
- );
594
-
595
- if (self.placementEventMappingLookup[hashedEvent]) {
596
- var mappedValue = self.placementEventMappingLookup[hashedEvent];
597
- window.mParticle.Rokt.setLocalSessionAttribute(mappedValue, true);
598
- }
599
- }
600
-
601
- function _enrichEvent(event) {
602
- return mergeObjects({}, event, {
603
- UserAttributes: self.userAttributes,
604
- });
605
- }
606
-
607
- function _sendEventStream(event) {
608
- if (window.Rokt && typeof window.Rokt.__event_stream__ === 'function') {
609
- if (self.eventStreamQueue.length) {
610
- var queuedEvents = self.eventStreamQueue;
611
- self.eventStreamQueue = [];
612
- for (var i = 0; i < queuedEvents.length; i++) {
613
- window.Rokt.__event_stream__(_enrichEvent(queuedEvents[i]));
614
- }
615
- }
616
- window.Rokt.__event_stream__(_enrichEvent(event));
617
- } else {
618
- self.eventStreamQueue.push(event);
619
- }
620
- }
621
-
622
- function _setRoktSessionId(sessionId) {
623
- if (!sessionId || typeof sessionId !== 'string') {
624
- return;
625
- }
626
- try {
627
- var mpInstance = window.mParticle.getInstance();
628
- if (
629
- mpInstance &&
630
- typeof mpInstance.setIntegrationAttribute === 'function'
631
- ) {
632
- mpInstance.setIntegrationAttribute(moduleId, {
633
- roktSessionId: sessionId,
634
- });
635
- }
636
- } catch (e) {
637
- // Best effort — never let this break the partner page
638
- }
639
- }
640
-
641
- function onUserIdentified(filteredUser) {
642
- self.filters.filteredUser = filteredUser;
643
- self.userAttributes = filteredUser.getAllUserAttributes();
644
- _sendEventStream(_buildIdentityEvent('identify', filteredUser));
645
- }
646
-
647
- function _buildIdentityEvent(eventName, filteredUser) {
648
- var mpid =
649
- filteredUser.getMPID && typeof filteredUser.getMPID === 'function'
650
- ? filteredUser.getMPID()
651
- : null;
652
- var sessionId =
653
- window.mParticle &&
654
- window.mParticle.sessionManager &&
655
- typeof window.mParticle.sessionManager.getSession === 'function'
656
- ? window.mParticle.sessionManager.getSession()
657
- : null;
658
- var userIdentities =
659
- filteredUser.getUserIdentities &&
660
- typeof filteredUser.getUserIdentities === 'function'
661
- ? filteredUser.getUserIdentities().userIdentities
662
- : null;
663
-
664
- return {
665
- EventName: eventName,
666
- EventDataType: 14, // MessageType.Profile
667
- Timestamp: Date.now(),
668
- MPID: mpid,
669
- SessionId: sessionId,
670
- UserIdentities: userIdentities,
671
- };
672
- }
673
-
674
- function onLoginComplete(filteredUser) {
675
- self.userAttributes = filteredUser.getAllUserAttributes();
676
- _sendEventStream(_buildIdentityEvent('login', filteredUser));
677
- }
678
-
679
- function onLogoutComplete(filteredUser) {
680
- self.userAttributes = filteredUser.getAllUserAttributes();
681
- _sendEventStream(_buildIdentityEvent('logout', filteredUser));
682
- }
683
-
684
- function onModifyComplete(filteredUser) {
685
- self.userAttributes = filteredUser.getAllUserAttributes();
686
- _sendEventStream(_buildIdentityEvent('modify_user', filteredUser));
687
- }
688
-
689
- function setUserAttribute(key, value) {
690
- self.userAttributes[key] = value;
691
- _sendEventStream(
692
- _buildIdentityEvent(
693
- 'set_user_attributes',
694
- self.filters.filteredUser || {}
695
- )
696
- );
697
- }
698
-
699
- function removeUserAttribute(key) {
700
- delete self.userAttributes[key];
701
- }
702
-
703
- function attachLauncher(accountId, launcherOptions) {
704
- var mpSessionId =
705
- window.mParticle &&
706
- window.mParticle.sessionManager &&
707
- typeof window.mParticle.sessionManager.getSession === 'function'
708
- ? window.mParticle.sessionManager.getSession()
709
- : undefined;
710
-
711
- var options = mergeObjects(
712
- {
713
- accountId: accountId,
714
- },
715
- launcherOptions || {},
716
- mpSessionId ? { mpSessionId: mpSessionId } : {}
717
- );
718
-
719
- if (isPartnerInLocalLauncherTestGroup()) {
720
- var localLauncher = window.Rokt.createLocalLauncher(options);
721
- initRoktLauncher(localLauncher);
722
- } else {
723
- window.Rokt.createLauncher(options)
724
- .then(initRoktLauncher)
725
- .catch(function (err) {
726
- console.error('Error creating Rokt launcher:', err);
727
- });
728
- }
729
- }
730
-
731
- function initRoktLauncher(launcher) {
732
- // Assign the launcher to a global variable for later access
733
- window.Rokt.currentLauncher = launcher;
734
- // Locally cache the launcher and filters
735
- self.launcher = launcher;
736
-
737
- var roktFilters = window.mParticle.Rokt.filters;
738
-
739
- if (!roktFilters) {
740
- console.warn('Rokt Kit: No filters have been set.');
741
- } else {
742
- self.filters = roktFilters;
743
- if (!roktFilters.filteredUser) {
744
- console.warn('Rokt Kit: No filtered user has been set.');
745
- }
746
- }
747
-
748
- // Kit must be initialized before attaching to the Rokt manager
749
- self.isInitialized = true;
750
-
751
- sendAdBlockMeasurementSignals(self.domain, self.integrationName);
752
-
753
- // Attaches the kit to the Rokt manager
754
- window.mParticle.Rokt.attachKit(self);
755
- processEventQueue();
756
- }
757
-
758
- // mParticle Kit Callback Methods
759
- function fetchOptimizely() {
760
- var forwarders = window.mParticle
761
- ._getActiveForwarders()
762
- .filter(function (forwarder) {
763
- return forwarder.name === 'Optimizely';
764
- });
765
-
766
- try {
767
- if (forwarders.length > 0 && window.optimizely) {
768
- // Get the state object
769
- var optimizelyState = window.optimizely.get('state');
770
- if (
771
- !optimizelyState ||
772
- !optimizelyState.getActiveExperimentIds
773
- ) {
774
- return {};
775
- }
776
- // Get active experiment IDs
777
- var activeExperimentIds =
778
- optimizelyState.getActiveExperimentIds();
779
- // Get variations for each active experiment
780
- var activeExperiments = activeExperimentIds.reduce(function (
781
- acc,
782
- expId
783
- ) {
784
- acc[
785
- 'rokt.custom.optimizely.experiment.' +
786
- expId +
787
- '.variationId'
788
- ] = optimizelyState.getVariationMap()[expId].id;
789
- return acc;
790
- },
791
- {});
792
- return activeExperiments;
793
- }
794
- } catch (error) {
795
- console.error('Error fetching Optimizely attributes:', error);
796
- }
797
- return {};
798
- }
799
-
800
- // Called by the mParticle Rokt Manager
801
- this.selectPlacements = selectPlacements;
802
- this.hashAttributes = hashAttributes;
803
- this.use = use;
804
-
805
- // Kit Callback Methods
806
- this.init = initForwarder;
807
- this.process = processEvent;
808
- this.setExtensionData = setExtensionData;
809
- this.setUserAttribute = setUserAttribute;
810
- this.onUserIdentified = onUserIdentified;
811
- this.onLoginComplete = onLoginComplete;
812
- this.onLogoutComplete = onLogoutComplete;
813
- this.onModifyComplete = onModifyComplete;
814
- this.removeUserAttribute = removeUserAttribute;
815
-
816
- /**
817
- * Checks if the Rokt kit is ready to use.
818
- * Both conditions must be true:
819
- * 1. self.isInitialized - Set after successful initialization of the kit
820
- * 2. self.launcher - The Rokt launcher instance must be available
821
- * @returns {boolean} Whether the kit is ready for use
822
- */
823
- function isKitReady() {
824
- return !!(self.isInitialized && self.launcher);
825
- }
826
-
827
- function isPartnerInLocalLauncherTestGroup() {
828
- return (
829
- window.mParticle.config &&
830
- window.mParticle.config.isLocalLauncherEnabled &&
831
- _isAssignedToSampleGroup()
832
- );
833
- }
834
-
835
- function _isAssignedToSampleGroup() {
836
- var LOCAL_LAUNCHER_TEST_GROUP_THRESHOLD = 0.5;
837
- return Math.random() > LOCAL_LAUNCHER_TEST_GROUP_THRESHOLD;
838
- }
839
-
840
- function captureTiming(metricName) {
841
- if (
842
- window &&
843
- window.mParticle &&
844
- window.mParticle.captureTiming &&
845
- metricName
846
- ) {
847
- window.mParticle.captureTiming(metricName);
848
- }
849
- }
850
-
851
- function createAutoRemovedIframe(src) {
852
- var iframe = document.createElement('iframe');
853
- iframe.style.display = 'none';
854
- iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin');
855
- iframe.src = src;
856
- iframe.onload = function () {
857
- iframe.onload = null;
858
- if (iframe.parentNode) {
859
- iframe.parentNode.removeChild(iframe);
860
- }
861
- };
862
- var target = document.body || document.head;
863
- if (target) {
864
- target.appendChild(iframe);
865
- }
866
- }
867
-
868
- var ADBLOCK_CONTROL_DOMAIN = 'apps.roktecommerce.com';
869
- var INIT_LOG_SAMPLING_RATE = 0.1;
870
- var _allowedOriginHashes = [-553112570, 549508659];
871
-
872
- function djb2(str) {
873
- var hash = 5381;
874
- for (var i = 0; i < str.length; i++) {
875
- hash = (hash << 5) + hash + str.charCodeAt(i);
876
- hash = hash & hash;
877
- }
878
- return hash;
879
- }
880
-
881
- function sendAdBlockMeasurementSignals(domain, version) {
882
- var originHash = djb2(window.location.origin);
883
- if (_allowedOriginHashes.indexOf(originHash) === -1) {
884
- return;
885
- }
886
-
887
- if (Math.random() >= INIT_LOG_SAMPLING_RATE) {
888
- return;
889
- }
890
-
891
- var guid = window.__rokt_li_guid__;
892
- if (!guid) {
893
- return;
894
- }
895
-
896
- var pageUrl = window.location.href.split('?')[0].split('#')[0];
897
- var params =
898
- 'version=' +
899
- encodeURIComponent(version) +
900
- '&launcherInstanceGuid=' +
901
- encodeURIComponent(guid) +
902
- '&pageUrl=' +
903
- encodeURIComponent(pageUrl);
904
-
905
- var existingDomain = domain || 'apps.rokt.com';
906
- createAutoRemovedIframe(
907
- 'https://' + existingDomain + '/v1/wsdk-init/index.html?' + params
908
- );
909
-
910
- createAutoRemovedIframe(
911
- 'https://' +
912
- ADBLOCK_CONTROL_DOMAIN +
913
- '/v1/wsdk-init/index.html?' +
914
- params +
915
- '&isControl=true'
916
- );
917
- }
918
- };
919
-
920
- function generateIntegrationName(customIntegrationName) {
921
- var coreSdkVersion = window.mParticle.getVersion();
922
- var kitVersion = "1.22.0";
923
- var name = 'mParticle_' + 'wsdkv_' + coreSdkVersion + '_kitv_' + kitVersion;
924
-
925
- if (customIntegrationName) {
926
- name += '_' + customIntegrationName;
927
- }
928
- return name;
929
- }
930
-
931
- function getId() {
932
- return moduleId;
933
- }
934
-
935
- function register(config) {
936
- if (!config) {
937
- window.console.log(
938
- 'You must pass a config object to register the kit ' + name
939
- );
940
- return;
941
- }
942
- if (!isObject(config)) {
943
- window.console.log(
944
- "'config' must be an object. You passed in a " + typeof config
945
- );
946
- return;
947
- }
948
-
949
- if (isObject(config.kits)) {
950
- config.kits[name] = {
951
- constructor: constructor,
952
- };
953
- } else {
954
- config.kits = {};
955
- config.kits[name] = {
956
- constructor: constructor,
957
- };
958
- }
959
- window.console.log(
960
- 'Successfully registered ' + name + ' to your mParticle configuration'
961
- );
962
- }
963
-
964
- function isObject(val) {
965
- return (
966
- val != null && typeof val === 'object' && Array.isArray(val) === false
967
- );
968
- }
969
-
970
- function mergeObjects() {
971
- var resObj = {};
972
- for (var i = 0; i < arguments.length; i += 1) {
973
- var obj = arguments[i],
974
- keys = Object.keys(obj);
975
- for (var j = 0; j < keys.length; j += 1) {
976
- resObj[keys[j]] = obj[keys[j]];
977
- }
978
- }
979
- return resObj;
980
- }
981
-
982
- function parseSettingsString(settingsString) {
983
- if (!settingsString) {
984
- return [];
985
- }
986
- try {
987
- return JSON.parse(settingsString.replace(/&quot;/g, '"'));
988
- } catch (error) {
989
- console.error('Settings string contains invalid JSON');
990
- }
991
- return [];
992
- }
993
-
994
- function extractRoktExtensions(settingsString) {
995
- var settings = settingsString ? parseSettingsString(settingsString) : [];
996
- var roktExtensions = [];
997
-
998
- for (var i = 0; i < settings.length; i++) {
999
- roktExtensions.push(settings[i].value);
1000
- }
1001
-
1002
- return roktExtensions;
1003
- }
1004
-
1005
- function generateMappedEventLookup(placementEventMapping) {
1006
- if (!placementEventMapping) {
1007
- return {};
1008
- }
1009
-
1010
- var mappedEvents = {};
1011
- for (var i = 0; i < placementEventMapping.length; i++) {
1012
- var mapping = placementEventMapping[i];
1013
- mappedEvents[mapping.jsmap] = mapping.value;
1014
- }
1015
- return mappedEvents;
1016
- }
1017
-
1018
- function hashEventMessage(messageType, eventType, eventName) {
1019
- return window.mParticle.generateHash(
1020
- [messageType, eventType, eventName].join('')
1021
- );
1022
- }
1023
-
1024
- function isEmpty(value) {
1025
- return value == null || !(Object.keys(value) || value).length;
1026
- }
1027
-
1028
- function isString(value) {
1029
- return typeof value === 'string';
1030
- }
1031
-
1032
- // --- Reporting Services ---
1033
-
1034
- var ErrorCodes = {
1035
- UNKNOWN_ERROR: 'UNKNOWN_ERROR',
1036
- UNHANDLED_EXCEPTION: 'UNHANDLED_EXCEPTION',
1037
- IDENTITY_REQUEST: 'IDENTITY_REQUEST',
1038
- };
1039
-
1040
- var WSDKErrorSeverity = {
1041
- ERROR: 'ERROR',
1042
- INFO: 'INFO',
1043
- WARNING: 'WARNING',
1044
- };
1045
-
1046
- var DEFAULT_LOGGING_URL = 'apps.rokt-api.com/v1/log';
1047
- var DEFAULT_ERROR_URL = 'apps.rokt-api.com/v1/errors';
1048
- var RATE_LIMIT_PER_SEVERITY = 10;
1049
-
1050
- function RateLimiter() {
1051
- this._logCount = {};
1052
- }
1053
-
1054
- RateLimiter.prototype.incrementAndCheck = function (severity) {
1055
- var count = this._logCount[severity] || 0;
1056
- var newCount = count + 1;
1057
- this._logCount[severity] = newCount;
1058
- return newCount > RATE_LIMIT_PER_SEVERITY;
1059
- };
1060
-
1061
- // --- ReportingTransport: shared transport layer for reporting services ---
1062
-
1063
- function ReportingTransport(
1064
- config,
1065
- integrationName,
1066
- launcherInstanceGuid,
1067
- accountId,
1068
- rateLimiter
1069
- ) {
1070
- var self = this;
1071
- self._isLoggingEnabled = (config && config.isLoggingEnabled) || false;
1072
- self._integrationName = integrationName || '';
1073
- self._launcherInstanceGuid = launcherInstanceGuid;
1074
- self._accountId = accountId || null;
1075
- self._rateLimiter = rateLimiter || new RateLimiter();
1076
- self._reporter = 'mp-wsdk';
1077
- self._isEnabled = _isReportingEnabled(self);
1078
- }
1079
-
1080
- ReportingTransport.prototype.send = function (
1081
- url,
1082
- severity,
1083
- msg,
1084
- code,
1085
- stackTrace,
1086
- onError
1087
- ) {
1088
- if (!this._isEnabled || this._rateLimiter.incrementAndCheck(severity)) {
1089
- return;
1090
- }
1091
-
1092
- try {
1093
- var logRequest = {
1094
- additionalInformation: {
1095
- message: msg,
1096
- version: this._integrationName || '',
1097
- },
1098
- severity: severity,
1099
- code: code || ErrorCodes.UNKNOWN_ERROR,
1100
- url: _getUrl(),
1101
- deviceInfo: _getUserAgent(),
1102
- stackTrace: stackTrace,
1103
- reporter: this._reporter,
1104
- integration: this._integrationName || '',
1105
- };
1106
- var headers = {
1107
- Accept: 'text/plain;charset=UTF-8',
1108
- 'Content-Type': 'application/json',
1109
- 'rokt-launcher-version': this._integrationName || '',
1110
- 'rokt-wsdk-version': 'joint',
1111
- };
1112
- if (this._launcherInstanceGuid) {
1113
- headers['rokt-launcher-instance-guid'] = this._launcherInstanceGuid;
1114
- }
1115
- if (this._accountId) {
1116
- headers['rokt-account-id'] = this._accountId;
1117
- }
1118
- var payload = {
1119
- method: 'POST',
1120
- headers: headers,
1121
- body: JSON.stringify(logRequest),
1122
- };
1123
- fetch(url, payload).catch(function (error) {
1124
- console.error('ReportingTransport: Failed to send log', error);
1125
- if (onError) {
1126
- onError(error);
1127
- }
1128
- });
1129
- } catch (error) {
1130
- console.error('ReportingTransport: Failed to send log', error);
1131
- if (onError) {
1132
- onError(error);
1133
- }
1134
- }
1135
- };
1136
-
1137
- function _isReportingEnabled(transport) {
1138
- return (
1139
- _isDebugModeEnabled() ||
1140
- (_isRoktDomainPresent() && transport._isLoggingEnabled)
1141
- );
1142
- }
1143
-
1144
- function _isRoktDomainPresent() {
1145
- return typeof window !== 'undefined' && Boolean(window['ROKT_DOMAIN']);
1146
- }
1147
-
1148
- function _isDebugModeEnabled() {
1149
- return (
1150
- typeof window !== 'undefined' &&
1151
- window.location &&
1152
- window.location.search &&
1153
- window.location.search
1154
- .toLowerCase()
1155
- .indexOf('mp_enable_logging=true') !== -1
1156
- );
1157
- }
1158
-
1159
- function _getUrl() {
1160
- return typeof window !== 'undefined' && window.location
1161
- ? window.location.href
1162
- : undefined;
1163
- }
1164
-
1165
- function _getUserAgent() {
1166
- return typeof window !== 'undefined' && window.navigator
1167
- ? window.navigator.userAgent
1168
- : undefined;
1169
- }
1170
-
1171
- // --- ErrorReportingService: handles ERROR and WARNING severity ---
1172
-
1173
- function ErrorReportingService(
1174
- config,
1175
- integrationName,
1176
- launcherInstanceGuid,
1177
- accountId,
1178
- rateLimiter
1179
- ) {
1180
- this._transport = new ReportingTransport(
1181
- config,
1182
- integrationName,
1183
- launcherInstanceGuid,
1184
- accountId,
1185
- rateLimiter
1186
- );
1187
- this._errorUrl =
1188
- 'https://' + ((config && config.errorUrl) || DEFAULT_ERROR_URL);
1189
- }
1190
-
1191
- ErrorReportingService.prototype.report = function (error) {
1192
- if (!error) {
1193
- return;
1194
- }
1195
- var severity = error.severity || WSDKErrorSeverity.ERROR;
1196
- this._transport.send(
1197
- this._errorUrl,
1198
- severity,
1199
- error.message,
1200
- error.code,
1201
- error.stackTrace
1202
- );
1203
- };
1204
-
1205
- // --- LoggingService: handles INFO severity ---
1206
-
1207
- function LoggingService(
1208
- config,
1209
- errorReportingService,
1210
- integrationName,
1211
- launcherInstanceGuid,
1212
- accountId,
1213
- rateLimiter
1214
- ) {
1215
- this._transport = new ReportingTransport(
1216
- config,
1217
- integrationName,
1218
- launcherInstanceGuid,
1219
- accountId,
1220
- rateLimiter
1221
- );
1222
- this._loggingUrl =
1223
- 'https://' + ((config && config.loggingUrl) || DEFAULT_LOGGING_URL);
1224
- this._errorReportingService = errorReportingService;
1225
- }
1226
-
1227
- LoggingService.prototype.log = function (entry) {
1228
- if (!entry) {
1229
- return;
1230
- }
1231
- var self = this;
1232
- self._transport.send(
1233
- self._loggingUrl,
1234
- WSDKErrorSeverity.INFO,
1235
- entry.message,
1236
- entry.code,
1237
- undefined,
1238
- function (error) {
1239
- if (self._errorReportingService) {
1240
- self._errorReportingService.report({
1241
- message:
1242
- 'LoggingService: Failed to send log: ' + error.message,
1243
- code: ErrorCodes.UNKNOWN_ERROR,
1244
- severity: WSDKErrorSeverity.ERROR,
1245
- });
1246
- }
1247
- }
1248
- );
1249
- };
1250
-
1251
- if (window && window.mParticle && window.mParticle.addForwarder) {
1252
- window.mParticle.addForwarder({
1253
- name: name,
1254
- constructor: constructor,
1255
- getId: getId,
1256
- });
1257
- }
1258
-
1259
- var RoktKit = {
1260
- register: register,
1261
- ReportingTransport: ReportingTransport,
1262
- ErrorReportingService: ErrorReportingService,
1263
- LoggingService: LoggingService,
1264
- RateLimiter: RateLimiter,
1265
- ErrorCodes: ErrorCodes,
1266
- WSDKErrorSeverity: WSDKErrorSeverity,
1267
- };
1268
- var RoktKit_1 = RoktKit.register;
1269
- var RoktKit_2 = RoktKit.ReportingTransport;
1270
- var RoktKit_3 = RoktKit.ErrorReportingService;
1271
- var RoktKit_4 = RoktKit.LoggingService;
1272
- var RoktKit_5 = RoktKit.RateLimiter;
1273
- var RoktKit_6 = RoktKit.ErrorCodes;
1274
- var RoktKit_7 = RoktKit.WSDKErrorSeverity;
1275
-
1276
- exports.ErrorCodes = RoktKit_6;
1277
- exports.ErrorReportingService = RoktKit_3;
1278
- exports.LoggingService = RoktKit_4;
1279
- exports.RateLimiter = RoktKit_5;
1280
- exports.ReportingTransport = RoktKit_2;
1281
- exports.WSDKErrorSeverity = RoktKit_7;
1282
- exports.default = RoktKit;
1283
- exports.register = RoktKit_1;
1284
-
1285
- return exports;
1286
-
1287
- }({}));
1
+ var RoktKit=(function(I){"use strict";const c="Rokt",H="selectPlacements",F="apps.roktecommerce.com",S={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST"},R={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"},z="apps.rokt-api.com/v1/log",Q="apps.rokt-api.com/v1/errors",B=10;function o(){return window.mParticle}function U(n,t){const s=["https://",typeof n<"u"?n:"apps.rokt.com","/wsdk/integrations/launcher.js"].join("");return!t||t.length===0?s:s+"?extensions="+t.join(",")}function k(n){return n!=null&&typeof n=="object"&&Array.isArray(n)===!1}function A(n){if(!n)return[];try{return JSON.parse(n.replace(/&quot;/g,'"'))}catch{console.error("Settings string contains invalid JSON")}return[]}function T(n){const t=n?A(n):[],e=[];for(let i=0;i<t.length;i++)e.push(t[i].value);return e}function M(n){if(!n)return{};const t={};for(let e=0;e<n.length;e++){const i=n[e];t[i.jsmap]=i.value}return t}function P(n){const t={};if(!Array.isArray(n))return t;for(let e=0;e<n.length;e++){const i=n[e];if(!i||!_(i.value)||!_(i.map))continue;const r=i.value,s=i.map;t[r]||(t[r]=[]),t[r].push({eventAttributeKey:s,conditions:Array.isArray(i.conditions)?i.conditions:[]})}return t}function C(n,t,e){return o().generateHash([n,t,e].join(""))}function E(n){return n==null?!0:typeof n=="object"?Object.keys(n).length===0:Array.isArray(n)?n.length===0:!1}function _(n){return typeof n=="string"}function V(n){let i="mParticle_wsdkv_"+o().getVersion()+"_kitv_"+"1.24.0";return n&&(i+="_"+n),i}function K(n){let t=5381;for(let e=0;e<n.length;e++)t=(t<<5)+t+n.charCodeAt(e),t=t&t;return t}function L(n){const t=document.createElement("iframe");t.style.display="none",t.setAttribute("sandbox","allow-scripts allow-same-origin"),t.src=n,t.onload=function(){t.onload=null,t.parentNode&&t.parentNode.removeChild(t)};const e=document.body||document.head;e&&e.appendChild(t)}function D(n,t){const e=K(window.location.origin);if(g._allowedOriginHashes.indexOf(e)===-1||Math.random()>=.1)return;const r=window.__rokt_li_guid__;if(!r)return;const s=window.location.href.split("?")[0].split("#")[0],a="version="+encodeURIComponent(t??"")+"&launcherInstanceGuid="+encodeURIComponent(r)+"&pageUrl="+encodeURIComponent(s);L("https://"+(n||"apps.rokt.com")+"/v1/wsdk-init/index.html?"+a),L("https://"+F+"/v1/wsdk-init/index.html?"+a+"&isControl=true")}function Y(){return typeof window<"u"&&!!window.ROKT_DOMAIN}function W(){return typeof window<"u"&&!!window.location?.search?.toLowerCase().includes("mp_enable_logging=true")}function q(){return typeof window<"u"?window.location?.href:void 0}function J(){return typeof window<"u"?window.navigator?.userAgent:void 0}class x{constructor(){this._logCount={}}incrementAndCheck(t){const i=(this._logCount[t]||0)+1;return this._logCount[t]=i,i>B}}class N{constructor(t,e,i,r,s){this._reporter="mp-wsdk";const a=t?.isLoggingEnabled===!0||t?.isLoggingEnabled==="true";this._integrationName=e||"",this._launcherInstanceGuid=i,this._accountId=r||null,this._rateLimiter=s||new x,this._isEnabled=W()||Y()&&a}send(t,e,i,r,s,a){if(!(!this._isEnabled||this._rateLimiter.incrementAndCheck(e)))try{const u={additionalInformation:{message:i,version:this._integrationName},severity:e,code:r||S.UNKNOWN_ERROR,url:q(),deviceInfo:J(),stackTrace:s,reporter:this._reporter,integration:this._integrationName},l={Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","rokt-launcher-version":this._integrationName,"rokt-wsdk-version":"joint"};this._launcherInstanceGuid&&(l["rokt-launcher-instance-guid"]=this._launcherInstanceGuid),this._accountId&&(l["rokt-account-id"]=this._accountId),fetch(t,{method:"POST",headers:l,body:JSON.stringify(u)}).catch(f=>{console.error("ReportingTransport: Failed to send log",f),a&&a(f)})}catch(u){console.error("ReportingTransport: Failed to send log",u),a&&a(u)}}}class j{constructor(t,e,i,r,s){this._transport=new N(t,e,i,r,s),this._errorUrl="https://"+(t?.errorUrl||Q)}report(t){if(!t)return;const e=t.severity||R.ERROR;this._transport.send(this._errorUrl,e,t.message,t.code,t.stackTrace)}}class G{constructor(t,e,i,r,s,a){this._transport=new N(t,i,r,s,a),this._loggingUrl="https://"+(t?.loggingUrl||z),this._errorReportingService=e}log(t){t&&this._transport.send(this._loggingUrl,R.INFO,t.message,t.code,void 0,e=>{this._errorReportingService&&this._errorReportingService.report({message:"LoggingService: Failed to send log: "+e.message,code:S.UNKNOWN_ERROR,severity:R.ERROR})})}}const h=class h{constructor(){this.name=c,this.id=181,this.moduleId=181,this.isInitialized=!1,this.launcher=null,this.filters={},this.userAttributes={},this.testHelpers=null,this.placementEventMappingLookup={},this.placementEventAttributeMappingLookup={},this.batchQueue=[],this.batchStreamQueue=[],this.pendingIdentityEvents=[],this.integrationName=null,this.errorReportingService=null,this.loggingService=null}getEventAttributeValue(t,e){const i=t&&t.EventAttributes;return!i||typeof i[e]>"u"?null:i[e]}doesEventAttributeConditionMatch(t,e){if(!t||!_(t.operator))return!1;const i=t.operator.toLowerCase(),r=t.attributeValue;return i==="exists"?e!==null:e==null?!1:i==="equals"?String(e)===String(r):i==="contains"?String(e).indexOf(String(r))!==-1:!1}doesEventMatchRule(t,e){if(!e||!_(e.eventAttributeKey))return!1;const i=e.conditions;if(!Array.isArray(i))return!1;const r=this.getEventAttributeValue(t,e.eventAttributeKey);if(i.length===0)return r!==null;for(let s=0;s<i.length;s++)if(!this.doesEventAttributeConditionMatch(i[s],r))return!1;return!0}applyPlacementEventAttributeMapping(t){const e=Object.keys(this.placementEventAttributeMappingLookup);for(let i=0;i<e.length;i++){const r=e[i],s=this.placementEventAttributeMappingLookup[r];if(E(s))continue;let a=!0;for(let u=0;u<s.length;u++)if(!this.doesEventMatchRule(t,s[u])){a=!1;break}a&&o().Rokt.setLocalSessionAttribute?.(r,!0)}}isLauncherReadyToAttach(){return!!window.Rokt&&typeof window.Rokt.createLauncher=="function"}returnUserIdentities(t){if(!t||!t.getUserIdentities)return{};const e=t.getUserIdentities().userIdentities;return this.replaceOtherIdentityWithEmailsha256(e)}returnLocalSessionAttributes(){return!o().Rokt||typeof o().Rokt.getLocalSessionAttributes!="function"?{}:E(this.placementEventMappingLookup)&&E(this.placementEventAttributeMappingLookup)?{}:o().Rokt.getLocalSessionAttributes()}replaceOtherIdentityWithEmailsha256(t){const e={...t||{}},i=this._mappedEmailSha256Key;return i&&t[i]&&(e[h.EMAIL_SHA256_KEY]=t[i]),i&&delete e[i],e}logSelectPlacementsEvent(t){if(!window.mParticle||typeof o().logEvent!="function"||!k(t))return;const e=o().EventType.Other;o().logEvent(H,e,t)}buildIdentityEvent(t,e){const i=e.getMPID(),r=o()&&o().sessionManager&&typeof o().sessionManager.getSession=="function"?o().sessionManager.getSession():null,s=e.getUserIdentities&&typeof e.getUserIdentities=="function"?e.getUserIdentities().userIdentities:null;return{EventName:t,EventDataType:14,EventCategory:0,Timestamp:Date.now(),MPID:i,SessionId:r,UserIdentities:s}}mergePendingIdentityEvents(t){if(this.pendingIdentityEvents.length===0)return t;const e={...t,events:[...t.events??[],...this.pendingIdentityEvents]};return this.pendingIdentityEvents=[],e}drainBatchQueue(){this.batchQueue.forEach(t=>{this.processBatch(t)}),this.batchQueue=[]}processBatch(t){return this.isKitReady()?(this.sendBatchStream(this.mergePendingIdentityEvents(t)),"Successfully sent batch to forwarder: "+c):(this.batchQueue.push(t),"Batch queued for forwarder: "+c)}sendBatchStream(t){if(window.Rokt&&typeof window.Rokt.__batch_stream__=="function"){if(this.batchStreamQueue.length){const e=this.batchStreamQueue;this.batchStreamQueue=[];for(let i=0;i<e.length;i++)window.Rokt.__batch_stream__(e[i])}window.Rokt.__batch_stream__(t)}else this.batchStreamQueue.push(t)}setRoktSessionId(t){if(!(!t||typeof t!="string"))try{const e=o().getInstance();e&&typeof e.setIntegrationAttribute=="function"&&e.setIntegrationAttribute(181,{roktSessionId:t})}catch{}}attachLauncher(t,e){const i=o()&&o().sessionManager&&typeof o().sessionManager.getSession=="function"?o().sessionManager.getSession():void 0,r={accountId:t,...e||{},...i?{mpSessionId:i}:{}};if(this.isPartnerInLocalLauncherTestGroup()){const s=window.Rokt.createLocalLauncher(r);this.initRoktLauncher(s)}else window.Rokt.createLauncher(r).then(s=>this.initRoktLauncher(s)).catch(s=>{console.error("Error creating Rokt launcher:",s)})}initRoktLauncher(t){window.Rokt&&(window.Rokt.currentLauncher=t),this.launcher=t;const e=o().Rokt?.filters;e?(this.filters=e,e.filteredUser||console.warn("Rokt Kit: No filtered user has been set.")):console.warn("Rokt Kit: No filters have been set."),this.isInitialized=!0,D(this.domain,this.integrationName),o().Rokt.attachKit(this),this.drainBatchQueue()}fetchOptimizely(){const t=o()._getActiveForwarders().filter(e=>e.name==="Optimizely");try{if(t.length>0&&window.optimizely){const e=window.optimizely.get("state");return!e||!e.getActiveExperimentIds?{}:e.getActiveExperimentIds().reduce((s,a)=>(s["rokt.custom.optimizely.experiment."+a+".variationId"]=e.getVariationMap()[a].id,s),{})}}catch(e){console.error("Error fetching Optimizely attributes:",e)}return{}}isKitReady(){return!!(this.isInitialized&&this.launcher)}isPartnerInLocalLauncherTestGroup(){return!!(o().config&&o().config.isLocalLauncherEnabled&&this.isAssignedToSampleGroup())}isAssignedToSampleGroup(){return Math.random()>.5}captureTiming(t){window&&o()&&o().captureTiming&&t&&o().captureTiming(t)}init(t,e,i,r,s){const a=t,u=a.accountId,l=T(a.roktExtensions);this.userAttributes=s||{},this._onboardingExpProvider=a.onboardingExpProvider;const f=A(a.placementEventMapping);this.placementEventMappingLookup=M(f);const O=A(a.placementEventAttributeMapping);this.placementEventAttributeMappingLookup=P(O),a.hashedEmailUserIdentityType&&(this._mappedEmailSha256Key=a.hashedEmailUserIdentityType.toLowerCase());const b=o().Rokt?.domain,p={...o().Rokt?.launcherOptions||{}};this.integrationName=V(p.integrationName),p.integrationName=this.integrationName,this.domain=b;const v={loggingUrl:a.loggingUrl,errorUrl:a.errorUrl,isLoggingEnabled:a.isLoggingEnabled==="true"||a.isLoggingEnabled===!0},m=new j(v,this.integrationName,window.__rokt_li_guid__,a.accountId),w=new G(v,m,this.integrationName,window.__rokt_li_guid__,a.accountId);if(this.errorReportingService=m,this.loggingService=w,o()._registerErrorReportingService&&o()._registerErrorReportingService(m),o()._registerLoggingService&&o()._registerLoggingService(w),i)return this.testHelpers={generateLauncherScript:U,extractRoktExtensions:T,hashEventMessage:C,parseSettingsString:A,generateMappedEventLookup:M,generateMappedEventAttributeLookup:P,sendAdBlockMeasurementSignals:D,createAutoRemovedIframe:L,djb2:K,setAllowedOriginHashes:y=>{h._allowedOriginHashes=y},ReportingTransport:N,ErrorReportingService:j,LoggingService:G,RateLimiter:x,ErrorCodes:S,WSDKErrorSeverity:R},this.attachLauncher(u,p),"Successfully initialized: "+c;if(this.isLauncherReadyToAttach())this.attachLauncher(u,p);else{const y=document.head||document.body,d=document.createElement("script");d.type="text/javascript",d.src=U(b,l),d.async=!0,d.crossOrigin="anonymous",d.fetchPriority="high",d.id="rokt-launcher",d.onload=()=>{this.isLauncherReadyToAttach()?this.attachLauncher(u,p):console.error("Rokt object is not available after script load.")},d.onerror=$=>{console.error("Error loading Rokt launcher script:",$)},y.appendChild(d),this.captureTiming(h.PERFORMANCE_MARKS.RoktScriptAppended)}return"Successfully initialized: "+c}process(t){if(!this.isKitReady())return"Kit not ready for forwarder: "+c;if(typeof o().Rokt?.setLocalSessionAttribute=="function"&&(E(this.placementEventAttributeMappingLookup)||this.applyPlacementEventAttributeMapping(t),!E(this.placementEventMappingLookup))){const e=C(t.EventDataType,t.EventCategory,t.EventName??"");this.placementEventMappingLookup[String(e)]&&o().Rokt.setLocalSessionAttribute?.(this.placementEventMappingLookup[String(e)],!0)}return"Successfully sent to forwarder: "+c}setExtensionData(t){if(!this.isKitReady()){console.error("Rokt Kit: Not initialized");return}window.Rokt.setExtensionData(t)}setUserAttribute(t,e){return this.userAttributes[t]=e,"Successfully set user attribute for forwarder: "+c}removeUserAttribute(t){return delete this.userAttributes[t],"Successfully removed user attribute for forwarder: "+c}onUserIdentified(t){const e=t;return this.filters.filteredUser=e,this.userAttributes=t.getAllUserAttributes(),this.pendingIdentityEvents.push(this.buildIdentityEvent("identify",e)),"Successfully called onUserIdentified for forwarder: "+c}onLoginComplete(t,e){const i=t;return this.userAttributes=t.getAllUserAttributes(),this.pendingIdentityEvents.push(this.buildIdentityEvent("login",i)),"Successfully called onLoginComplete for forwarder: "+c}onLogoutComplete(t,e){const i=t;return this.userAttributes=t.getAllUserAttributes(),this.pendingIdentityEvents.push(this.buildIdentityEvent("logout",i)),"Successfully called onLogoutComplete for forwarder: "+c}onModifyComplete(t,e){const i=t;return this.userAttributes=t.getAllUserAttributes(),this.pendingIdentityEvents.push(this.buildIdentityEvent("modify",i)),"Successfully called onModifyComplete for forwarder: "+c}selectPlacements(t){const e=t&&t.attributes||{},i={...this.userAttributes,...e},r=this.filters||{},s=r.userAttributeFilters||[],a=r.filteredUser||null,u=a?a.getMPID():null;let l;r?r.filterUserAttributes?l=r.filterUserAttributes(i,s):l=i:(console.warn("Rokt Kit: No filters available, using user attributes"),l=i),this.userAttributes=l;const f=this._onboardingExpProvider==="Optimizely"?this.fetchOptimizely():{},O=this.returnUserIdentities(a),b=this.returnLocalSessionAttributes(),p={...O,...l,...f,...b,mpid:u},v={...t,attributes:p},m=this.launcher.selectPlacements(v),w=()=>this.logSelectPlacementsEvent(p);return Promise.resolve(m).then(y=>y?.context?.sessionId?.then(d=>this.setRoktSessionId(d))).catch(()=>{}).finally(w),m}hashAttributes(t){return this.isKitReady()?this.launcher.hashAttributes(t):(console.error("Rokt Kit: Not initialized"),null)}use(t){return this.isKitReady()?!t||!_(t)?Promise.reject(new Error("Rokt Kit: Invalid extension name")):this.launcher.use(t):(console.error("Rokt Kit: Not initialized"),Promise.reject(new Error("Rokt Kit: Not initialized")))}};h._allowedOriginHashes=[-553112570,549508659],h.PERFORMANCE_MARKS={RoktScriptAppended:"mp:RoktScriptAppended"},h.EMAIL_SHA256_KEY="emailsha256";let g=h;function X(){return 181}function Z(n){if(!n){window.console.log("You must pass a config object to register the kit "+c);return}if(!k(n)){window.console.log("'config' must be an object. You passed in a "+typeof n);return}k(n.kits)?n.kits[c]={constructor:g}:(n.kits={},n.kits[c]={constructor:g}),window.console.log("Successfully registered "+c+" to your mParticle configuration")}return typeof window<"u"&&window.mParticle&&o().addForwarder&&o().addForwarder({name:c,constructor:g,getId:X}),I.register=Z,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"}),I})({});
2
+ //# sourceMappingURL=Rokt-Kit.iife.js.map