-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRokt-Kit.ts
More file actions
1514 lines (1303 loc) · 51.4 KB
/
Copy pathRokt-Kit.ts
File metadata and controls
1514 lines (1303 loc) · 51.4 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
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
// ============================================================
// Types
// ============================================================
import { Batch, KitInterface, IMParticleUser, SDKEvent } from '@mparticle/web-sdk/internal';
import type { IUserIdentities } from '@mparticle/web-sdk';
// BaseEvent not re-exported from @mparticle/web-sdk/internal, so we import directly from @mparticle/event-models.
import { BaseEvent } from '@mparticle/event-models';
interface RoktKitSettings {
accountId: string;
roktExtensions?: string;
placementEventMapping?: string;
placementEventAttributeMapping?: string;
hashedEmailUserIdentityType?: string;
onboardingExpProvider?: string;
loggingUrl?: string;
errorUrl?: string;
workspaceIdSyncApiKey?: string;
}
interface EventAttributeCondition {
operator: string;
attributeValue: string;
}
interface PlacementEventRule {
eventAttributeKey: string;
conditions: EventAttributeCondition[];
}
interface EventAttributeMapping {
value: string;
map: string;
conditions?: EventAttributeCondition[];
}
interface PlacementEventMappingEntry {
jsmap: string;
value: string;
}
interface RoktExtensionEntry {
value: string;
}
interface RoktSelection {
context?: {
sessionId?: Promise<string>;
};
then?: (callback: (sel: RoktSelection) => void) => Promise<void>;
catch?: (callback: () => void) => void;
}
interface RoktLauncher {
selectPlacements(options: Record<string, unknown>): RoktSelection | Promise<RoktSelection>;
hashAttributes(attributes: Record<string, unknown>): Promise<Record<string, unknown>>;
use(extensionName: string): Promise<unknown>;
}
interface RoktGlobal {
createLauncher(options: Record<string, unknown>): Promise<RoktLauncher>;
createLocalLauncher(options: Record<string, unknown>): RoktLauncher;
currentLauncher?: RoktLauncher;
__batch_stream__?(batch: Batch): void;
setExtensionData(data: Record<string, unknown>): void;
}
// FilteredUser is the IMParticleUser shape we receive after kit filtering.
// `getMPID` and `getUserIdentities` are inherited from the SDK's `User` base type.
type FilteredUser = IMParticleUser;
// TODO: Replace with `IIdentitySearchResult` from `@mparticle/web-sdk` once
// a version that exports it is published (currently on a feature branch in
// mParticle/mparticle-web-sdk PR #1255). The shape below is intentionally
// structurally identical so the swap is a one-line import change.
interface WorkspaceIdSyncResult {
httpCode: number;
body?: {
context?: string | null;
mpid?: string;
matched_identities?: Record<string, string>;
is_ephemeral?: boolean;
is_logged_in?: boolean;
};
}
// TODO: Replace with `IdentitySearchCallback`-compatible reference from
// `@mparticle/web-sdk` once published (mirrors `SDKIdentityApi.search`).
type WorkspaceIdSyncSearcher = (
apiKey: string,
knownIdentities: IUserIdentities,
callback: (result: WorkspaceIdSyncResult) => void,
) => void;
interface KitFilters {
userAttributeFilters?: string[];
filterUserAttributes?: (attributes: Record<string, unknown>, filters?: string[]) => Record<string, unknown>;
filteredUser?: FilteredUser | null;
}
interface RoktManager {
attachKit(kit: RoktKit): void | Promise<void>;
flushOnShoppableAdsReadyMessageQueue?(kit: RoktKit): void;
filters?: KitFilters;
domain?: string;
launcherOptions?: Record<string, unknown>;
getLocalSessionAttributes?(): Record<string, unknown>;
setLocalSessionAttribute?(key: string, value: unknown): void;
}
interface MParticleInstance {
setIntegrationAttribute(moduleId: number, attrs: Record<string, unknown>): void;
}
interface OptimizelyState {
getActiveExperimentIds(): string[];
getVariationMap(): Record<string, { id: string }>;
}
interface OptimizelyGlobal {
get(key: 'state'): OptimizelyState;
}
// Our view of the mParticle global with Rokt-specific extensions.
// We access window.mParticle via an explicit cast (see `mp()` helper below)
// rather than augmenting Window to avoid conflicts with @mparticle/web-sdk declarations.
interface MParticleExtended {
Rokt: RoktManager;
addForwarder(config: ForwarderRegistration): void;
getVersion(): string;
generateHash(value: string): string | number;
logEvent(name: string, type: number, attrs?: Record<string, unknown>): void;
EventType: { Other: number };
getInstance(): MParticleInstance;
sessionManager?: { getSession(): string };
_getActiveForwarders(): Array<{ name: string }>;
config?: { isLocalLauncherEnabled?: boolean; isLoggingEnabled?: boolean };
captureTiming?(metricName: string): void;
forwarder?: RoktKit;
loggedEvents?: Array<Record<string, unknown>>;
_registerErrorReportingService?(service: ErrorReportingService): void;
_registerLoggingService?(service: LoggingService): void;
Identity?: { search?: WorkspaceIdSyncSearcher };
}
interface TestHelpers {
generateLauncherScript: (domain: string | undefined, extensions: string[]) => string;
generateThankYouElementScript: (domain: string | undefined) => string;
extractRoktExtensionConfig: (settingsString?: string) => RoktExtensionConfig;
hashEventMessage: (messageType: number, eventType: number, eventName: string) => string | number;
parseSettingsString: <T>(settingsString?: string) => T[];
generateMappedEventLookup: (placementEventMapping: PlacementEventMappingEntry[]) => Record<string, string>;
generateMappedEventAttributeLookup: (mapping: EventAttributeMapping[]) => Record<string, PlacementEventRule[]>;
sendAdBlockMeasurementSignals: (domain: string | undefined, version: string | null) => void;
createAutoRemovedIframe: (src: string) => void;
djb2: (str: string) => number;
setAllowedOriginHashes: (hashes: number[]) => void;
ReportingTransport: typeof ReportingTransport;
ErrorReportingService: typeof ErrorReportingService;
LoggingService: typeof LoggingService;
RateLimiter: typeof RateLimiter;
ErrorCodes: typeof ErrorCodes;
WSDKErrorSeverity: typeof WSDKErrorSeverity;
}
interface ForwarderRegistration {
name: string;
constructor: new () => RoktKit;
getId: () => number;
}
interface ReportingConfig {
loggingUrl?: string;
errorUrl?: string;
isLoggingEnabled: boolean;
}
interface ErrorReport {
message: string;
code?: string;
severity?: string;
stackTrace?: string;
}
interface LogEntry {
message: string;
code?: string;
}
interface RoktExtensionConfig {
roktExtensionsQueryParams: string[];
legacyRoktExtensions: string[];
loadThankYouElement: boolean;
}
declare global {
interface Window {
Rokt?: RoktGlobal;
__rokt_li_guid__?: string;
optimizely?: OptimizelyGlobal;
// mParticle is declared as any to avoid conflicts with @mparticle/web-sdk type declarations.
// We use the typed mp() accessor for all internal accesses.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mParticle: any;
}
}
// ============================================================
// Module-level constants
// ============================================================
const name = 'Rokt';
const moduleId = 181;
const EVENT_NAME_SELECT_PLACEMENTS = 'selectPlacements';
const ADBLOCK_CONTROL_DOMAIN = 'apps.roktecommerce.com';
const INIT_LOG_SAMPLING_RATE = 0.1;
const ROKT_IDENTITY_EVENT_TYPE = {
LOGIN: 'login',
LOGOUT: 'logout',
MODIFY_USER: 'modify_user',
IDENTIFY: 'identify',
} as const;
const ROKT_THANK_YOU_JOURNEY_EXTENSION = 'ThankYouPageJourney';
const ROKT_INTEGRATION_SCRIPT_ID = 'rokt-launcher';
const ROKT_THANK_YOU_ELEMENT_SCRIPT_ID = 'rokt-thank-you-element';
const USER_IDENTIFIED_IN_WORKSPACE_KEY = 'userIdentifiedInWorkspace';
// Bound on how long selectPlacements will wait for an in-flight Workspace
// IDSync search before proceeding without the userIdentifiedInWorkspace flag.
// Long enough to cover the typical /v1/search round-trip (~50ms); short enough that a
// stalled search never blocks placement rendering on a thank-you page.
const WORKSPACE_SEARCH_SELECT_TIMEOUT_MS = 500;
type RoktIdentityEventType = (typeof ROKT_IDENTITY_EVENT_TYPE)[keyof typeof ROKT_IDENTITY_EVENT_TYPE];
// ============================================================
// Reporting service constants
// ============================================================
const ErrorCodes = {
UNKNOWN_ERROR: 'UNKNOWN_ERROR',
UNHANDLED_EXCEPTION: 'UNHANDLED_EXCEPTION',
IDENTITY_REQUEST: 'IDENTITY_REQUEST',
} as const;
const WSDKErrorSeverity = {
ERROR: 'ERROR',
INFO: 'INFO',
WARNING: 'WARNING',
} as const;
const DEFAULT_LOGGING_URL = 'apps.rokt-api.com/v1/log';
const DEFAULT_ERROR_URL = 'apps.rokt-api.com/v1/errors';
const RATE_LIMIT_PER_SEVERITY = 10;
// ============================================================
// Helper: typed accessor for window.mParticle
// We use an explicit cast here to avoid conflicts with @mparticle/web-sdk
// type declarations while still providing full type safety for our usages.
// ============================================================
function mp(): MParticleExtended {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (window as any).mParticle as MParticleExtended;
}
// ============================================================
// Module-level utility functions
// ============================================================
function generateLauncherScript(domain: string | undefined, extensions: string[]): string {
const launcherPath = '/wsdk/integrations/launcher.js';
const baseUrl = [generateBaseUrl(domain), launcherPath].join('');
if (!extensions || extensions.length === 0) {
return baseUrl;
}
return baseUrl + '?extensions=' + extensions.join(',');
}
function generateThankYouElementScript(domain: string | undefined) {
const thankYouElementPath = '/rokt-elements/rokt-element-thank-you.js';
return [generateBaseUrl(domain), thankYouElementPath].join('');
}
function generateBaseUrl(domain: string | undefined) {
const resolvedDomain = typeof domain !== 'undefined' ? domain : 'apps.rokt-api.com';
const protocol = 'https://';
return [protocol, resolvedDomain].join('');
}
function loadRoktScript(
scriptId: string,
source: string,
handlers?: { onLoad?: () => void; onError?: (e: Event | string) => void },
): void {
if (document.getElementById(scriptId)) return; // resolves the preexisting script issue
const target = document.head || document.body;
const script = document.createElement('script');
script.id = scriptId;
script.type = 'text/javascript';
script.src = source;
script.async = true;
script.crossOrigin = 'anonymous';
(script as HTMLScriptElement & { fetchPriority: string }).fetchPriority = 'high';
if (handlers?.onLoad) script.onload = handlers.onLoad;
if (handlers?.onError) script.onerror = handlers.onError;
target.appendChild(script);
}
function isObject(val: unknown): val is Record<string, unknown> {
return val != null && typeof val === 'object' && Array.isArray(val) === false;
}
function parseSettingsString<T>(settingsString?: string): T[] {
if (!settingsString) {
return [];
}
try {
return JSON.parse(settingsString.replace(/"/g, '"')) as T[];
} catch (_error) {
console.error('Settings string contains invalid JSON');
}
return [];
}
function extractRoktExtensionConfig(settingsString?: string): RoktExtensionConfig {
const settings = settingsString ? parseSettingsString<RoktExtensionEntry>(settingsString) : [];
const roktExtensionsQueryParams: string[] = [];
const legacyRoktExtensions: string[] = [];
let loadThankYouElement = false;
for (let i = 0; i < settings.length; i++) {
const extensionName = settings[i].value;
if (extensionName === 'thank-you-journey') {
loadThankYouElement = true;
legacyRoktExtensions.push(ROKT_THANK_YOU_JOURNEY_EXTENSION);
} else {
roktExtensionsQueryParams.push(extensionName);
}
}
return {
roktExtensionsQueryParams,
legacyRoktExtensions,
loadThankYouElement,
};
}
async function registerLegacyExtensions(legacyExtensions: string[], launcher: RoktLauncher | null) {
const extensions: Promise<unknown>[] = [];
if (launcher) {
for (const extension of legacyExtensions) {
extensions.push(launcher.use(extension));
}
}
return Promise.all(extensions);
}
function generateMappedEventLookup(placementEventMapping: PlacementEventMappingEntry[]): Record<string, string> {
if (!placementEventMapping) {
return {};
}
const mappedEvents: Record<string, string> = {};
for (let i = 0; i < placementEventMapping.length; i++) {
const mapping = placementEventMapping[i];
mappedEvents[mapping.jsmap] = mapping.value;
}
return mappedEvents;
}
function generateMappedEventAttributeLookup(
placementEventAttributeMapping: EventAttributeMapping[],
): Record<string, PlacementEventRule[]> {
const mappedAttributeKeys: Record<string, PlacementEventRule[]> = {};
if (!Array.isArray(placementEventAttributeMapping)) {
return mappedAttributeKeys;
}
for (let i = 0; i < placementEventAttributeMapping.length; i++) {
const mapping = placementEventAttributeMapping[i];
if (!mapping || !isString(mapping.value) || !isString(mapping.map)) {
continue;
}
const mappedAttributeKey = mapping.value;
const eventAttributeKey = mapping.map;
if (!mappedAttributeKeys[mappedAttributeKey]) {
mappedAttributeKeys[mappedAttributeKey] = [];
}
mappedAttributeKeys[mappedAttributeKey].push({
eventAttributeKey: eventAttributeKey,
conditions: Array.isArray(mapping.conditions) ? mapping.conditions : [],
});
}
return mappedAttributeKeys;
}
function hashEventMessage(messageType: number, eventType: number, eventName: string): string | number {
return mp().generateHash([messageType, eventType, eventName].join(''));
}
function isEmpty(value: unknown): boolean {
if (value == null) return true;
if (typeof value === 'object') {
return Object.keys(value as object).length === 0;
}
if (Array.isArray(value)) {
return (value as unknown[]).length === 0;
}
return false;
}
function isString(value: unknown): value is string {
return typeof value === 'string';
}
function generateIntegrationName(customIntegrationName?: string): string {
const coreSdkVersion = mp().getVersion();
const kitVersion = process.env.PACKAGE_VERSION;
let integrationName = 'mParticle_' + 'wsdkv_' + coreSdkVersion + '_kitv_' + kitVersion;
if (customIntegrationName) {
integrationName += '_' + customIntegrationName;
}
return integrationName;
}
function djb2(str: string): number {
let hash = 5381;
for (let i = 0; i < str.length; i++) {
hash = (hash << 5) + hash + str.charCodeAt(i);
hash = hash & hash;
}
return hash;
}
function createAutoRemovedIframe(src: string): void {
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin');
iframe.src = src;
iframe.onload = function () {
iframe.onload = null;
if (iframe.parentNode) {
iframe.parentNode.removeChild(iframe);
}
};
const target = document.body || document.head;
if (target) {
target.appendChild(iframe);
}
}
function sendAdBlockMeasurementSignals(domain: string | undefined, version: string | null): void {
const originHash = djb2(window.location.origin);
const allowedOriginHashes = RoktKit._allowedOriginHashes;
if (allowedOriginHashes.indexOf(originHash) === -1) {
return;
}
if (Math.random() >= INIT_LOG_SAMPLING_RATE) {
return;
}
const guid = window.__rokt_li_guid__;
if (!guid) {
return;
}
const pageUrl = window.location.href.split('?')[0].split('#')[0];
const params =
'version=' +
encodeURIComponent(version ?? '') +
'&launcherInstanceGuid=' +
encodeURIComponent(guid) +
'&pageUrl=' +
encodeURIComponent(pageUrl);
const existingDomain = domain || 'apps.rokt.com';
createAutoRemovedIframe('https://' + existingDomain + '/v1/wsdk-init/index.html?' + params);
createAutoRemovedIframe(
'https://' + ADBLOCK_CONTROL_DOMAIN + '/v1/wsdk-init/index.html?' + params + '&isControl=true',
);
}
// ============================================================
// Reporting helpers
// ============================================================
function _isDebugModeEnabled(): boolean {
return typeof window !== 'undefined' && !!window.location?.search?.toLowerCase().includes('mp_enable_logging=true');
}
function _getReportingUrl(): string | undefined {
return typeof window !== 'undefined' ? window.location?.href : undefined;
}
function _getUserAgent(): string | undefined {
return typeof window !== 'undefined' ? window.navigator?.userAgent : undefined;
}
class RateLimiter {
private _logCount: Record<string, number> = {};
incrementAndCheck(severity: string): boolean {
const count = this._logCount[severity] || 0;
const newCount = count + 1;
this._logCount[severity] = newCount;
return newCount > RATE_LIMIT_PER_SEVERITY;
}
}
class ReportingTransport {
private _isEnabled: boolean;
private _integrationName: string;
private _launcherInstanceGuid: string | undefined;
private _accountId: string | null;
private _rateLimiter: RateLimiter;
private readonly _reporter = 'mp-wsdk';
constructor(
config: ReportingConfig,
integrationName: string | null | undefined,
launcherInstanceGuid: string | undefined,
accountId: string | null | undefined,
rateLimiter?: RateLimiter,
) {
const isLoggingEnabled = config.isLoggingEnabled;
this._integrationName = integrationName || '';
this._launcherInstanceGuid = launcherInstanceGuid;
this._accountId = accountId || null;
this._rateLimiter = rateLimiter || new RateLimiter();
this._isEnabled = _isDebugModeEnabled() || isLoggingEnabled;
}
send(
url: string,
severity: string,
msg: string,
code?: string,
stackTrace?: string,
onError?: (error: Error) => void,
): void {
if (!this._isEnabled || this._rateLimiter.incrementAndCheck(severity)) {
return;
}
try {
const logRequest = {
additionalInformation: {
message: msg,
version: this._integrationName,
},
severity,
code: code || ErrorCodes.UNKNOWN_ERROR,
url: _getReportingUrl(),
deviceInfo: _getUserAgent(),
stackTrace,
reporter: this._reporter,
integration: this._integrationName,
};
const headers: Record<string, string> = {
Accept: 'text/plain;charset=UTF-8',
'Content-Type': 'application/json',
'rokt-launcher-version': this._integrationName,
'rokt-wsdk-version': 'joint',
};
if (this._launcherInstanceGuid) {
headers['rokt-launcher-instance-guid'] = this._launcherInstanceGuid;
}
if (this._accountId) {
headers['rokt-account-id'] = this._accountId;
}
fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(logRequest),
}).catch((error: Error) => {
console.error('ReportingTransport: Failed to send log', error);
if (onError) onError(error);
});
} catch (error) {
console.error('ReportingTransport: Failed to send log', error);
if (onError) onError(error as Error);
}
}
}
class ErrorReportingService {
private _transport: ReportingTransport;
private _errorUrl: string;
constructor(
config: ReportingConfig,
integrationName: string | null | undefined,
launcherInstanceGuid?: string,
accountId?: string | null,
rateLimiter?: RateLimiter,
) {
this._transport = new ReportingTransport(config, integrationName, launcherInstanceGuid, accountId, rateLimiter);
this._errorUrl = 'https://' + (config?.errorUrl || DEFAULT_ERROR_URL);
}
report(error: ErrorReport | null | undefined): void {
if (!error) return;
const severity = error.severity || WSDKErrorSeverity.ERROR;
this._transport.send(this._errorUrl, severity, error.message, error.code, error.stackTrace);
}
}
class LoggingService {
private _transport: ReportingTransport;
private _loggingUrl: string;
private _errorReportingService: { report: (e: ErrorReport) => void };
constructor(
config: ReportingConfig,
errorReportingService: { report: (e: ErrorReport) => void },
integrationName: string | null | undefined,
launcherInstanceGuid?: string,
accountId?: string | null,
rateLimiter?: RateLimiter,
) {
this._transport = new ReportingTransport(config, integrationName, launcherInstanceGuid, accountId, rateLimiter);
this._loggingUrl = 'https://' + (config?.loggingUrl || DEFAULT_LOGGING_URL);
this._errorReportingService = errorReportingService;
}
log(entry: LogEntry | null | undefined): void {
if (!entry) return;
this._transport.send(
this._loggingUrl,
WSDKErrorSeverity.INFO,
entry.message,
entry.code,
undefined,
(error: Error) => {
if (this._errorReportingService) {
this._errorReportingService.report({
message: 'LoggingService: Failed to send log: ' + error.message,
code: ErrorCodes.UNKNOWN_ERROR,
severity: WSDKErrorSeverity.ERROR,
});
}
},
);
}
}
// ============================================================
// RoktKit class
// ============================================================
class RoktKit implements KitInterface {
// Static field for allowed origin hashes (mutable by testHelpers)
public static _allowedOriginHashes: number[] = [-553112570, 549508659];
private static readonly PERFORMANCE_MARKS = {
RoktScriptAppended: 'mp:RoktScriptAppended',
};
private static readonly EMAIL_SHA256_KEY = 'emailsha256';
// Public fields (accessed by tests and the mParticle framework)
public name = name;
public id = moduleId;
public moduleId = moduleId;
public isInitialized = false;
public launcher: RoktLauncher | null = null;
public filters: KitFilters = {};
public userAttributes: Record<string, unknown> = {};
// Flag set by the Workspace IDSync flow on a 200 response. Stored on the
// kit instance and merged into placement attributes inside selectPlacements.
public userIdentifiedInWorkspace = false;
public testHelpers: TestHelpers | null = null;
public placementEventMappingLookup: Record<string, string> = {};
public placementEventAttributeMappingLookup: Record<string, PlacementEventRule[]> = {};
public batchQueue: Batch[] = [];
public batchStreamQueue: Batch[] = [];
public pendingIdentityEvents: BaseEvent[] = [];
public integrationName: string | null = null;
public domain?: string;
public errorReportingService: ErrorReportingService | null = null;
public loggingService: LoggingService | null = null;
// Private fields
private _mappedEmailSha256Key?: string;
private _onboardingExpProvider?: string;
private _thankYouElementOnLoadCallback: (() => void) | null = null;
private _isThankYouElementLoaded = false;
private _workspaceIdSyncApiKey?: string;
// Held during a search dispatch so the next selectPlacements call;
// can wait for the HTTP response before reading userIdentifiedInWorkspace;
// — otherwise the first placement call ships without the flag.
private _workspaceSearchInFlightPromise: Promise<void> | null = null;
// Stable serialization of the identifier set sent in the most recent
// successful search dispatch. If a subsequent identification arrives with
// an identical set, we skip the network call (the flag is still correct
// from the prior search). Keyed over the full IUserIdentities map — not
// just email — so partners passing hashed email through `other`/`other2-10`
// or any other identifier benefit from the same dedupe. Cleared on logout
// so a re-login re-evaluates fresh.
private _workspaceLastSearchedIdentitiesKey?: string;
// ---- Private helpers ----
private getEventAttributeValue(event: SDKEvent, eventAttributeKey: string): unknown {
const attributes = event && event.EventAttributes;
if (!attributes) {
return null;
}
if (typeof attributes[eventAttributeKey] === 'undefined') {
return null;
}
return attributes[eventAttributeKey];
}
private doesEventAttributeConditionMatch(condition: EventAttributeCondition, actualValue: unknown): boolean {
if (!condition || !isString(condition.operator)) {
return false;
}
const operator = condition.operator.toLowerCase();
const expectedValue = condition.attributeValue;
if (operator === 'exists') {
return actualValue !== null;
}
if (actualValue == null) {
return false;
}
if (operator === 'equals') {
return String(actualValue) === String(expectedValue);
}
if (operator === 'contains') {
return String(actualValue).indexOf(String(expectedValue)) !== -1;
}
return false;
}
private doesEventMatchRule(event: SDKEvent, rule: PlacementEventRule): boolean {
if (!rule || !isString(rule.eventAttributeKey)) {
return false;
}
const conditions = rule.conditions;
if (!Array.isArray(conditions)) {
return false;
}
const actualValue = this.getEventAttributeValue(event, rule.eventAttributeKey);
if (conditions.length === 0) {
return actualValue !== null;
}
for (let i = 0; i < conditions.length; i++) {
if (!this.doesEventAttributeConditionMatch(conditions[i], actualValue)) {
return false;
}
}
return true;
}
private applyPlacementEventAttributeMapping(event: SDKEvent): void {
const mappedAttributeKeys = Object.keys(this.placementEventAttributeMappingLookup);
for (let i = 0; i < mappedAttributeKeys.length; i++) {
const mappedAttributeKey = mappedAttributeKeys[i];
const rulesForMappedAttributeKey = this.placementEventAttributeMappingLookup[mappedAttributeKey];
if (isEmpty(rulesForMappedAttributeKey)) {
continue;
}
// Require ALL rules for the same key to match (AND).
let allMatch = true;
for (let j = 0; j < rulesForMappedAttributeKey.length; j++) {
if (!this.doesEventMatchRule(event, rulesForMappedAttributeKey[j])) {
allMatch = false;
break;
}
}
if (!allMatch) {
continue;
}
mp().Rokt.setLocalSessionAttribute?.(mappedAttributeKey, true);
}
}
private isLauncherReadyToAttach(): boolean {
return !!window.Rokt && typeof window.Rokt.createLauncher === 'function';
}
/**
* Returns the user identities from the filtered user, if any.
*/
private returnUserIdentities(filteredUser: FilteredUser | null | undefined): Record<string, string> {
if (!filteredUser || !filteredUser.getUserIdentities) {
return {};
}
const userIdentities: IUserIdentities = filteredUser.getUserIdentities().userIdentities;
return this.replaceOtherIdentityWithEmailsha256(userIdentities);
}
private returnLocalSessionAttributes(): Record<string, unknown> {
if (!mp().Rokt || typeof mp().Rokt.getLocalSessionAttributes !== 'function') {
return {};
}
if (isEmpty(this.placementEventMappingLookup) && isEmpty(this.placementEventAttributeMappingLookup)) {
return {};
}
return mp().Rokt.getLocalSessionAttributes!();
}
private replaceOtherIdentityWithEmailsha256(userIdentities: IUserIdentities): Record<string, string> {
const newUserIdentities: Record<string, string> = { ...(userIdentities || {}) };
const key = this._mappedEmailSha256Key;
if (key && userIdentities[key as keyof IUserIdentities]) {
newUserIdentities[RoktKit.EMAIL_SHA256_KEY] = userIdentities[key as keyof IUserIdentities] as string;
}
if (key) {
delete newUserIdentities[key];
}
return newUserIdentities;
}
private logSelectPlacementsEvent(attributes: unknown): void {
if (!window.mParticle || typeof mp().logEvent !== 'function') {
return;
}
if (!isObject(attributes)) {
return;
}
const EVENT_TYPE_OTHER = mp().EventType.Other;
mp().logEvent(EVENT_NAME_SELECT_PLACEMENTS, EVENT_TYPE_OTHER, attributes as Record<string, unknown>);
}
private buildIdentityEvent(eventType: RoktIdentityEventType, filteredUser: FilteredUser): BaseEvent {
const mpid = filteredUser.getMPID();
const sessionUuid =
mp() && mp().sessionManager && typeof mp().sessionManager!.getSession === 'function'
? mp().sessionManager!.getSession()
: undefined;
return {
event_type: eventType,
data: {
timestamp_unixtime_ms: Date.now(),
session_uuid: sessionUuid ?? undefined,
mpid,
},
} as unknown as BaseEvent;
}
private mergePendingIdentityEvents(batch: Batch): Batch {
if (this.pendingIdentityEvents.length === 0) {
return batch;
}
const merged: Batch = {
...batch,
events: [...(batch.events ?? []), ...this.pendingIdentityEvents],
};
this.pendingIdentityEvents = [];
return merged;
}
private drainBatchQueue(): void {
this.batchQueue.forEach((batch) => {
this.processBatch(batch);
});
this.batchQueue = [];
}
public processBatch(batch: Batch): string {
if (!this.isKitReady()) {
this.batchQueue.push(batch);
return 'Batch queued for forwarder: ' + name;
}
this.sendBatchStream(this.mergePendingIdentityEvents(batch));
return 'Successfully sent batch to forwarder: ' + name;
}
private sendBatchStream(batch: Batch): void {
if (window.Rokt && typeof window.Rokt.__batch_stream__ === 'function') {
if (this.batchStreamQueue.length) {
const queuedBatches = this.batchStreamQueue;
this.batchStreamQueue = [];
for (let i = 0; i < queuedBatches.length; i++) {
window.Rokt.__batch_stream__(queuedBatches[i]);
}
}
window.Rokt.__batch_stream__(batch);
} else {
this.batchStreamQueue.push(batch);
}
}
private setRoktSessionId(sessionId: string): void {
if (!sessionId || typeof sessionId !== 'string') {
return;
}
try {
const mpInstance = mp().getInstance();
if (mpInstance && typeof mpInstance.setIntegrationAttribute === 'function') {
mpInstance.setIntegrationAttribute(moduleId, {
roktSessionId: sessionId,
});
}
} catch (_e) {
// Best effort — never let this break the partner page
}
}
private attachLauncher(
accountId: string,
launcherOptions: Record<string, unknown>,
legacyRoktExtensions: string[] = [],
): void {
const mpSessionId =
mp() && mp().sessionManager && typeof mp().sessionManager!.getSession === 'function'
? mp().sessionManager!.getSession()
: undefined;
const options: Record<string, unknown> = {
accountId,
...(launcherOptions || {}),
...(mpSessionId ? { mpSessionId } : {}),
};
let launcherPromise: Promise<RoktLauncher>;
if (this.isPartnerInLocalLauncherTestGroup()) {
launcherPromise = Promise.resolve(window.Rokt!.createLocalLauncher(options));
} else {
launcherPromise = window.Rokt!.createLauncher(options);
}
launcherPromise
.then(async (launcher) => {
await registerLegacyExtensions(legacyRoktExtensions, launcher);
this.initRoktLauncher(launcher);
})
.catch((err: unknown) => {
console.error('Error creating Rokt launcher:', err);
});
}
private initRoktLauncher(launcher: RoktLauncher): void {
// Assign the launcher to a global variable for later access
if (window.Rokt) {
window.Rokt.currentLauncher = launcher;
}
// Locally cache the launcher and filters
this.launcher = launcher;
const roktFilters = mp().Rokt?.filters;
if (!roktFilters) {
console.warn('Rokt Kit: No filters have been set.');
} else {
this.filters = roktFilters;
if (!roktFilters.filteredUser) {