@mparticle/web-google-analytics-4-client-kit 1.3.1 → 1.4.1

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.
@@ -2,10 +2,123 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ var googleConsentValues = {
6
+ // Server Integration uses 'Unspecified' as a value when the setting is 'not set'.
7
+ // However, this is not used by Google's Web SDK. We are referencing it here as a comment
8
+ // as a record of this distinction and for posterity.
9
+ // If Google ever adds this for web, the line can just be uncommented to support this.
10
+ //
11
+ // Docs:
12
+ // Web: https://developers.google.com/tag-platform/gtagjs/reference#consent
13
+ // S2S: https://developers.google.com/google-ads/api/reference/rpc/v15/ConsentStatusEnum.ConsentStatus
14
+ //
15
+ // Unspecified: 'unspecified',
16
+ Denied: 'denied',
17
+ Granted: 'granted',
18
+ };
19
+
20
+ // Declares list of valid Google Consent Properties
21
+ var googleConsentProperties = [
22
+ 'ad_storage',
23
+ 'ad_user_data',
24
+ 'ad_personalization',
25
+ 'analytics_storage',
26
+ ];
27
+
28
+ function ConsentHandler(common) {
29
+ this.common = common || {};
30
+ }
31
+
32
+ ConsentHandler.prototype.getUserConsentState = function () {
33
+ var userConsentState = {};
34
+
35
+ if (mParticle.Identity && mParticle.Identity.getCurrentUser) {
36
+ var currentUser = mParticle.Identity.getCurrentUser();
37
+
38
+ if (!currentUser) {
39
+ return {};
40
+ }
41
+
42
+ var consentState =
43
+ mParticle.Identity.getCurrentUser().getConsentState();
44
+
45
+ if (consentState && consentState.getGDPRConsentState) {
46
+ userConsentState = consentState.getGDPRConsentState();
47
+ }
48
+ }
49
+
50
+ return userConsentState;
51
+ };
52
+
53
+ ConsentHandler.prototype.getEventConsentState = function (eventConsentState) {
54
+ return eventConsentState && eventConsentState.getGDPRConsentState
55
+ ? eventConsentState.getGDPRConsentState()
56
+ : {};
57
+ };
58
+
59
+ ConsentHandler.prototype.getConsentSettings = function () {
60
+ var consentSettings = {};
61
+
62
+ var googleToMpConsentSettingsMapping = {
63
+ ad_user_data: 'defaultAdUserDataConsentSDK',
64
+ ad_personalization: 'defaultAdPersonalizationConsentSDK',
65
+ ad_storage: 'defaultAdStorageConsentSDK',
66
+ analytics_storage: 'defaultAnalyticsStorageConsentSDK',
67
+ };
68
+
69
+ var forwarderSettings = this.common.forwarderSettings;
70
+
71
+ Object.keys(googleToMpConsentSettingsMapping).forEach(function (
72
+ googleConsentKey
73
+ ) {
74
+ var mpConsentSettingKey =
75
+ googleToMpConsentSettingsMapping[googleConsentKey];
76
+ var googleConsentValuesKey = forwarderSettings[mpConsentSettingKey];
77
+
78
+ if (googleConsentValuesKey && mpConsentSettingKey) {
79
+ consentSettings[googleConsentKey] =
80
+ googleConsentValues[googleConsentValuesKey];
81
+ }
82
+ });
83
+
84
+ return consentSettings;
85
+ };
86
+
87
+ ConsentHandler.prototype.generateConsentStatePayloadFromMappings = function (
88
+ consentState,
89
+ mappings
90
+ ) {
91
+ if (!mappings) return {};
92
+
93
+ var payload = this.common.cloneObject(this.common.consentPayloadDefaults);
94
+
95
+ for (var i = 0; i <= mappings.length - 1; i++) {
96
+ var mappingEntry = mappings[i];
97
+ var mpMappedConsentName = mappingEntry.map;
98
+ var googleMappedConsentName = mappingEntry.value;
99
+
100
+ if (
101
+ consentState[mpMappedConsentName] &&
102
+ googleConsentProperties.indexOf(googleMappedConsentName) !== -1
103
+ ) {
104
+ payload[googleMappedConsentName] = consentState[mpMappedConsentName]
105
+ .Consented
106
+ ? googleConsentValues.Granted
107
+ : googleConsentValues.Denied;
108
+ }
109
+ }
110
+
111
+ return payload;
112
+ };
113
+
114
+ var consent = ConsentHandler;
115
+
5
116
  // Google requires event and user attribute strings to have specific limits
