forked from rudderlabs/rudder-sdk-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
analytics.js
1402 lines (1270 loc) · 41.1 KB
/
analytics.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
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
/* eslint-disable new-cap */
/* eslint-disable func-names */
/* eslint-disable eqeqeq */
/* eslint-disable no-prototype-builtins */
/* eslint-disable class-methods-use-this */
/* eslint-disable no-restricted-syntax */
/* eslint-disable guard-for-in */
/* eslint-disable no-sequences */
/* eslint-disable no-multi-assign */
/* eslint-disable no-unused-expressions */
/* eslint-disable import/extensions */
/* eslint-disable no-param-reassign */
import Emitter from "component-emitter";
import after from "after";
import querystring from "component-querystring";
import merge from "lodash.merge";
import cloneDeep from "lodash.clonedeep";
import utm from "@segment/utm-params";
import {
getJSONTrimmed,
generateUUID,
handleError,
getDefaultPageProperties,
getUserProvidedConfigUrl,
findAllEnabledDestinations,
tranformToRudderNames,
transformToServerNames,
checkReservedKeywords,
getReferrer,
getReferringDomain,
commonNames,
} from "./utils/utils";
import {
CONFIG_URL,
MAX_WAIT_FOR_INTEGRATION_LOAD,
INTEGRATION_LOAD_CHECK_INTERVAL,
POLYFILL_URL,
} from "./utils/constants";
import { integrations } from "./integrations";
import RudderElementBuilder from "./utils/RudderElementBuilder";
import Storage from "./utils/storage";
import { EventRepository } from "./utils/EventRepository";
import logger from "./utils/logUtil";
import { addDomEventHandlers } from "./utils/autotrack.js";
import ScriptLoader from "./integrations/ScriptLoader";
import parseLinker from "./utils/linker";
import CookieConsentFactory from "./cookieConsent/CookieConsentFactory";
const queryDefaults = {
trait: "ajs_trait_",
prop: "ajs_prop_",
};
// https://unpkg.com/[email protected]/dist/browser.js
/**
* Add the rudderelement object to flush queue
*
* @param {RudderElement} rudderElement
*/
function enqueue(rudderElement, type) {
if (!this.eventRepository) {
this.eventRepository = EventRepository;
}
this.eventRepository.enqueue(rudderElement, type);
}
/**
* class responsible for handling core
* event tracking functionalities
*/
class Analytics {
/**
* Creates an instance of Analytics.
* @memberof Analytics
*/
constructor() {
this.autoTrackHandlersRegistered = false;
this.autoTrackFeatureEnabled = false;
this.initialized = false;
this.areEventsReplayed = false;
this.trackValues = [];
this.eventsBuffer = [];
this.clientIntegrations = [];
this.loadOnlyIntegrations = {};
this.clientIntegrationObjects = undefined;
this.successfullyLoadedIntegration = [];
this.failedToBeLoadedIntegration = [];
this.toBeProcessedArray = [];
this.toBeProcessedByIntegrationArray = [];
this.storage = Storage;
this.eventRepository = EventRepository;
this.sendAdblockPage = false;
this.sendAdblockPageOptions = {};
this.clientSuppliedCallbacks = {};
this.readyCallback = () => {};
this.executeReadyCallback = undefined;
this.methodToCallbackMapping = {
syncPixel: "syncPixelCallback",
};
this.loaded = false;
this.loadIntegration = true;
this.cookieConsentOptions = {};
}
/**
* initialize the user after load config
*/
initializeUser() {
this.userId =
this.storage.getUserId() != undefined ? this.storage.getUserId() : "";
this.userTraits =
this.storage.getUserTraits() != undefined
? this.storage.getUserTraits()
: {};
this.groupId =
this.storage.getGroupId() != undefined ? this.storage.getGroupId() : "";
this.groupTraits =
this.storage.getGroupTraits() != undefined
? this.storage.getGroupTraits()
: {};
this.anonymousId = this.getAnonymousId();
// save once for storing older values to encrypted
this.storage.setUserId(this.userId);
this.storage.setAnonymousId(this.anonymousId);
this.storage.setGroupId(this.groupId);
this.storage.setUserTraits(this.userTraits);
this.storage.setGroupTraits(this.groupTraits);
}
setInitialPageProperties() {
let initialReferrer = this.storage.getInitialReferrer();
let initialReferringDomain = this.storage.getInitialReferringDomain();
if (initialReferrer == null && initialReferringDomain == null) {
initialReferrer = getReferrer();
initialReferringDomain = getReferringDomain(initialReferrer);
this.storage.setInitialReferrer(initialReferrer);
this.storage.setInitialReferringDomain(initialReferringDomain);
}
}
/**
* Process the response from control plane and
* call initialize for integrations
*
* @param {*} status
* @param {*} response
* @memberof Analytics
*/
processResponse(status, response) {
try {
logger.debug(`===in process response=== ${status}`);
if (typeof response === "string") {
response = JSON.parse(response);
}
if (
response.source.useAutoTracking &&
!this.autoTrackHandlersRegistered
) {
this.autoTrackFeatureEnabled = true;
addDomEventHandlers(this);
this.autoTrackHandlersRegistered = true;
}
response.source.destinations.forEach(function (destination, index) {
logger.debug(
`Destination ${index} Enabled? ${destination.enabled} Type: ${destination.destinationDefinition.name} Use Native SDK? true`
);
if (destination.enabled) {
this.clientIntegrations.push({
name: destination.destinationDefinition.name,
config: destination.config,
});
}
}, this);
logger.debug("this.clientIntegrations: ", this.clientIntegrations);
// intersection of config-plane native sdk destinations with sdk load time destination list
this.clientIntegrations = findAllEnabledDestinations(
this.loadOnlyIntegrations,
this.clientIntegrations
);
var cookieConsent;
// Call the cookie consent factory to initialize and return the type of cookie
// consent being set. For now we only support OneTrust.
try {
cookieConsent = CookieConsentFactory.initialize(
this.cookieConsentOptions
);
} catch (e) {
logger.error(e);
}
// If cookie consent object is return we filter according to consents given by user
// else we do not consider any filtering for cookie consent.
this.clientIntegrations = this.clientIntegrations.filter((intg) => {
return (
integrations[intg.name] != undefined &&
(!cookieConsent || // check if cookie consent object is present and then do filtering
(cookieConsent && cookieConsent.isEnabled(intg.config)))
);
});
this.init(this.clientIntegrations);
} catch (error) {
handleError(error);
logger.debug("===handling config BE response processing error===");
logger.debug(
"autoTrackHandlersRegistered",
this.autoTrackHandlersRegistered
);
if (this.autoTrackFeatureEnabled && !this.autoTrackHandlersRegistered) {
addDomEventHandlers(this);
this.autoTrackHandlersRegistered = true;
}
}
}
/**
* Initialize integrations by addinfg respective scripts
* keep the instances reference in core
*
* @param {*} intgArray
* @returns
* @memberof Analytics
*/
init(intgArray) {
const self = this;
logger.debug("supported intgs ", integrations);
// this.clientIntegrationObjects = [];
if (!intgArray || intgArray.length == 0) {
if (this.readyCallback) {
this.readyCallback();
}
this.toBeProcessedByIntegrationArray = [];
return;
}
let intgInstance;
intgArray.forEach((intg) => {
try {
logger.debug(
"[Analytics] init :: trying to initialize integration name:: ",
intg.name
);
const intgClass = integrations[intg.name];
const destConfig = intg.config;
intgInstance = new intgClass(destConfig, self);
intgInstance.init();
logger.debug("initializing destination: ", intg);
this.isInitialized(intgInstance).then(this.replayEvents);
} catch (e) {
logger.error(
"[Analytics] initialize integration (integration.init()) failed :: ",
intg.name
);
this.failedToBeLoadedIntegration.push(intgInstance);
}
});
}
// eslint-disable-next-line class-methods-use-this
replayEvents(object) {
if (
object.successfullyLoadedIntegration.length +
object.failedToBeLoadedIntegration.length ===
object.clientIntegrations.length &&
!object.areEventsReplayed
) {
logger.debug(
"===replay events called====",
" successfully loaded count: ",
object.successfullyLoadedIntegration.length,
" failed loaded count: ",
object.failedToBeLoadedIntegration.length
);
// eslint-disable-next-line no-param-reassign
object.clientIntegrationObjects = [];
// eslint-disable-next-line no-param-reassign
object.clientIntegrationObjects = object.successfullyLoadedIntegration;
logger.debug(
"==registering after callback===",
" after to be called after count : ",
object.clientIntegrationObjects.length
);
object.executeReadyCallback = after(
object.clientIntegrationObjects.length,
object.readyCallback
);
logger.debug("==registering ready callback===");
object.on("ready", object.executeReadyCallback);
object.clientIntegrationObjects.forEach((intg) => {
logger.debug("===looping over each successful integration====");
if (!intg.isReady || intg.isReady()) {
logger.debug("===letting know I am ready=====", intg.name);
object.emit("ready");
}
});
if (object.toBeProcessedByIntegrationArray.length > 0) {
// send the queued events to the fetched integration
object.toBeProcessedByIntegrationArray.forEach((event) => {
const methodName = event[0];
event.shift();
// convert common names to sdk identified name
if (Object.keys(event[0].message.integrations).length > 0) {
tranformToRudderNames(event[0].message.integrations);
}
// if not specified at event level, All: true is default
const clientSuppliedIntegrations = event[0].message.integrations;
// get intersection between config plane native enabled destinations
// (which were able to successfully load on the page) vs user supplied integrations
const succesfulLoadedIntersectClientSuppliedIntegrations =
findAllEnabledDestinations(
clientSuppliedIntegrations,
object.clientIntegrationObjects
);
// send to all integrations now from the 'toBeProcessedByIntegrationArray' replay queue
for (
let i = 0;
i < succesfulLoadedIntersectClientSuppliedIntegrations.length;
i += 1
) {
try {
if (
!succesfulLoadedIntersectClientSuppliedIntegrations[i]
.isFailed ||
!succesfulLoadedIntersectClientSuppliedIntegrations[
i
].isFailed()
) {
if (
succesfulLoadedIntersectClientSuppliedIntegrations[i][
methodName
]
) {
const sendEvent = !object.IsEventBlackListed(
event[0].message.event,
succesfulLoadedIntersectClientSuppliedIntegrations[i].name
);
// Block the event if it is blacklisted for the device-mode destination
if (sendEvent) {
const clonedBufferEvent = cloneDeep(event);
succesfulLoadedIntersectClientSuppliedIntegrations[i][
methodName
](...clonedBufferEvent);
}
}
}
} catch (error) {
handleError(error);
}
}
});
object.toBeProcessedByIntegrationArray = [];
}
object.areEventsReplayed = true;
}
}
pause(time) {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
}
isInitialized(instance, time = 0) {
return new Promise((resolve) => {
if (instance.isLoaded()) {
logger.debug("===integration loaded successfully====", instance.name);
this.successfullyLoadedIntegration.push(instance);
return resolve(this);
}
if (time >= MAX_WAIT_FOR_INTEGRATION_LOAD) {
logger.debug("====max wait over====");
this.failedToBeLoadedIntegration.push(instance);
return resolve(this);
}
this.pause(INTEGRATION_LOAD_CHECK_INTERVAL).then(() => {
logger.debug("====after pause, again checking====");
return this.isInitialized(
instance,
time + INTEGRATION_LOAD_CHECK_INTERVAL
).then(resolve);
});
});
}
/**
* Process page params and forward to page call
*
* @param {*} category
* @param {*} name
* @param {*} properties
* @param {*} options
* @param {*} callback
* @memberof Analytics
*/
page(category, name, properties, options, callback) {
if (!this.loaded) return;
if (typeof options === "function") (callback = options), (options = null);
if (typeof properties === "function")
(callback = properties), (options = properties = null);
if (typeof name === "function")
(callback = name), (options = properties = name = null);
if (
typeof category === "object" &&
category != null &&
category != undefined
)
(options = name), (properties = category), (name = category = null);
if (typeof name === "object" && name != null && name != undefined)
(options = properties), (properties = name), (name = null);
if (typeof category === "string" && typeof name !== "string")
(name = category), (category = null);
if (this.sendAdblockPage && category != "RudderJS-Initiated") {
this.sendSampleRequest();
}
this.processPage(category, name, properties, options, callback);
}
/**
* Process track params and forward to track call
*
* @param {*} event
* @param {*} properties
* @param {*} options
* @param {*} callback
* @memberof Analytics
*/
track(event, properties, options, callback) {
if (!this.loaded) return;
if (typeof options === "function") (callback = options), (options = null);
if (typeof properties === "function")
(callback = properties), (options = null), (properties = null);
this.processTrack(event, properties, options, callback);
}
/**
* Process identify params and forward to indentify call
*
* @param {*} userId
* @param {*} traits
* @param {*} options
* @param {*} callback
* @memberof Analytics
*/
identify(userId, traits, options, callback) {
if (!this.loaded) return;
if (typeof options === "function") (callback = options), (options = null);
if (typeof traits === "function")
(callback = traits), (options = null), (traits = null);
if (typeof userId === "object")
(options = traits), (traits = userId), (userId = this.userId);
this.processIdentify(userId, traits, options, callback);
}
/**
*
* @param {*} to
* @param {*} from
* @param {*} options
* @param {*} callback
*/
alias(to, from, options, callback) {
if (!this.loaded) return;
if (typeof options === "function") (callback = options), (options = null);
if (typeof from === "function")
(callback = from), (options = null), (from = null);
if (typeof from === "object") (options = from), (from = null);
const rudderElement = new RudderElementBuilder().setType("alias").build();
rudderElement.message.previousId =
from || (this.userId ? this.userId : this.getAnonymousId());
rudderElement.message.userId = to;
this.processAndSendDataToDestinations(
"alias",
rudderElement,
options,
callback
);
}
/**
*
* @param {*} to
* @param {*} from
* @param {*} options
* @param {*} callback
*/
group(groupId, traits, options, callback) {
if (!this.loaded) return;
if (!arguments.length) return;
if (typeof options === "function") (callback = options), (options = null);
if (typeof traits === "function")
(callback = traits), (options = null), (traits = null);
if (typeof groupId === "object")
(options = traits), (traits = groupId), (groupId = this.groupId);
this.groupId = groupId;
this.storage.setGroupId(this.groupId);
const rudderElement = new RudderElementBuilder().setType("group").build();
if (traits) {
for (const key in traits) {
this.groupTraits[key] = traits[key];
}
} else {
this.groupTraits = {};
}
this.storage.setGroupTraits(this.groupTraits);
this.processAndSendDataToDestinations(
"group",
rudderElement,
options,
callback
);
}
/**
* Send page call to Rudder BE and to initialized integrations
*
* @param {*} category
* @param {*} name
* @param {*} properties
* @param {*} options
* @param {*} callback
* @memberof Analytics
*/
processPage(category, name, properties, options, callback) {
const rudderElement = new RudderElementBuilder().setType("page").build();
if (!properties) {
properties = {};
}
if (name) {
rudderElement.message.name = name;
properties.name = name;
}
if (category) {
rudderElement.message.category = category;
properties.category = category;
}
rudderElement.message.properties = this.getPageProperties(properties); // properties;
this.trackPage(rudderElement, options, callback);
}
/**
* Send track call to Rudder BE and to initialized integrations
*
* @param {*} event
* @param {*} properties
* @param {*} options
* @param {*} callback
* @memberof Analytics
*/
processTrack(event, properties, options, callback) {
const rudderElement = new RudderElementBuilder().setType("track").build();
if (event) {
rudderElement.setEventName(event);
}
if (properties) {
rudderElement.setProperty(properties);
} else {
rudderElement.setProperty({});
}
this.trackEvent(rudderElement, options, callback);
}
/**
* Send identify call to Rudder BE and to initialized integrations
*
* @param {*} userId
* @param {*} traits
* @param {*} options
* @param {*} callback
* @memberof Analytics
*/
processIdentify(userId, traits, options, callback) {
if (userId && this.userId && userId !== this.userId) {
this.reset();
}
this.userId = userId;
this.storage.setUserId(this.userId);
const rudderElement = new RudderElementBuilder()
.setType("identify")
.build();
if (traits) {
for (const key in traits) {
this.userTraits[key] = traits[key];
}
this.storage.setUserTraits(this.userTraits);
}
this.identifyUser(rudderElement, options, callback);
}
/**
* Identify call supporting rudderelement from builder
*
* @param {*} rudderElement
* @param {*} callback
* @memberof Analytics
*/
identifyUser(rudderElement, options, callback) {
if (rudderElement.message.userId) {
this.userId = rudderElement.message.userId;
this.storage.setUserId(this.userId);
}
if (
rudderElement &&
rudderElement.message &&
rudderElement.message.context &&
rudderElement.message.context.traits
) {
this.userTraits = {
...rudderElement.message.context.traits,
};
this.storage.setUserTraits(this.userTraits);
}
this.processAndSendDataToDestinations(
"identify",
rudderElement,
options,
callback
);
}
/**
* Page call supporting rudderelement from builder
*
* @param {*} rudderElement
* @param {*} callback
* @memberof Analytics
*/
trackPage(rudderElement, options, callback) {
this.processAndSendDataToDestinations(
"page",
rudderElement,
options,
callback
);
}
/**
* Track call supporting rudderelement from builder
*
* @param {*} rudderElement
* @param {*} callback
* @memberof Analytics
*/
trackEvent(rudderElement, options, callback) {
this.processAndSendDataToDestinations(
"track",
rudderElement,
options,
callback
);
}
IsEventBlackListed(eventName, intgName) {
if (!eventName || !(typeof eventName === "string")) {
return false;
}
const sdkIntgName = commonNames[intgName];
const intg = this.clientIntegrations.find(
(intg) => intg.name === sdkIntgName
);
const { blacklistedEvents, whitelistedEvents, eventFilteringOption } =
intg.config;
if (!eventFilteringOption) {
return false;
}
switch (eventFilteringOption) {
// disabled filtering
case "disable":
return false;
// Blacklist is choosen for filtering events
case "blacklistedEvents":
const isValidBlackList =
blacklistedEvents &&
Array.isArray(blacklistedEvents) &&
blacklistedEvents.every((x) => x.eventName !== "");
if (isValidBlackList) {
return blacklistedEvents.find(
(eventObj) =>
eventObj.eventName.trim().toUpperCase() ===
eventName.trim().toUpperCase()
) === undefined
? false
: true;
} else {
return false;
}
// Whitelist is choosen for filtering events
case "whitelistedEvents":
const isValidWhiteList =
whitelistedEvents &&
Array.isArray(whitelistedEvents) &&
whitelistedEvents.some((x) => x.eventName !== "");
if (isValidWhiteList) {
return whitelistedEvents.find(
(eventObj) =>
eventObj.eventName.trim().toUpperCase() ===
eventName.trim().toUpperCase()
) === undefined
? true
: false;
} else {
return true;
}
default:
return false;
}
}
/**
* Process and send data to destinations along with rudder BE
*
* @param {*} type
* @param {*} rudderElement
* @param {*} callback
* @memberof Analytics
*/
processAndSendDataToDestinations(type, rudderElement, options, callback) {
try {
if (!this.anonymousId) {
this.setAnonymousId();
}
// assign page properties to context
// rudderElement.message.context.page = getDefaultPageProperties();
rudderElement.message.context.traits = {
...this.userTraits,
};
logger.debug("anonymousId: ", this.anonymousId);
rudderElement.message.anonymousId = this.anonymousId;
rudderElement.message.userId = rudderElement.message.userId
? rudderElement.message.userId
: this.userId;
if (type == "group") {
if (this.groupId) {
rudderElement.message.groupId = this.groupId;
}
if (this.groupTraits) {
rudderElement.message.traits = {
...this.groupTraits,
};
}
}
this.processOptionsParam(rudderElement, options);
logger.debug(JSON.stringify(rudderElement));
// check for reserved keys and log
checkReservedKeywords(rudderElement.message, type);
// structure user supplied integrations object to rudder format
if (Object.keys(rudderElement.message.integrations).length > 0) {
tranformToRudderNames(rudderElement.message.integrations);
}
// if not specified at event level, All: true is default
const clientSuppliedIntegrations = rudderElement.message.integrations;
// get intersection between config plane native enabled destinations
// (which were able to successfully load on the page) vs user supplied integrations
const succesfulLoadedIntersectClientSuppliedIntegrations =
findAllEnabledDestinations(
clientSuppliedIntegrations,
this.clientIntegrationObjects
);
// try to first send to all integrations, if list populated from BE
try {
succesfulLoadedIntersectClientSuppliedIntegrations.forEach((obj) => {
if (!obj.isFailed || !obj.isFailed()) {
if (obj[type]) {
let sendEvent = !this.IsEventBlackListed(
rudderElement.message.event,
obj.name
);
// Block the event if it is blacklisted for the device-mode destination
if (sendEvent) {
const clonedRudderElement = cloneDeep(rudderElement);
obj[type](clonedRudderElement);
}
}
}
});
} catch (err) {
handleError({ message: `[sendToNative]:${err}` });
}
// config plane native enabled destinations, still not completely loaded
// in the page, add the events to a queue and process later
if (!this.clientIntegrationObjects) {
logger.debug("pushing in replay queue");
// new event processing after analytics initialized but integrations not fetched from BE
this.toBeProcessedByIntegrationArray.push([type, rudderElement]);
}
// convert integrations object to server identified names, kind of hack now!
transformToServerNames(rudderElement.message.integrations);
// self analytics process, send to rudder
enqueue.call(this, rudderElement, type);
logger.debug(`${type} is called `);
if (callback) {
callback();
}
} catch (error) {
handleError(error);
}
}
/**
* add campaign parsed details under context
* @param {*} rudderElement
*/
addCampaignInfo(rudderElement) {
const { search } = getDefaultPageProperties();
const campaign = utm(search);
if (
rudderElement.message.context &&
typeof rudderElement.message.context === "object"
) {
rudderElement.message.context.campaign = campaign;
}
}
/**
* process options parameter
* Apart from top level keys merge everyting under context
* context.page's default properties are overriden by same keys of
* provided properties in case of page call
*
* @param {*} rudderElement
* @param {*} options
* @memberof Analytics
*/
processOptionsParam(rudderElement, options) {
const { type, properties } = rudderElement.message;
this.addCampaignInfo(rudderElement);
// assign page properties to context.page
rudderElement.message.context.page =
type == "page"
? this.getContextPageProperties(properties)
: this.getContextPageProperties();
const toplevelElements = [
"integrations",
"anonymousId",
"originalTimestamp",
];
for (const key in options) {
if (toplevelElements.includes(key)) {
rudderElement.message[key] = options[key];
} else if (key !== "context") {
rudderElement.message.context = merge(rudderElement.message.context, {
[key]: options[key],
});
} else if (typeof options[key] === "object" && options[key] != null) {
rudderElement.message.context = merge(rudderElement.message.context, {
...options[key],
});
} else {
logger.error(
"[Analytics: processOptionsParam] context passed in options is not object"
);
}
}
}
getPageProperties(properties, options) {
const defaultPageProperties = getDefaultPageProperties();
const optionPageProperties = options && options.page ? options.page : {};
for (const key in defaultPageProperties) {
if (properties[key] === undefined) {
properties[key] =
optionPageProperties[key] || defaultPageProperties[key];
}
}
return properties;
}
// Assign page properties to context.page if the same property is not provided under context.page
getContextPageProperties(properties) {
const defaultPageProperties = getDefaultPageProperties();
const contextPageProperties = {};
for (const key in defaultPageProperties) {
contextPageProperties[key] =
properties && properties[key]
? properties[key]
: defaultPageProperties[key];
}
return contextPageProperties;
}
/**
* Clear user information
*
* @memberof Analytics
*/
reset(flag) {
if (!this.loaded) return;
if (flag) {
this.anonymousId = "";
}
this.userId = "";
this.userTraits = {};
this.groupId = "";
this.groupTraits = {};
this.storage.clear(flag);
}
getAnonymousId() {
// if (!this.loaded) return;
this.anonymousId = this.storage.getAnonymousId();
if (!this.anonymousId) {
this.setAnonymousId();
}
return this.anonymousId;
}
getUserTraits() {
return this.userTraits;
}
/**
* Sets anonymous id in the followin precedence:
* 1. anonymousId: Id directly provided to the function.
* 2. rudderAmpLinkerParm: value generated from linker query parm (rudderstack)
* using praseLinker util.
* 3. generateUUID: A new uniquie id is generated and assigned.
*
* @param {string} anonymousId
* @param {string} rudderAmpLinkerParm
*/
setAnonymousId(anonymousId, rudderAmpLinkerParm) {
// if (!this.loaded) return;
const parsedAnonymousIdObj = rudderAmpLinkerParm
? parseLinker(rudderAmpLinkerParm)
: null;
const parsedAnonymousId = parsedAnonymousIdObj
? parsedAnonymousIdObj.rs_amp_id
: null;
this.anonymousId = anonymousId || parsedAnonymousId || generateUUID();
this.storage.setAnonymousId(this.anonymousId);
}
isValidWriteKey(writeKey) {
if (
!writeKey ||
typeof writeKey !== "string" ||
writeKey.trim().length == 0
) {
return false;
}
return true;
}
isValidServerUrl(serverUrl) {
if (
!serverUrl ||
typeof serverUrl !== "string" ||
serverUrl.trim().length == 0
) {