@mparticle/web-google-analytics-4-client-kit 1.0.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.
@@ -0,0 +1,1315 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ function Common() {}
6
+
7
+ Common.prototype.forwarderSettings = null;
8
+
9
+ Common.prototype.mergeObjects = function () {
10
+ var resObj = {};
11
+ for (var i = 0; i < arguments.length; i += 1) {
12
+ var obj = arguments[i],
13
+ keys = Object.keys(obj);
14
+ for (var j = 0; j < keys.length; j += 1) {
15
+ resObj[keys[j]] = obj[keys[j]];
16
+ }
17
+ }
18
+ return resObj;
19
+ };
20
+
21
+ Common.prototype.getUserId = function (
22
+ user,
23
+ externalUserIdentityType,
24
+ hashUserId
25
+ ) {
26
+ if (!user) {
27
+ return;
28
+ }
29
+
30
+ var externalUserIdentityTypes = {
31
+ none: 'None',
32
+ customerId: 'CustomerId',
33
+ other: 'Other',
34
+ other2: 'Other2',
35
+ other3: 'Other3',
36
+ other4: 'Other4',
37
+ other5: 'Other5',
38
+ other6: 'Other6',
39
+ other7: 'Other7',
40
+ other8: 'Other8',
41
+ other9: 'Other9',
42
+ other10: 'Other10',
43
+ mpid: 'mpid',
44
+ };
45
+
46
+ var userId,
47
+ userIdentities = user.getUserIdentities().userIdentities;
48
+ if (externalUserIdentityType !== externalUserIdentityTypes.none) {
49
+ switch (externalUserIdentityType) {
50
+ case 'CustomerId':
51
+ userId = userIdentities.customerid;
52
+ break;
53
+ case externalUserIdentityTypes.other:
54
+ userId = userIdentities.other;
55
+ break;
56
+ case externalUserIdentityTypes.other2:
57
+ userId = userIdentities.other2;
58
+ break;
59
+ case externalUserIdentityTypes.other3:
60
+ userId = userIdentities.other3;
61
+ break;
62
+ case externalUserIdentityTypes.other4:
63
+ userId = userIdentities.other4;
64
+ break;
65
+ case externalUserIdentityTypes.other5:
66
+ userId = userIdentities.other5;
67
+ break;
68
+ case externalUserIdentityTypes.other6:
69
+ userId = userIdentities.other6;
70
+ break;
71
+ case externalUserIdentityTypes.other7:
72
+ userId = userIdentities.other7;
73
+ break;
74
+ case externalUserIdentityTypes.other8:
75
+ userId = userIdentities.other8;
76
+ break;
77
+ case externalUserIdentityTypes.other9:
78
+ userId = userIdentities.other9;
79
+ break;
80
+ case externalUserIdentityTypes.other10:
81
+ userId = userIdentities.other10;
82
+ break;
83
+ case externalUserIdentityTypes.mpid:
84
+ userId = user.getMPID();
85
+ break;
86
+ default:
87
+ console.warn(
88
+ 'External identity type not found for setting identity on ' +
89
+ 'GA4' +
90
+ '. User not set. Please double check your implementation.'
91
+ );
92
+ }
93
+ }
94
+ if (userId) {
95
+ if (hashUserId == 'True') {
96
+ userId = window.mParticle.generateHash(userId);
97
+ }
98
+ } else {
99
+ console.warn(
100
+ 'External identity type of ' +
101
+ externalUserIdentityType +
102
+ ' not set on the user'
103
+ );
104
+ }
105
+ return userId;
106
+ };
107
+
108
+ var common = Common;
109
+
110
+ function CommerceHandler(common) {
111
+ this.common = common || {};
112
+ }
113
+
114
+ var ProductActionTypes = {
115
+ Unknown: 0,
116
+ AddToCart: 10,
117
+ Click: 14,
118
+ Checkout: 12,
119
+ CheckoutOption: 13,
120
+ Impression: 22,
121
+ Purchase: 16,
122
+ Refund: 17,
123
+ RemoveFromCart: 11,
124
+ ViewDetail: 15,
125
+ AddToWishlist: 20,
126
+ };
127
+
128
+ var PromotionActionTypes = {
129
+ PromotionClick: 19,
130
+ PromotionView: 18,
131
+ };
132
+
133
+ // Custom Flags
134
+ var GA4_COMMERCE_EVENT_TYPE = 'GA4.CommerceEventType',
135
+ GA4_SHIPPING_TIER = 'GA4.ShippingTier',
136
+ GA4_PAYMENT_TYPE = 'GA4.PaymentType';
137
+
138
+ var ADD_SHIPPING_INFO = 'add_shipping_info',
139
+ ADD_PAYMENT_INFO = 'add_payment_info',
140
+ VIEW_CART = 'view_cart';
141
+
142
+ CommerceHandler.prototype.logCommerceEvent = function (event) {
143
+ var needsCurrency = true,
144
+ needsValue = true,
145
+ ga4CommerceEventParameters,
146
+ isViewCartEvent = false;
147
+
148
+ // GA4 has a view_cart event which MP does not support via a ProductActionType
149
+ // In order to log a view_cart event, pass ProductActionType.Unknown along with
150
+ // the proper custom flag
151
+ // Unknown ProductActionTypes without a custom flag will reach the switch statement
152
+ // below and throw an error to the customer
153
+ if (event.EventCategory === ProductActionTypes.Unknown) {
154
+ if (
155
+ event.CustomFlags &&
156
+ event.CustomFlags[GA4_COMMERCE_EVENT_TYPE] === VIEW_CART
157
+ ) {
158
+ isViewCartEvent = true;
159
+ return logViewCart(event);
160
+ }
161
+ }
162
+ // Handle Impressions
163
+ if (event.EventCategory === ProductActionTypes.Impression) {
164
+ return logImpressionEvent(event);
165
+ // Handle Promotions
166
+ } else if (
167
+ event.EventCategory === PromotionActionTypes.PromotionClick ||
168
+ event.EventCategory === PromotionActionTypes.PromotionView
169
+ ) {
170
+ return logPromotionEvent(event);
171
+ }
172
+
173
+ ga4CommerceEventParameters = buildParameters(event);
174
+ if (event.EventAttributes) {
175
+ ga4CommerceEventParameters = this.common.mergeObjects(
176
+ ga4CommerceEventParameters,
177
+ event.EventAttributes
178
+ );
179
+ }
180
+
181
+ switch (event.EventCategory) {
182
+ case ProductActionTypes.AddToCart:
183
+ case ProductActionTypes.RemoveFromCart:
184
+ ga4CommerceEventParameters = buildAddOrRemoveCartItem(event);
185
+ break;
186
+ case ProductActionTypes.Checkout:
187
+ ga4CommerceEventParameters = buildCheckout(event);
188
+ break;
189
+ case ProductActionTypes.Click:
190
+ ga4CommerceEventParameters = buildSelectItem(event);
191
+
192
+ needsCurrency = false;
193
+ needsValue = false;
194
+ break;
195
+ case ProductActionTypes.Purchase:
196
+ ga4CommerceEventParameters = buildPurchase(event);
197
+ break;
198
+ case ProductActionTypes.Refund:
199
+ ga4CommerceEventParameters = buildRefund(event);
200
+ break;
201
+ case ProductActionTypes.ViewDetail:
202
+ ga4CommerceEventParameters = buildViewItem(event);
203
+ break;
204
+ case ProductActionTypes.AddToWishlist:
205
+ ga4CommerceEventParameters = buildAddToWishlist(event);
206
+ break;
207
+
208
+ case ProductActionTypes.CheckoutOption:
209
+ return logCheckoutOptionEvent(event);
210
+
211
+ default:
212
+ // a view cart event is handled at the beginning of this function
213
+ if (!isViewCartEvent) {
214
+ console.error(
215
+ 'Unsupported Commerce Event. Event not sent.',
216
+ event
217
+ );
218
+ return false;
219
+ }
220
+ }
221
+
222
+ // CheckoutOption, Promotions, and Impressions will not make it to this code
223
+ if (needsCurrency) {
224
+ ga4CommerceEventParameters.currency = event.CurrencyCode;
225
+ }
226
+
227
+ if (needsValue) {
228
+ ga4CommerceEventParameters.value =
229
+ (event.CustomFlags && event.CustomFlags['GA4.Value']) ||
230
+ event.ProductAction.TotalAmount ||
231
+ null;
232
+ }
233
+
234
+ gtag('event', mapGA4EcommerceEventName(event), ga4CommerceEventParameters);
235
+ return true;
236
+ };
237
+
238
+ function buildParameters(event) {
239
+ return {
240
+ items: buildProductsList(event.ProductAction.ProductList),
241
+ coupon: event.ProductAction ? event.ProductAction.CouponCode : null,
242
+ };
243
+ }
244
+
245
+ function buildAddOrRemoveCartItem(event) {
246
+ return {
247
+ items: buildProductsList(event.ProductAction.ProductList),
248
+ };
249
+ }
250
+
251
+ function buildCheckout(event) {
252
+ return {
253
+ items: buildProductsList(event.ProductAction.ProductList),
254
+ coupon: event.ProductAction ? event.ProductAction.CouponCode : null,
255
+ };
256
+ }
257
+
258
+ function buildCheckoutOptions(event) {
259
+ var parameters = event.EventAttributes;
260
+ parameters.items = buildProductsList(event.ProductAction.ProductList);
261
+ parameters.coupon = event.ProductAction
262
+ ? event.ProductAction.CouponCode
263
+ : null;
264
+
265
+ return parameters;
266
+ }
267
+
268
+ function parseImpression(impression) {
269
+ return {
270
+ item_list_id: impression.ProductImpressionList,
271
+ item_list_name: impression.ProductImpressionList,
272
+ items: buildProductsList(impression.ProductList),
273
+ };
274
+ }
275
+
276
+ function buildSelectItem(event) {
277
+ return {
278
+ items: buildProductsList(event.ProductAction.ProductList),
279
+ };
280
+ }
281
+
282
+ function buildViewItem(event) {
283
+ return {
284
+ items: buildProductsList(event.ProductAction.ProductList),
285
+ };
286
+ }
287
+
288
+ function buildPromotion(promotion) {
289
+ return parsePromotion(promotion);
290
+ }
291
+
292
+ function buildPurchase(event) {
293
+ return {
294
+ transaction_id: event.ProductAction.TransactionId,
295
+ value: event.ProductAction.TotalAmount,
296
+ affiliation: event.ProductAction.Affiliation,
297
+ coupon: event.ProductAction.CouponCode,
298
+ shipping: event.ProductAction.ShippingAmount,
299
+ tax: event.ProductAction.TaxAmount,
300
+ items: buildProductsList(event.ProductAction.ProductList),
301
+ };
302
+ }
303
+ function buildRefund(event) {
304
+ return {
305
+ transaction_id: event.ProductAction.TransactionId,
306
+ value: event.ProductAction.TotalAmount,
307
+ affiliation: event.ProductAction.Affiliation,
308
+ coupon: event.ProductAction.CouponCode,
309
+ shipping: event.ProductAction.ShippingAmount,
310
+ tax: event.ProductAction.TaxAmount,
311
+ items: buildProductsList(event.ProductAction.ProductList),
312
+ };
313
+ }
314
+ function buildAddToWishlist(event) {
315
+ return {
316
+ value: event.ProductAction.TotalAmount,
317
+ items: buildProductsList(event.ProductAction.ProductList),
318
+ };
319
+ }
320
+
321
+ function buildAddShippingInfo(event) {
322
+ return {
323
+ coupon:
324
+ event.ProductAction && event.ProductAction.CouponCode
325
+ ? event.ProductAction.CouponCode
326
+ : null,
327
+ shipping_tier:
328
+ event.CustomFlags && event.CustomFlags[GA4_SHIPPING_TIER]
329
+ ? event.CustomFlags[GA4_SHIPPING_TIER]
330
+ : null,
331
+ items: buildProductsList(event.ProductAction.ProductList),
332
+ };
333
+ }
334
+
335
+ function buildAddPaymentInfo(event) {
336
+ return {
337
+ coupon:
338
+ event.ProductAction && event.ProductAction.CouponCode
339
+ ? event.ProductAction.CouponCode
340
+ : null,
341
+ payment_type:
342
+ event.CustomFlags && event.CustomFlags[GA4_PAYMENT_TYPE]
343
+ ? event.CustomFlags[GA4_PAYMENT_TYPE]
344
+ : null,
345
+ items: buildProductsList(event.ProductAction.ProductList),
346
+ };
347
+ }
348
+
349
+ // Utility function
350
+ function toUnderscore(string) {
351
+ return string
352
+ .split(/(?=[A-Z])/)
353
+ .join('_')
354
+ .toLowerCase();
355
+ }
356
+
357
+ function parseProduct(_product) {
358
+ var product = {};
359
+
360
+ for (var key in _product) {
361
+ switch (key) {
362
+ case 'Sku':
363
+ product.item_id = _product.Sku;
364
+ break;
365
+ case 'Name':
366
+ product.item_name = _product.Name;
367
+ break;
368
+ case 'Brand':
369
+ product.item_brand = _product.Brand;
370
+ break;
371
+ case 'Category':
372
+ product.item_category = _product.Category;
373
+ break;
374
+ case 'Variant':
375
+ product.item_variant = _product.Variant;
376
+ break;
377
+ default:
378
+ product[toUnderscore(key)] = _product[key];
379
+ }
380
+ }
381
+
382
+ return product;
383
+ }
384
+
385
+ function parsePromotion(_promotion) {
386
+ var promotion = {};
387
+
388
+ for (var key in _promotion) {
389
+ switch (key) {
390
+ case 'Id':
391
+ promotion.promotion_id = _promotion.Id;
392
+ break;
393
+ case 'Creative':
394
+ promotion.creative_name = _promotion.Creative;
395
+ break;
396
+ case 'Name':
397
+ promotion.promotion_name = _promotion.Name;
398
+ break;
399
+ case 'Position':
400
+ promotion.creative_slot = _promotion.Position;
401
+ break;
402
+ default:
403
+ promotion[toUnderscore(key)] = _promotion[key];
404
+ }
405
+ }
406
+
407
+ return promotion;
408
+ }
409
+
410
+ function buildProductsList(products) {
411
+ var productsList = [];
412
+
413
+ products.forEach(function (product) {
414
+ productsList.push(parseProduct(product));
415
+ });
416
+
417
+ return productsList;
418
+ }
419
+
420
+ function mapGA4EcommerceEventName(event) {
421
+ switch (event.EventCategory) {
422
+ case ProductActionTypes.AddToCart:
423
+ return 'add_to_cart';
424
+ case ProductActionTypes.AddToWishlist:
425
+ return 'add_to_wishlist';
426
+ case ProductActionTypes.RemoveFromCart:
427
+ return 'remove_from_cart';
428
+ case ProductActionTypes.Purchase:
429
+ return 'purchase';
430
+ case ProductActionTypes.Checkout:
431
+ return 'begin_checkout';
432
+ case ProductActionTypes.CheckoutOption:
433
+ return getCheckoutOptionEventName(event.CustomFlags);
434
+ case ProductActionTypes.Click:
435
+ return 'select_item';
436
+ case ProductActionTypes.Impression:
437
+ return 'view_item_list';
438
+ case ProductActionTypes.Refund:
439
+ return 'refund';
440
+ case ProductActionTypes.ViewDetail:
441
+ return 'view_item';
442
+ case PromotionActionTypes.PromotionClick:
443
+ return 'select_promotion';
444
+ case PromotionActionTypes.PromotionView:
445
+ return 'view_promotion';
446
+ case ProductActionTypes.Unknown:
447
+ if (
448
+ event.CustomFlags &&
449
+ event.CustomFlags[GA4_COMMERCE_EVENT_TYPE] === VIEW_CART
450
+ ) {
451
+ return 'view_cart';
452
+ }
453
+ break;
454
+ default:
455
+ console.error('Product Action Type not supported');
456
+ return null;
457
+ }
458
+ }
459
+
460
+ function getCheckoutOptionEventName(customFlags) {
461
+ switch (customFlags[GA4_COMMERCE_EVENT_TYPE]) {
462
+ case ADD_SHIPPING_INFO:
463
+ return ADD_SHIPPING_INFO;
464
+ case ADD_PAYMENT_INFO:
465
+ return ADD_PAYMENT_INFO;
466
+ default:
467
+ return 'set_checkout_option';
468
+ }
469
+ }
470
+
471
+ // Google previously had a CheckoutOption event, and now this has been split into 2 GA4 events - add_shipping_info and add_payment_info
472
+ // Since MP still uses CheckoutOption, we must map this to the 2 events using custom flags. To prevent any data loss from customers
473
+ // migrating from UA to GA4, we will set a default `set_checkout_option` which matches Firebase's data model.
474
+ function logCheckoutOptionEvent(event) {
475
+ try {
476
+ var customFlags = event.CustomFlags,
477
+ GA4CommerceEventType = customFlags[GA4_COMMERCE_EVENT_TYPE],
478
+ ga4CommerceEventParameters;
479
+
480
+ // 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
481
+ if (!customFlags || !GA4CommerceEventType) {
482
+ console.error(
483
+ '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.'
484
+ );
485
+ }
486
+
487
+ switch (GA4CommerceEventType) {
488
+ case ADD_SHIPPING_INFO:
489
+ ga4CommerceEventParameters = buildAddShippingInfo(event);
490
+ break;
491
+ case ADD_PAYMENT_INFO:
492
+ ga4CommerceEventParameters = buildAddPaymentInfo(event);
493
+ break;
494
+ default:
495
+ ga4CommerceEventParameters = buildCheckoutOptions(event);
496
+ break;
497
+ }
498
+ } catch (error) {
499
+ console.error(
500
+ 'There is an issue with the custom flags in your CheckoutOption event. The event was not sent. Plrease review the docs and fix.',
501
+ error
502
+ );
503
+ return false;
504
+ }
505
+
506
+ gtag('event', mapGA4EcommerceEventName(event), ga4CommerceEventParameters);
507
+
508
+ return true;
509
+ }
510
+
511
+ function logPromotionEvent(event) {
512
+ try {
513
+ var ga4CommerceEventParameters;
514
+ event.PromotionAction.PromotionList.forEach(function (promotion) {
515
+ ga4CommerceEventParameters = buildPromotion(promotion);
516
+ gtag(
517
+ 'event',
518
+ mapGA4EcommerceEventName(event),
519
+ ga4CommerceEventParameters
520
+ );
521
+ });
522
+ return true;
523
+ } catch (error) {
524
+ console.error(
525
+ 'Error logging Promotions to GA4. Promotions not logged.',
526
+ error
527
+ );
528
+ }
529
+ return false;
530
+ }
531
+
532
+ function logImpressionEvent(event) {
533
+ try {
534
+ var ga4CommerceEventParameters;
535
+ event.ProductImpressions.forEach(function (impression) {
536
+ ga4CommerceEventParameters = parseImpression(impression);
537
+
538
+ gtag(
539
+ 'event',
540
+ mapGA4EcommerceEventName(event),
541
+ ga4CommerceEventParameters
542
+ );
543
+ });
544
+ } catch (error) {
545
+ console.log(
546
+ 'Error logging Impressions to GA4. Impressions not logged',
547
+ error
548
+ );
549
+ return false;
550
+ }
551
+ return true;
552
+ }
553
+
554
+ function logViewCart(event) {
555
+ var ga4CommerceEventParameters = buildViewCart(event);
556
+ ga4CommerceEventParameters.currency = event.CurrencyCode;
557
+
558
+ ga4CommerceEventParameters.value =
559
+ (event.CustomFlags && event.CustomFlags['GA4.Value']) ||
560
+ event.ProductAction.TotalAmount ||
561
+ null;
562
+ gtag('event', mapGA4EcommerceEventName(event), ga4CommerceEventParameters);
563
+ return true;
564
+ }
565
+
566
+ function buildViewCart(event) {
567
+ return {
568
+ items: buildProductsList(event.ProductAction.ProductList),
569
+ };
570
+ }
571
+
572
+ var commerceHandler = CommerceHandler;
573
+
574
+ function EventHandler(common) {
575
+ this.common = common || {};
576
+ }
577
+
578
+ EventHandler.prototype.logEvent = function (event) {
579
+ gtag('event', event.EventName, event.EventAttributes || {});
580
+ };
581
+
582
+ EventHandler.prototype.logError = function () {
583
+ console.warn('Google Analytics 4 does not support error events.');
584
+ };
585
+
586
+ EventHandler.prototype.logPageView = function (event) {
587
+ var TITLE = 'Google.Title';
588
+ var LOCATION = 'Google.Location';
589
+ var pageTitle, pageLocation;
590
+ if (event.CustomFlags.hasOwnProperty(TITLE)) {
591
+ pageTitle = event.CustomFlags[TITLE];
592
+ } else {
593
+ pageTitle = document.title;
594
+ }
595
+
596
+ if (event.CustomFlags.hasOwnProperty(LOCATION)) {
597
+ pageLocation = event.CustomFlags[LOCATION];
598
+ } else {
599
+ pageLocation = location.href;
600
+ }
601
+ gtag('event', 'page_view', {
602
+ page_title: pageTitle,
603
+ page_location: pageLocation,
604
+ });
605
+
606
+ return true;
607
+ };
608
+
609
+ var eventHandler = EventHandler;
610
+
611
+ /*
612
+ The 'mParticleUser' is an object with methods get user Identities and set/get user attributes
613
+ Partners can determine what userIds are available to use in their SDK
614
+ Call mParticleUser.getUserIdentities() to return an object of userIdentities --> { userIdentities: {customerid: '1234', email: 'email@gmail.com'} }
615
+ For more identity types, see http://docs.mparticle.com/developers/sdk/javascript/identity#allowed-identity-types
616
+ Call mParticleUser.getMPID() to get mParticle ID
617
+ For any additional methods, see http://docs.mparticle.com/developers/sdk/javascript/apidocs/classes/mParticle.Identity.getCurrentUser().html
618
+ */
619
+
620
+ /*
621
+ identityApiRequest has the schema:
622
+ {
623
+ userIdentities: {
624
+ customerid: '123',
625
+ email: 'abc'
626
+ }
627
+ }
628
+ For more userIdentity types, see http://docs.mparticle.com/developers/sdk/javascript/identity#allowed-identity-types
629
+ */
630
+
631
+ function IdentityHandler(common) {
632
+ this.common = common || {};
633
+ }
634
+ IdentityHandler.prototype.onUserIdentified = function (mParticleUser) {
635
+ var userId = this.common.getUserId(
636
+ mParticleUser,
637
+ this.common.forwarderSettings.externalUserIdentityType,
638
+ this.common.forwarderSettings.hashUserId
639
+ );
640
+ gtag('config', this.common.forwarderSettings.measurementId, {
641
+ // do not send a page view when updating the userid in an identity call
642
+ send_page_view: false,
643
+ user_id: userId,
644
+ });
645
+ };
646
+ IdentityHandler.prototype.onIdentifyComplete = function (
647
+ mParticleUser,
648
+ identityApiRequest
649
+ ) {};
650
+ IdentityHandler.prototype.onLoginComplete = function (
651
+ mParticleUser,
652
+ identityApiRequest
653
+ ) {};
654
+ IdentityHandler.prototype.onLogoutComplete = function (
655
+ mParticleUser,
656
+ identityApiRequest
657
+ ) {};
658
+ IdentityHandler.prototype.onModifyComplete = function (
659
+ mParticleUser,
660
+ identityApiRequest
661
+ ) {};
662
+
663
+ /* In previous versions of the mParticle web SDK, setting user identities on
664
+ kits is only reachable via the onSetUserIdentity method below. We recommend
665
+ filling out `onSetUserIdentity` for maximum compatibility
666
+ */
667
+ IdentityHandler.prototype.onSetUserIdentity = function (
668
+ forwarderSettings,
669
+ id,
670
+ type
671
+ ) {};
672
+
673
+ var identityHandler = IdentityHandler;
674
+
675
+ var initialization = {
676
+ name: 'GoogleAnalytics4EventForwarder',
677
+ /* ****** Fill out initForwarder to load your SDK ******
678
+ Note that not all arguments may apply to your SDK initialization.
679
+ These are passed from mParticle, but leave them even if they are not being used.
680
+ forwarderSettings contain settings that your SDK requires in order to initialize
681
+ userAttributes example: {gender: 'male', age: 25}
682
+ userIdentities example: { 1: 'customerId', 2: 'facebookId', 7: 'emailid@email.com' }
683
+ additional identityTypes can be found at https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L88-L101
684
+ */
685
+ initForwarder: function (
686
+ forwarderSettings,
687
+ testMode,
688
+ userAttributes,
689
+ userIdentities,
690
+ processEvent,
691
+ eventQueue,
692
+ isInitialized,
693
+ common
694
+ ) {
695
+ common.forwarderSettings = forwarderSettings;
696
+ var measurementId = forwarderSettings.measurementId;
697
+ var userIdType = forwarderSettings.externalUserIdentityType;
698
+ var hashUserId = forwarderSettings.hashUserId;
699
+ var configSettings = {
700
+ send_page_view: forwarderSettings.enablePageView === 'True',
701
+ };
702
+ window.dataLayer = window.dataLayer || [];
703
+
704
+ window.gtag = function () {
705
+ window.dataLayer.push(arguments);
706
+ };
707
+
708
+ if (!testMode) {
709
+ var clientScript = document.createElement('script');
710
+ clientScript.type = 'text/javascript';
711
+ clientScript.async = true;
712
+ clientScript.src =
713
+ 'https://www.googletagmanager.com/gtag/js?id=' + measurementId;
714
+ (
715
+ document.getElementsByTagName('head')[0] ||
716
+ document.getElementsByTagName('body')[0]
717
+ ).appendChild(clientScript);
718
+
719
+ clientScript.onload = function () {
720
+ gtag('js', new Date());
721
+
722
+ if (window.mParticle.getVersion().split('.')[0] === '2') {
723
+ var userId = common.getUserId(
724
+ mParticle.Identity.getCurrentUser(),
725
+ userIdType,
726
+ hashUserId
727
+ );
728
+ if (userId) {
729
+ configSettings.user_id = userId;
730
+ }
731
+ }
732
+ gtag('config', measurementId, configSettings);
733
+ isInitialized = true;
734
+
735
+ if (window.dataLayer && gtag && eventQueue.length > 0) {
736
+ for (var i = 0; i < eventQueue.length; i++) {
737
+ processEvent(eventQueue[i]);
738
+ }
739
+ eventQueue = [];
740
+ }
741
+ };
742
+ } else {
743
+ isInitialized = true;
744
+ }
745
+ return isInitialized;
746
+ },
747
+ };
748
+
749
+ var initialization_1 = initialization;
750
+
751
+ var sessionHandler = {
752
+ onSessionStart: function(event) {
753
+
754
+ },
755
+ onSessionEnd: function(event) {
756
+
757
+ }
758
+ };
759
+
760
+ var sessionHandler_1 = sessionHandler;
761
+
762
+ function UserAttributeHandler(common) {
763
+ this.common = common || {};
764
+ }
765
+
766
+ // `mParticleUser` was removed from the function signatures onRemoveUserAttribute, onSetUserAttribute, and onConsentStateUpload because they were not being used
767
+ // In the future if mParticleUser is ever required for an implementation of any of the below APIs, see https://github.com/mparticle-integrations/mparticle-javascript-integration-example/blob/master/src/user-attribute-handler.js
768
+ // for previous function signatures
769
+
770
+ UserAttributeHandler.prototype.onRemoveUserAttribute = function(key) {
771
+ var userAttributes = {};
772
+ userAttributes[key] = null;
773
+ gtag('set', 'user_properties', userAttributes);
774
+ };
775
+
776
+ UserAttributeHandler.prototype.onSetUserAttribute = function(key, value) {
777
+ var userAttributes = {};
778
+ userAttributes[key] = value;
779
+ gtag('set', 'user_properties', userAttributes);
780
+ };
781
+
782
+ // TODO: Commenting this out for now because Integrations PM still determining if this is in scope or not
783
+ // UserAttributeHandler.prototype.onConsentStateUpdated = function() // oldState,
784
+ // newState,
785
+ // mParticleUser
786
+ // {};
787
+
788
+ var userAttributeHandler = UserAttributeHandler;
789
+
790
+ // =============== REACH OUT TO MPARTICLE IF YOU HAVE ANY QUESTIONS ===============
791
+ //
792
+ // Copyright 2018 mParticle, Inc.
793
+ //
794
+ // Licensed under the Apache License, Version 2.0 (the "License");
795
+ // you may not use this file except in compliance with the License.
796
+ // You may obtain a copy of the License at
797
+ //
798
+ // http://www.apache.org/licenses/LICENSE-2.0
799
+ //
800
+ // Unless required by applicable law or agreed to in writing, software
801
+ // distributed under the License is distributed on an "AS IS" BASIS,
802
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
803
+ // See the License for the specific language governing permissions and
804
+ // limitations under the License.
805
+
806
+
807
+
808
+
809
+
810
+
811
+
812
+
813
+
814
+ var name = initialization_1.name,
815
+ moduleId = initialization_1.moduleId,
816
+ MessageType = {
817
+ SessionStart: 1,
818
+ SessionEnd: 2,
819
+ PageView: 3,
820
+ PageEvent: 4,
821
+ CrashReport: 5,
822
+ OptOut: 6,
823
+ Commerce: 16,
824
+ Media: 20,
825
+ };
826
+
827
+ var constructor = function() {
828
+ var self = this,
829
+ isInitialized = false,
830
+ forwarderSettings,
831
+ reportingService,
832
+ eventQueue = [];
833
+
834
+ self.name = initialization_1.name;
835
+ self.moduleId = initialization_1.moduleId;
836
+ self.common = new common();
837
+
838
+ function initForwarder(
839
+ settings,
840
+ service,
841
+ testMode,
842
+ trackerId,
843
+ userAttributes,
844
+ userIdentities,
845
+ appVersion,
846
+ appName,
847
+ customFlags,
848
+ clientId
849
+ ) {
850
+ forwarderSettings = settings;
851
+
852
+ if (
853
+ typeof window !== 'undefined' &&
854
+ window.mParticle.isTestEnvironment
855
+ ) {
856
+ reportingService = function() {};
857
+ } else {
858
+ reportingService = service;
859
+ }
860
+
861
+ try {
862
+ initialization_1.initForwarder(
863
+ settings,
864
+ testMode,
865
+ userAttributes,
866
+ userIdentities,
867
+ processEvent,
868
+ eventQueue,
869
+ isInitialized,
870
+ self.common,
871
+ appVersion,
872
+ appName,
873
+ customFlags,
874
+ clientId
875
+ );
876
+ self.eventHandler = new eventHandler(self.common);
877
+ self.identityHandler = new identityHandler(self.common);
878
+ self.userAttributeHandler = new userAttributeHandler(self.common);
879
+ self.commerceHandler = new commerceHandler(self.common);
880
+
881
+ isInitialized = true;
882
+ } catch (e) {
883
+ console.log('Failed to initialize ' + name + ' - ' + e);
884
+ }
885
+ }
886
+
887
+ function processEvent(event) {
888
+ var reportEvent = false;
889
+ if (isInitialized) {
890
+ try {
891
+ if (event.EventDataType === MessageType.SessionStart) {
892
+ reportEvent = logSessionStart(event);
893
+ } else if (event.EventDataType === MessageType.SessionEnd) {
894
+ reportEvent = logSessionEnd(event);
895
+ } else if (event.EventDataType === MessageType.CrashReport) {
896
+ reportEvent = logError(event);
897
+ } else if (event.EventDataType === MessageType.PageView) {
898
+ reportEvent = logPageView(event);
899
+ } else if (event.EventDataType === MessageType.Commerce) {
900
+ reportEvent = logEcommerceEvent(event);
901
+ } else if (event.EventDataType === MessageType.PageEvent) {
902
+ reportEvent = logEvent(event);
903
+ } else if (event.EventDataType === MessageType.Media) {
904
+ // Kits should just treat Media Events as generic Events
905
+ reportEvent = logEvent(event);
906
+ }
907
+ if (reportEvent === true && reportingService) {
908
+ reportingService(self, event);
909
+ return 'Successfully sent to ' + name;
910
+ } else {
911
+ return (
912
+ 'Error logging event or event type not supported on forwarder ' +
913
+ name
914
+ );
915
+ }
916
+ } catch (e) {
917
+ return 'Failed to send to ' + name + ' ' + e;
918
+ }
919
+ } else {
920
+ eventQueue.push(event);
921
+ return (
922
+ "Can't send to forwarder " +
923
+ name +
924
+ ', not initialized. Event added to queue.'
925
+ );
926
+ }
927
+ }
928
+
929
+ function logSessionStart(event) {
930
+ try {
931
+ sessionHandler_1.onSessionStart(event);
932
+ return true;
933
+ } catch (e) {
934
+ return {
935
+ error: 'Error starting session on forwarder ' + name + '; ' + e,
936
+ };
937
+ }
938
+ }
939
+
940
+ function logSessionEnd(event) {
941
+ try {
942
+ sessionHandler_1.onSessionEnd(event);
943
+ return true;
944
+ } catch (e) {
945
+ return {
946
+ error: 'Error ending session on forwarder ' + name + '; ' + e,
947
+ };
948
+ }
949
+ }
950
+
951
+ function logError(event) {
952
+ try {
953
+ self.eventHandler.logError(event);
954
+ return true;
955
+ } catch (e) {
956
+ return {
957
+ error: 'Error logging error on forwarder ' + name + '; ' + e,
958
+ };
959
+ }
960
+ }
961
+
962
+ function logPageView(event) {
963
+ try {
964
+ self.eventHandler.logPageView(event);
965
+ return true;
966
+ } catch (e) {
967
+ return {
968
+ error:
969
+ 'Error logging page view on forwarder ' + name + '; ' + e,
970
+ };
971
+ }
972
+ }
973
+
974
+ function logEvent(event) {
975
+ try {
976
+ self.eventHandler.logEvent(event);
977
+ return true;
978
+ } catch (e) {
979
+ return {
980
+ error: 'Error logging event on forwarder ' + name + '; ' + e,
981
+ };
982
+ }
983
+ }
984
+
985
+ function logEcommerceEvent(event) {
986
+ try {
987
+ self.commerceHandler.logCommerceEvent(event);
988
+ return true;
989
+ } catch (e) {
990
+ return {
991
+ error:
992
+ 'Error logging purchase event on forwarder ' +
993
+ name +
994
+ '; ' +
995
+ e,
996
+ };
997
+ }
998
+ }
999
+
1000
+ function setUserAttribute(key, value) {
1001
+ if (isInitialized) {
1002
+ try {
1003
+ self.userAttributeHandler.onSetUserAttribute(
1004
+ key,
1005
+ value,
1006
+ forwarderSettings
1007
+ );
1008
+ return 'Successfully set user attribute on forwarder ' + name;
1009
+ } catch (e) {
1010
+ return (
1011
+ 'Error setting user attribute on forwarder ' +
1012
+ name +
1013
+ '; ' +
1014
+ e
1015
+ );
1016
+ }
1017
+ } else {
1018
+ return (
1019
+ "Can't set user attribute on forwarder " +
1020
+ name +
1021
+ ', not initialized'
1022
+ );
1023
+ }
1024
+ }
1025
+
1026
+ function removeUserAttribute(key) {
1027
+ if (isInitialized) {
1028
+ try {
1029
+ self.userAttributeHandler.onRemoveUserAttribute(
1030
+ key,
1031
+ forwarderSettings
1032
+ );
1033
+ return (
1034
+ 'Successfully removed user attribute on forwarder ' + name
1035
+ );
1036
+ } catch (e) {
1037
+ return (
1038
+ 'Error removing user attribute on forwarder ' +
1039
+ name +
1040
+ '; ' +
1041
+ e
1042
+ );
1043
+ }
1044
+ } else {
1045
+ return (
1046
+ "Can't remove user attribute on forwarder " +
1047
+ name +
1048
+ ', not initialized'
1049
+ );
1050
+ }
1051
+ }
1052
+
1053
+ function setUserIdentity(id, type) {
1054
+ if (isInitialized) {
1055
+ try {
1056
+ self.identityHandler.onSetUserIdentity(
1057
+ forwarderSettings,
1058
+ id,
1059
+ type
1060
+ );
1061
+ return 'Successfully set user Identity on forwarder ' + name;
1062
+ } catch (e) {
1063
+ return (
1064
+ 'Error removing user attribute on forwarder ' +
1065
+ name +
1066
+ '; ' +
1067
+ e
1068
+ );
1069
+ }
1070
+ } else {
1071
+ return (
1072
+ "Can't call setUserIdentity on forwarder " +
1073
+ name +
1074
+ ', not initialized'
1075
+ );
1076
+ }
1077
+ }
1078
+
1079
+ function onUserIdentified(user) {
1080
+ if (isInitialized) {
1081
+ try {
1082
+ self.identityHandler.onUserIdentified(user);
1083
+
1084
+ return (
1085
+ 'Successfully called onUserIdentified on forwarder ' + name
1086
+ );
1087
+ } catch (e) {
1088
+ return {
1089
+ error:
1090
+ 'Error calling onUserIdentified on forwarder ' +
1091
+ name +
1092
+ '; ' +
1093
+ e,
1094
+ };
1095
+ }
1096
+ } else {
1097
+ return (
1098
+ "Can't set new user identities on forwader " +
1099
+ name +
1100
+ ', not initialized'
1101
+ );
1102
+ }
1103
+ }
1104
+
1105
+ function onIdentifyComplete(user, filteredIdentityRequest) {
1106
+ if (isInitialized) {
1107
+ try {
1108
+ self.identityHandler.onIdentifyComplete(
1109
+ user,
1110
+ filteredIdentityRequest
1111
+ );
1112
+
1113
+ return (
1114
+ 'Successfully called onIdentifyComplete on forwarder ' +
1115
+ name
1116
+ );
1117
+ } catch (e) {
1118
+ return {
1119
+ error:
1120
+ 'Error calling onIdentifyComplete on forwarder ' +
1121
+ name +
1122
+ '; ' +
1123
+ e,
1124
+ };
1125
+ }
1126
+ } else {
1127
+ return (
1128
+ "Can't call onIdentifyCompleted on forwader " +
1129
+ name +
1130
+ ', not initialized'
1131
+ );
1132
+ }
1133
+ }
1134
+
1135
+ function onLoginComplete(user, filteredIdentityRequest) {
1136
+ if (isInitialized) {
1137
+ try {
1138
+ self.identityHandler.onLoginComplete(
1139
+ user,
1140
+ filteredIdentityRequest
1141
+ );
1142
+
1143
+ return (
1144
+ 'Successfully called onLoginComplete on forwarder ' + name
1145
+ );
1146
+ } catch (e) {
1147
+ return {
1148
+ error:
1149
+ 'Error calling onLoginComplete on forwarder ' +
1150
+ name +
1151
+ '; ' +
1152
+ e,
1153
+ };
1154
+ }
1155
+ } else {
1156
+ return (
1157
+ "Can't call onLoginComplete on forwader " +
1158
+ name +
1159
+ ', not initialized'
1160
+ );
1161
+ }
1162
+ }
1163
+
1164
+ function onLogoutComplete(user, filteredIdentityRequest) {
1165
+ if (isInitialized) {
1166
+ try {
1167
+ self.identityHandler.onLogoutComplete(
1168
+ user,
1169
+ filteredIdentityRequest
1170
+ );
1171
+
1172
+ return (
1173
+ 'Successfully called onLogoutComplete on forwarder ' + name
1174
+ );
1175
+ } catch (e) {
1176
+ return {
1177
+ error:
1178
+ 'Error calling onLogoutComplete on forwarder ' +
1179
+ name +
1180
+ '; ' +
1181
+ e,
1182
+ };
1183
+ }
1184
+ } else {
1185
+ return (
1186
+ "Can't call onLogoutComplete on forwader " +
1187
+ name +
1188
+ ', not initialized'
1189
+ );
1190
+ }
1191
+ }
1192
+
1193
+ function onModifyComplete(user, filteredIdentityRequest) {
1194
+ if (isInitialized) {
1195
+ try {
1196
+ self.identityHandler.onModifyComplete(
1197
+ user,
1198
+ filteredIdentityRequest
1199
+ );
1200
+
1201
+ return (
1202
+ 'Successfully called onModifyComplete on forwarder ' + name
1203
+ );
1204
+ } catch (e) {
1205
+ return {
1206
+ error:
1207
+ 'Error calling onModifyComplete on forwarder ' +
1208
+ name +
1209
+ '; ' +
1210
+ e,
1211
+ };
1212
+ }
1213
+ } else {
1214
+ return (
1215
+ "Can't call onModifyComplete on forwader " +
1216
+ name +
1217
+ ', not initialized'
1218
+ );
1219
+ }
1220
+ }
1221
+
1222
+ function setOptOut(isOptingOutBoolean) {
1223
+ if (isInitialized) {
1224
+ try {
1225
+ self.initialization.setOptOut(isOptingOutBoolean);
1226
+
1227
+ return 'Successfully called setOptOut on forwarder ' + name;
1228
+ } catch (e) {
1229
+ return {
1230
+ error:
1231
+ 'Error calling setOptOut on forwarder ' +
1232
+ name +
1233
+ '; ' +
1234
+ e,
1235
+ };
1236
+ }
1237
+ } else {
1238
+ return (
1239
+ "Can't call setOptOut on forwader " +
1240
+ name +
1241
+ ', not initialized'
1242
+ );
1243
+ }
1244
+ }
1245
+
1246
+ this.init = initForwarder;
1247
+ this.process = processEvent;
1248
+ this.setUserAttribute = setUserAttribute;
1249
+ this.removeUserAttribute = removeUserAttribute;
1250
+ this.onUserIdentified = onUserIdentified;
1251
+ this.setUserIdentity = setUserIdentity;
1252
+ this.onIdentifyComplete = onIdentifyComplete;
1253
+ this.onLoginComplete = onLoginComplete;
1254
+ this.onLogoutComplete = onLogoutComplete;
1255
+ this.onModifyComplete = onModifyComplete;
1256
+ this.setOptOut = setOptOut;
1257
+ };
1258
+
1259
+ function getId() {
1260
+ return moduleId;
1261
+ }
1262
+
1263
+ function isObject(val) {
1264
+ return (
1265
+ val != null && typeof val === 'object' && Array.isArray(val) === false
1266
+ );
1267
+ }
1268
+
1269
+ function register(config) {
1270
+ if (!config) {
1271
+ console.log(
1272
+ 'You must pass a config object to register the kit ' + name
1273
+ );
1274
+ return;
1275
+ }
1276
+
1277
+ if (!isObject(config)) {
1278
+ console.log(
1279
+ "'config' must be an object. You passed in a " + typeof config
1280
+ );
1281
+ return;
1282
+ }
1283
+
1284
+ if (isObject(config.kits)) {
1285
+ config.kits[name] = {
1286
+ constructor: constructor,
1287
+ };
1288
+ } else {
1289
+ config.kits = {};
1290
+ config.kits[name] = {
1291
+ constructor: constructor,
1292
+ };
1293
+ }
1294
+ console.log(
1295
+ 'Successfully registered ' + name + ' to your mParticle configuration'
1296
+ );
1297
+ }
1298
+
1299
+ if (typeof window !== 'undefined') {
1300
+ if (window && window.mParticle && window.mParticle.addForwarder) {
1301
+ window.mParticle.addForwarder({
1302
+ name: name,
1303
+ constructor: constructor,
1304
+ getId: getId,
1305
+ });
1306
+ }
1307
+ }
1308
+
1309
+ var webKitWrapper = {
1310
+ register: register,
1311
+ };
1312
+ var webKitWrapper_1 = webKitWrapper.register;
1313
+
1314
+ exports.default = webKitWrapper;
1315
+ exports.register = webKitWrapper_1;