6
117
  // in place when sending to data layer.
7
118
  // https://support.google.com/analytics/answer/11202874?sjid=7958830619827381593-NA
8
119
 
120
+
121
+
9
122
  var EVENT_NAME_MAX_LENGTH = 40;
10
123
  var EVENT_ATTRIBUTE_KEY_MAX_LENGTH = 40;
11
124
  var EVENT_ATTRIBUTE_VAL_MAX_LENGTH = 100;
@@ -37,7 +150,13 @@ function isEmpty(value) {
37
150
  return value == null || !(Object.keys(value) || value).length;
38
151
  }
39
152
 
40
- function Common() {}
153
+ function Common() {
154
+ this.consentMappings = [];
155
+ this.consentPayloadDefaults = {};
156
+ this.consentPayloadAsString = '';
157
+
158
+ this.consentHandler = new consent(this);
159
+ }
41
160
 
42
161
  Common.prototype.forwarderSettings = null;
43
162
 
@@ -309,6 +428,12 @@ Common.prototype.getUserId = function (
309
428
  }
310
429
  };
311
430
 
431
+ Common.prototype.cloneObject = function (obj) {
432
+ return JSON.parse(JSON.stringify(obj));
433
+ };
434
+
435
+ Common.prototype.isEmpty = isEmpty;
436
+
312
437
  var common = Common;
313
438
 
314
439
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
@@ -369,18 +494,18 @@ CommerceHandler.prototype.logCommerceEvent = function (event) {
369
494
  event.CustomFlags[GA4_COMMERCE_EVENT_TYPE] === VIEW_CART
370
495
  ) {
371
496
  isViewCartEvent = true;
372
- return logViewCart(event, affiliation);
497
+ return this.logViewCart(event, affiliation);
373
498
  }
374
499
  }
375
500
  // Handle Impressions
376
501
  if (event.EventCategory === ProductActionTypes.Impression) {
377
- return logImpressionEvent(event, affiliation);
502
+ return this.logImpressionEvent(event, affiliation);
378
503
  // Handle Promotions
379
504
  } else if (
380
505
  event.EventCategory === PromotionActionTypes.PromotionClick ||
381
506
  event.EventCategory === PromotionActionTypes.PromotionView
382
507
  ) {
383
- return logPromotionEvent(event);
508
+ return this.logPromotionEvent(event);
384
509
  }
385
510
 
386
511
  switch (event.EventCategory) {
@@ -414,7 +539,7 @@ CommerceHandler.prototype.logCommerceEvent = function (event) {
414
539
  break;
415
540
 
416
541
  case ProductActionTypes.CheckoutOption:
417
- return logCheckoutOptionEvent(event, affiliation);
542
+ return this.logCheckoutOptionEvent(event, affiliation);
418
543
 
419
544
  default:
420
545
  // a view cart event is handled at the beginning of this function
@@ -451,10 +576,146 @@ CommerceHandler.prototype.logCommerceEvent = function (event) {
451
576
  null;
452
577
  }
453
578
 
454
- gtag('event', mapGA4EcommerceEventName(event), ga4CommerceEventParameters);
579
+ return this.sendCommerceEventToGA4(
580
+ mapGA4EcommerceEventName(event),
581
+ ga4CommerceEventParameters
582
+ );
583
+ };
584
+
585
+ CommerceHandler.prototype.sendCommerceEventToGA4 = function (
586
+ eventName,
587
+ eventAttributes
588
+ ) {
589
+ if (this.common.forwarderSettings.measurementId) {
590
+ eventAttributes.send_to = this.common.forwarderSettings.measurementId;
591
+ }
592
+
593
+ gtag('event', eventName, eventAttributes);
594
+
455
595
  return true;
456
596
  };
457
597
 
598
+ // Google previously had a CheckoutOption event, and now this has been split into 2 GA4 events - add_shipping_info and add_payment_info
599
+ // Since MP still uses CheckoutOption, we must map this to the 2 events using custom flags. To prevent any data loss from customers
600
+ // migrating from UA to GA4, we will set a default `set_checkout_option` which matches Firebase's data model.
601
+ CommerceHandler.prototype.logCheckoutOptionEvent = function (
602
+ event,
603
+ affiliation
604
+ ) {
605
+ try {
606
+ var customFlags = event.CustomFlags,
607
+ GA4CommerceEventType = customFlags[GA4_COMMERCE_EVENT_TYPE],
608
+ ga4CommerceEventParameters;
609
+
610
+ // if no custom flags exist or there is no GA4CommerceEventType, the user has not updated their code from using legacy GA which still supports checkout_option
611
+ if (!customFlags || !GA4CommerceEventType) {
612
+ console.error(
613
+ 'Your checkout option event for the Google Analytics 4 integration is missing a custom flag for "GA4.CommerceEventType". The event was sent using the deprecated set_checkout_option event. Review mParticle docs for GA4 for the custom flags to add.'
614
+ );
615
+ }
616
+
617
+ switch (GA4CommerceEventType) {
618
+ case ADD_SHIPPING_INFO:
619
+ ga4CommerceEventParameters = buildAddShippingInfo(
620
+ event,
621
+ affiliation
622
+ );
623
+ break;
624
+ case ADD_PAYMENT_INFO:
625
+ ga4CommerceEventParameters = buildAddPaymentInfo(
626
+ event,
627
+ affiliation
628
+ );
629
+ break;
630
+ default:
631
+ ga4CommerceEventParameters = buildCheckoutOptions(
632
+ event,
633
+ affiliation
634
+ );
635
+ break;
636
+ }
637
+ } catch (error) {
638
+ console.error(
639
+ 'There is an issue with the custom flags in your CheckoutOption event. The event was not sent. Plrease review the docs and fix.',
640
+ error
641
+ );
642
+ return false;
643
+ }
644
+
645
+ return this.sendCommerceEventToGA4(
646
+ mapGA4EcommerceEventName(event),
647
+ ga4CommerceEventParameters
648
+ );
649
+ };
650
+
651
+ CommerceHandler.prototype.logPromotionEvent = function (event) {
652
+ var self = this;
653
+ try {
654
+ var ga4CommerceEventParameters;
655
+ event.PromotionAction.PromotionList.forEach(function (promotion) {
656
+ ga4CommerceEventParameters = buildPromotion(promotion);
657
+
658
+ self.sendCommerceEventToGA4(
659
+ mapGA4EcommerceEventName(event),
660
+ ga4CommerceEventParameters
661
+ );
662
+ });
663
+
664
+ return true;
665
+ } catch (error) {
666
+ console.error(
667
+ 'Error logging Promotions to GA4. Promotions not logged.',
668
+ error
669
+ );
670
+ return false;
671
+ }
672
+ };
673
+
674
+ CommerceHandler.prototype.logImpressionEvent = function (event, affiliation) {
675
+ var self = this;
676
+ try {
677
+ var ga4CommerceEventParameters;
678
+ event.ProductImpressions.forEach(function (impression) {
679
+ ga4CommerceEventParameters = parseImpression(
680
+ impression,
681
+ affiliation
682
+ );
683
+
684
+ self.sendCommerceEventToGA4(
685
+ mapGA4EcommerceEventName(event),
686
+ ga4CommerceEventParameters
687
+ );
688
+ });
689
+
690
+ return true;
691
+ } catch (error) {
692
+ console.log(
693
+ 'Error logging Impressions to GA4. Impressions not logged',
694
+ error
695
+ );
696
+ return false;
697
+ }
698
+ };
699
+
700
+ CommerceHandler.prototype.logViewCart = function (event, affiliation) {
701
+ var ga4CommerceEventParameters = buildViewCart(event, affiliation);
702
+ ga4CommerceEventParameters = this.common.mergeObjects(
703
+ ga4CommerceEventParameters,
704
+ this.common.limitEventAttributes(event.EventAttributes)
705
+ );
706
+ ga4CommerceEventParameters.currency = event.CurrencyCode;
707
+
708
+ ga4CommerceEventParameters.value =
709
+ (event.CustomFlags && event.CustomFlags['GA4.Value']) ||
710
+ event.ProductAction.TotalAmount ||
711
+ null;
712
+
713
+ return this.sendCommerceEventToGA4(
714
+ mapGA4EcommerceEventName(event),
715
+ ga4CommerceEventParameters
716
+ );
717
+ };
718
+
458
719
  function buildAddOrRemoveCartItem(event, affiliation) {
459
720
  return {
460
721
  items: buildProductsList(event.ProductAction.ProductList, affiliation),
@@ -709,117 +970,6 @@ function getCheckoutOptionEventName(customFlags) {
709
970
  }
710
971
  }
711
972
 
712
- // Google previously had a CheckoutOption event, and now this has been split into 2 GA4 events - add_shipping_info and add_payment_info
713
- // Since MP still uses CheckoutOption, we must map this to the 2 events using custom flags. To prevent any data loss from customers
714
- // migrating from UA to GA4, we will set a default `set_checkout_option` which matches Firebase's data model.
715
- function logCheckoutOptionEvent(event, affiliation) {
716
- try {
717
- var customFlags = event.CustomFlags,
718
- GA4CommerceEventType = customFlags[GA4_COMMERCE_EVENT_TYPE],
719
- ga4CommerceEventParameters;
720
-
721
- // if no custom flags exist or there is no GA4CommerceEventType, the user has not updated their code from using legacy GA which still supports checkout_option
722
- if (!customFlags || !GA4CommerceEventType) {
723
- console.error(
724
- 'Your checkout option event for the Google Analytics 4 integration is missing a custom flag for "GA4.CommerceEventType". The event was sent using the deprecated set_checkout_option event. Review mParticle docs for GA4 for the custom flags to add.'
725
- );
726
- }
727
-
728
- switch (GA4CommerceEventType) {
729
- case ADD_SHIPPING_INFO:
730
- ga4CommerceEventParameters = buildAddShippingInfo(
731
- event,
732
- affiliation
733
- );
734
- break;
735
- case ADD_PAYMENT_INFO:
736
- ga4CommerceEventParameters = buildAddPaymentInfo(
737
- event,
738
- affiliation
739
- );
740
- break;
741
- default:
742
- ga4CommerceEventParameters = buildCheckoutOptions(
743
- event,
744
- affiliation
745
- );
746
- break;
747
- }
748
- } catch (error) {
749
- console.error(
750
- 'There is an issue with the custom flags in your CheckoutOption event. The event was not sent. Plrease review the docs and fix.',
751
- error
752
- );
753
- return false;
754
- }
755
-
756
- gtag('event', mapGA4EcommerceEventName(event), ga4CommerceEventParameters);
757
-
758
- return true;
759
- }
760
-
761
- function logPromotionEvent(event) {
762
- try {
763
- var ga4CommerceEventParameters;
764
- event.PromotionAction.PromotionList.forEach(function (promotion) {
765
- ga4CommerceEventParameters = buildPromotion(promotion);
766
- gtag(
767
- 'event',
768
- mapGA4EcommerceEventName(event),
769
- ga4CommerceEventParameters
770
- );
771
- });
772
- return true;
773
- } catch (error) {
774
- console.error(
775
- 'Error logging Promotions to GA4. Promotions not logged.',
776
- error
777
- );
778
- }
779
- return false;
780
- }
781
-
782
- function logImpressionEvent(event, affiliation) {
783
- try {
784
- var ga4CommerceEventParameters;
785
- event.ProductImpressions.forEach(function (impression) {
786
- ga4CommerceEventParameters = parseImpression(
787
- impression,
788
- affiliation
789
- );
790
-
791
- gtag(
792
- 'event',
793
- mapGA4EcommerceEventName(event),
794
- ga4CommerceEventParameters
795
- );
796
- });
797
- } catch (error) {
798
- console.log(
799
- 'Error logging Impressions to GA4. Impressions not logged',
800
- error
801
- );
802
- return false;
803
- }
804
- return true;
805
- }
806
-
807
- function logViewCart(event, affiliation) {
808
- var ga4CommerceEventParameters = buildViewCart(event, affiliation);
809
- ga4CommerceEventParameters = self$1.common.mergeObjects(
810
- ga4CommerceEventParameters,
811
- self$1.common.limitEventAttributes(event.EventAttributes)
812
- );
813
- ga4CommerceEventParameters.currency = event.CurrencyCode;
814
-
815
- ga4CommerceEventParameters.value =
816
- (event.CustomFlags && event.CustomFlags['GA4.Value']) ||
817
- event.ProductAction.TotalAmount ||
818
- null;
819
- gtag('event', mapGA4EcommerceEventName(event), ga4CommerceEventParameters);
820
- return true;
821
- }
822
-
823
973
  function buildViewCart(event, affiliation) {
824
974
  return {
825
975
  items: buildProductsList(event.ProductAction.ProductList, affiliation),
@@ -832,6 +982,32 @@ function EventHandler(common) {
832
982
  this.common = common || {};
833
983
  }
834
984
 
985
+ EventHandler.prototype.maybeSendConsentUpdateToGa4 = function (event) {
986
+ // If consent payload is empty,
987
+ // we never sent an initial default consent state
988
+ // so we shouldn't send an update.
989
+ if (this.common.consentPayloadAsString && this.common.consentMappings) {
990
+ var eventConsentState = this.common.consentHandler.getEventConsentState(
991
+ event.ConsentState
992
+ );
993
+
994
+ if (!this.common.isEmpty(eventConsentState)) {
995
+ var updatedConsentPayload =
996
+ this.common.consentHandler.generateConsentStatePayloadFromMappings(
997
+ eventConsentState,
998
+ this.common.consentMappings
999
+ );
1000
+
1001
+ var eventConsentAsString = JSON.stringify(updatedConsentPayload);
1002
+
1003
+ if (eventConsentAsString !== this.common.consentPayloadAsString) {
1004
+ gtag('consent', 'update', updatedConsentPayload);
1005
+ this.common.consentPayloadAsString = eventConsentAsString;
1006
+ }
1007
+ }
1008
+ }
1009
+ };
1010
+
835
1011
  // TODO: https://mparticle-eng.atlassian.net/browse/SQDSDKS-5715
836
1012
  EventHandler.prototype.sendEventToGA4 = function (eventName, eventAttributes) {
837
1013
  var standardizedEventName;
@@ -849,6 +1025,11 @@ EventHandler.prototype.sendEventToGA4 = function (eventName, eventAttributes) {
849
1025
  standardizedAttributes
850
1026
  );
851
1027
 
1028
+ if (this.common.forwarderSettings.measurementId) {
1029
+ standardizedAttributes.send_to =
1030
+ this.common.forwarderSettings.measurementId;
1031
+ }
1032
+
852
1033
  gtag(
853
1034
  'event',
854
1035
  this.common.truncateEventName(standardizedEventName),
@@ -857,6 +1038,7 @@ EventHandler.prototype.sendEventToGA4 = function (eventName, eventAttributes) {
857
1038
  };
858
1039
 
859
1040
  EventHandler.prototype.logEvent = function (event) {
1041
+ this.maybeSendConsentUpdateToGa4(event);
860
1042
  this.sendEventToGA4(event.EventName, event.EventAttributes);
861
1043
  };
862
1044
 
@@ -897,6 +1079,7 @@ EventHandler.prototype.logPageView = function (event) {
897
1079
  event.EventAttributes
898
1080
  );
899
1081
 
1082
+ this.maybeSendConsentUpdateToGa4(event);
900
1083
  this.sendEventToGA4('page_view', eventAttributes);
901
1084
 
902
1085
  return true;
@@ -996,7 +1179,7 @@ var initialization = {
996
1179
  // The API to allow a customer to provide the cleansing callback
997
1180
  // relies on window.GoogleAnalytics4Kit to exist. When MP is initialized
998
1181
  // via the snippet, the kit code adds it to the window automatically.
999
- // However, when initialized via npm, it does not exist, and so we have
1182
+ // However, when initialized via npm, it does not exist, and so we have
1000
1183
  // to set it manually here.
1001
1184
  window.GoogleAnalytics4Kit = window.GoogleAnalytics4Kit || {};
1002
1185
 
@@ -1010,6 +1193,19 @@ var initialization = {
1010
1193
  var configSettings = {
1011
1194
  send_page_view: forwarderSettings.enablePageView === 'True',
1012
1195
  };
1196
+
1197
+ if (forwarderSettings.consentMappingSDK) {
1198
+ common.consentMappings = parseSettingsString(
1199
+ forwarderSettings.consentMappingSDK
1200
+ );
1201
+ } else {
1202
+ // Ensures consent mappings is an empty array
1203
+ // for future use
1204
+ common.consentMappings = [];
1205
+ common.consentPayloadDefaults = {};
1206
+ common.consentPayloadAsString = '';
1207
+ }
1208
+
1013
1209
  window.dataLayer = window.dataLayer || [];
1014
1210
 
1015
1211
  window.gtag = function () {
@@ -1059,6 +1255,25 @@ var initialization = {
1059
1255
  } else {
1060
1256
  isInitialized = true;
1061
1257
  }
1258
+
1259
+ common.consentPayloadDefaults =
1260
+ common.consentHandler.getConsentSettings();
1261
+ var initialConsentState = common.consentHandler.getUserConsentState();
1262
+
1263
+ var defaultConsentPayload =
1264
+ common.consentHandler.generateConsentStatePayloadFromMappings(
1265
+ initialConsentState,
1266
+ common.consentMappings
1267
+ );
1268
+
1269
+ if (!common.isEmpty(defaultConsentPayload)) {
1270
+ common.consentPayloadAsString = JSON.stringify(
1271
+ defaultConsentPayload
1272
+ );
1273
+
1274
+ gtag('consent', 'default', defaultConsentPayload);
1275
+ }
1276
+
1062
1277
  return isInitialized;
1063
1278
  },
1064
1279
  };
@@ -1074,6 +1289,10 @@ function setClientId(clientId, moduleId) {
1074
1289
  window.mParticle._setIntegrationDelay(moduleId, false);
1075
1290
  }
1076
1291
 
1292
+ function parseSettingsString(settingsString) {
1293
+ return JSON.parse(settingsString.replace(/&quot;/g, '"'));
1294
+ }
1295
+
1077
1296
  var initialization_1 = initialization;
1078
1297
 
1079
1298
  var sessionHandler = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mparticle/web-google-analytics-4-client-kit",
3
- "version": "1.3.1",
3
+ "version": "1.4.1",
4
4
  "author": "mParticle Developers <developers@mparticle.com> (https://www.mparticle.com)",
5
5
  "description": "mParticle integration sdk for Google Analytics",
6
6
  "main": "dist/GoogleAnalytics4EventForwarderClientSide-Kit.common.js",