forked from snowplow/snowplow-javascript-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.ts
More file actions
1408 lines (1298 loc) · 41.2 KB
/
Copy pathcore.ts
File metadata and controls
1408 lines (1298 loc) · 41.2 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
/*
* JavaScript tracker core for Snowplow: core.ts
*
* Copyright (c) 2014-2020 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
import { v4 } from 'uuid';
import { payloadBuilder, PayloadData, PayloadDictionary, isJson } from './payload';
import { globalContexts, ConditionalContextProvider, ContextPrimitive, GlobalContexts } from './contexts';
/**
* Interface common for any Self-Describing JSON such as custom context or
* Self-describing (ex-unstuctured) event
*/
export interface SelfDescribingJson extends Record<string, unknown> {
schema: string;
data: Record<string, unknown>;
}
/**
* Algebraic datatype representing possible timestamp type choice
*/
export type Timestamp = TrueTimestamp | DeviceTimestamp | number;
export interface TrueTimestamp {
readonly type: 'ttm';
readonly value: number;
}
export interface DeviceTimestamp {
readonly type: 'dtm';
readonly value: number;
}
/**
* Pair of timestamp type ready to be included to payload
*/
type TimestampPayload = TrueTimestamp | DeviceTimestamp;
/**
* Transform optional/old-behavior number timestamp into`Timestamp` ADT
*
* @param tstamp optional number or timestamp object
* @returns correct timestamp object
*/
function getTimestamp(tstamp?: Timestamp): TimestampPayload {
if (tstamp == null) {
return { type: 'dtm', value: new Date().getTime() };
} else if (typeof tstamp === 'number') {
return { type: 'dtm', value: tstamp };
} else if (tstamp.type === 'ttm') {
// We can return tstamp here, but this is safer fallback
return { type: 'ttm', value: tstamp.value };
} else {
return { type: 'dtm', value: tstamp.value || new Date().getTime() };
}
}
/**
* Interface containing all Core functions
*/
export interface Core {
/**
* Set a persistent key-value pair to be added to every payload
*
* @param key Field name
* @param value Field value
*/
addPayloadPair: (key: string, value: string) => void;
/**
* Turn base 64 encoding on or off
*
* @param encode Whether to encode payload
*/
setBase64Encoding(encode: boolean): void;
/**
* Merges a dictionary into payloadPairs
*
* @param dict Adds a new payload dictionary to the existing one
*/
addPayloadDict(dict: PayloadDictionary): void;
/**
* Replace payloadPairs with a new dictionary
*
* @param dict Resets all current payload pairs with a new dictionary of pairs
*/
resetPayloadPairs(dict: PayloadDictionary): void;
/**
* Set the tracker version
*
* @param version The version of the current tracker
*/
setTrackerVersion(version: string): void;
/**
* Set the tracker namespace
*
* @param name The trackers namespace
*/
setTrackerNamespace(name: string): void;
/**
* Set the application ID
*
* @param appId An application ID which identifies the current application
*/
setAppId(appId: string): void;
/**
* Set the platform
*
* @param value A valid Snowplow platform value
*/
setPlatform(value: string): void;
/**
* Set the user ID
*
* @param userId The custom user id
*/
setUserId(userId: string): void;
/**
* Set the screen resolution
*
* @param width screen resolution width
* @param height screen resolution height
*/
setScreenResolution(width: string, height: string): void;
/**
* Set the viewport dimensions
*
* @param width viewport width
* @param height viewport height
*/
setViewport(width: string, height: string): void;
/**
* Set the color depth
*
* @param depth A color depth value as string
*/
setColorDepth(depth: string): void;
/**
* Set the timezone
*
* @param timezone A timezone string
*/
setTimezone(timezone: string): void;
/**
* Set the language
*
* @param lang A language string e.g. 'en-UK'
*/
setLang(lang: string): void;
/**
* Set the IP address
*
* @param ip An IP Address string
*/
setIpAddress(ip: string): void;
/**
* Set the Useragent
*
* @param useragent A useragent string
*/
setUseragent(useragent: string): void;
/**
* Log an unstructured event
*
* @deprecated use trackSelfDescribingEvent instead
* @param properties Contains the properties and schema location for the event
* @param context Custom contexts relating to the event
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackUnstructEvent: (
properties: Record<string, unknown>,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
) => PayloadData;
/**
* Log an self-describing (previously unstruct) event
*
* @param properties Contains the properties and schema location for the event
* @param context Custom contexts relating to the event
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackSelfDescribingEvent: (
properties: Record<string, unknown>,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
) => PayloadData;
/**
* Log the page view / visit
*
* @param pageUrl Current page URL
* @param pageTitle The user-defined page title to attach to this page view
* @param referrer URL users came from
* @param context Custom contexts relating to the event
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackPageView(
pageUrl: string,
pageTitle: string,
referrer: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Log that a user is still viewing a given page
* by sending a page ping
*
* @param pageUrl Current page URL
* @param pageTitle The page title to attach to this page ping
* @param referrer URL users came from
* @param minXOffset Minimum page x offset seen in the last ping period
* @param maxXOffset Maximum page x offset seen in the last ping period
* @param minYOffset Minimum page y offset seen in the last ping period
* @param maxYOffset Maximum page y offset seen in the last ping period
* @param context Custom contexts relating to the event
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackPagePing(
pageUrl: string,
pageTitle: string,
referrer: string,
minXOffset: number,
maxXOffset: number,
minYOffset: number,
maxYOffset: number,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track a structured event
*
* @param category The name you supply for the group of objects you want to track
* @param action A string that is uniquely paired with each category, and commonly used to define the type of user interaction for the web object
* @param label An optional string to provide additional dimensions to the event data
* @param property Describes the object or the action performed on it, e.g. quantity of item added to basket
* @param value An integer that you can use to provide numerical data about the user event
* @param context Custom contexts relating to the event
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackStructEvent(
category: string,
action: string,
label: string,
property: string,
value?: number,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track an ecommerce transaction
*
* @param orderId Internal unique order id number for this transaction.
* @param affiliation Partner or store affiliation.
* @param totalValue Total amount of the transaction.
* @param taxValue Tax amount of the transaction.
* @param shipping Shipping charge for the transaction.
* @param city City to associate with transaction.
* @param state State to associate with transaction.
* @param country Country to associate with transaction.
* @param currency Currency to associate with this transaction.
* @param context Context relating to the event.
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackEcommerceTransaction(
orderId: string,
affiliation: string,
totalValue: string,
taxValue?: string,
shipping?: string,
city?: string,
state?: string,
country?: string,
currency?: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track an ecommerce transaction item
*
* @param orderId Required Order ID of the transaction to associate with item.
* @param sku Item's SKU code.
* @param name Product name.
* @param category Product category.
* @param price Product price.
* @param quantity Purchase quantity.
* @param currency Product price currency.
* @param context Context relating to the event.
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackEcommerceTransactionItem(
orderId: string,
sku: string,
name: string,
category: string,
price: string,
quantity: string,
currency?: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track a screen view unstructured event
*
* @param name The name of the screen
* @param id The ID of the screen
* @param context Contexts relating to the event
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackScreenView(
name: string,
id: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Log the link or click with the server
*
* @param targetUrl
* @param elementId
* @param elementClasses
* @param elementTarget
* @param elementContent innerHTML of the link
* @param context Custom contexts relating to the event
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackLinkClick(
targetUrl: string,
elementId: string,
elementClasses: Array<string>,
elementTarget: string,
elementContent: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track an ad being served
*
* @param impressionId Identifier for a particular ad impression
* @param costModel The cost model. 'cpa', 'cpc', or 'cpm'
* @param cost Cost
* @param targetUrl URL ad pointing to
* @param bannerId Identifier for the ad banner displayed
* @param zoneId Identifier for the ad zone
* @param advertiserId Identifier for the advertiser
* @param campaignId Identifier for the campaign which the banner belongs to
* @param context Custom contexts relating to the event
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackAdImpression(
impressionId: string,
costModel: string,
cost: number,
targetUrl: string,
bannerId: string,
zoneId: string,
advertiserId: string,
campaignId: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track an ad being clicked
*
* @param targetUrl (required) The link's target URL
* @param clickId Identifier for the ad click
* @param costModel The cost model. 'cpa', 'cpc', or 'cpm'
* @param cost Cost
* @param bannerId Identifier for the ad banner displayed
* @param zoneId Identifier for the ad zone
* @param impressionId Identifier for a particular ad impression
* @param advertiserId Identifier for the advertiser
* @param campaignId Identifier for the campaign which the banner belongs to
* @param context Custom contexts relating to the event
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackAdClick(
targetUrl: string,
clickId: string,
costModel: string,
cost: number,
bannerId: string,
zoneId: string,
impressionId: string,
advertiserId: string,
campaignId: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track an ad conversion event
*
* @param conversionId Identifier for the ad conversion event
* @param costModel The cost model. 'cpa', 'cpc', or 'cpm'
* @param cost Cost
* @param category The name you supply for the group of objects you want to track
* @param action A string that is uniquely paired with each category
* @param property Describes the object of the conversion or the action performed on it
* @param initialValue Revenue attributable to the conversion at time of conversion
* @param advertiserId Identifier for the advertiser
* @param campaignId Identifier for the campaign which the banner belongs to
* @param context Custom contexts relating to the event
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackAdConversion(
conversionId: string,
costModel: string,
cost: number,
category: string,
action: string,
property: string,
initialValue: number,
advertiserId: string,
campaignId: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track a social event
*
* @param action Social action performed
* @param network Social network
* @param target Object of the social action e.g. the video liked, the tweet retweeted
* @param context Custom contexts relating to the event
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackSocialInteraction(
action: string,
network: string,
target: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track an add-to-cart event
*
* @param sku Item's SKU code.
* @param name Product name.
* @param category Product category.
* @param unitPrice Product price.
* @param quantity Quantity added.
* @param currency Product price currency.
* @param context Context relating to the event.
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackAddToCart(
sku: string,
name: string,
category: string,
unitPrice: string,
quantity: string,
currency?: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track a remove-from-cart event
*
* @param sku Item's SKU code.
* @param name Product name.
* @param category Product category.
* @param unitPrice Product price.
* @param quantity Quantity removed.
* @param currency Product price currency.
* @param context Context relating to the event.
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackRemoveFromCart(
sku: string,
name: string,
category: string,
unitPrice: string,
quantity: string,
currency?: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track the value of a form field changing or receiving focus
*
* @param schema The schema type of the event
* @param formId The parent form ID
* @param elementId ID of the changed element
* @param nodeName "INPUT", "TEXTAREA", or "SELECT"
* @param type Type of the changed element if its type is "INPUT"
* @param elementClasses List of classes of the changed element
* @param value The new value of the changed element
* @param context Context relating to the event.
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackFormFocusOrChange(
schema: string,
formId: string,
elementId: string,
nodeName: string,
type: string,
elementClasses: Array<string>,
value: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track a form submission event
*
* @param formId ID of the form
* @param formClasses Classes of the form
* @param elements Mutable elements within the form
* @param context Context relating to the event.
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackFormSubmission(
formId: string,
formClasses: Array<string>,
elements: Array<Record<string, unknown>>,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track an internal search event
*
* @param terms Search terms
* @param filters Search filters
* @param totalResults Number of results
* @param pageResults Number of results displayed on page
* @param context Context relating to the event.
* @param tstamp Timestamp of the event
* @return Payload
*/
trackSiteSearch(
terms: Array<string>,
filters: Record<string, string | boolean>,
totalResults: number,
pageResults: number,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track a consent withdrawn event
*
* @param all Indicates user withdraws consent for all documents.
* @param id ID number associated with document.
* @param version Version number of document.
* @param name Name of document.
* @param description Description of document.
* @param context Context relating to the event.
* @param tstamp Timestamp of the event.
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackConsentWithdrawn(
all: boolean,
id?: string,
version?: string,
name?: string,
description?: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Track a consent granted event
*
* @param id ID number associated with document.
* @param version Version number of document.
* @param name Name of document.
* @param description Description of document.
* @param expiry Date-time when consent expires.
* @param context Context relating to the event.
* @param tstamp Timestamp of the event.
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
trackConsentGranted(
id: string,
version: string,
name?: string,
description?: string,
expiry?: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData;
/**
* Adds contexts globally, contexts added here will be attached to all applicable events
* @param contexts An array containing either contexts or a conditional contexts
*/
addGlobalContexts(contexts: Array<ConditionalContextProvider | ContextPrimitive>): void;
/**
* Removes all global contexts
*/
clearGlobalContexts(): void;
/**
* Removes previously added global context, performs a deep comparison of the contexts or conditional contexts
* @param contexts An array containing either contexts or a conditional contexts
*/
removeGlobalContexts(contexts: Array<ConditionalContextProvider | ContextPrimitive>): void;
}
/**
* Create a tracker core object
*
* @param base64 Whether to base 64 encode contexts and unstructured event JSONs
* @param callback Function applied to every payload dictionary object
* @return Tracker core
*/
export function trackerCore(base64: boolean, callback?: (PayloadData: PayloadData) => void): Core {
const globalContextsHelper: GlobalContexts = globalContexts();
// Dictionary of key-value pairs which get added to every payload, e.g. tracker version
let payloadPairs: PayloadDictionary = {};
// base 64 encoding should default to true
if (typeof base64 === 'undefined') {
base64 = true;
}
/**
* Returns a copy of a JSON with undefined and null properties removed
*
* @param eventJson JSON object to clean
* @param exemptFields Set of fields which should not be removed even if empty
* @return A cleaned copy of eventJson
*/
const removeEmptyProperties = (
eventJson: PayloadDictionary,
exemptFields?: { [key: string]: boolean }
): PayloadDictionary => {
const ret: PayloadDictionary = {};
exemptFields = exemptFields || {};
for (const k in eventJson) {
if (exemptFields[k] || (eventJson[k] !== null && typeof eventJson[k] !== 'undefined')) {
ret[k] = eventJson[k];
}
}
return ret;
};
/**
* Wraps an array of custom contexts in a self-describing JSON
*
* @param contexts Array of custom context self-describing JSONs
* @return Outer JSON
*/
const completeContexts = (contexts?: Array<SelfDescribingJson>): Record<string, unknown> | undefined => {
if (contexts && contexts.length) {
return {
schema: 'iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-0',
data: contexts,
};
}
return undefined;
};
/**
* Adds all global contexts to a contexts array
*
* @param sb PayloadData
* @param contexts Custom contexts relating to the event
*/
const attachGlobalContexts = (sb: PayloadData, contexts?: Array<SelfDescribingJson>): Array<SelfDescribingJson> => {
const applicableContexts: Array<SelfDescribingJson> = globalContextsHelper.getApplicableContexts(sb);
const returnedContexts: Array<SelfDescribingJson> = [];
if (contexts && contexts.length) {
returnedContexts.push(...contexts);
}
if (applicableContexts && applicableContexts.length) {
returnedContexts.push(...applicableContexts);
}
return returnedContexts;
};
/**
* Gets called by every trackXXX method
* Adds context and payloadPairs name-value pairs to the payload
* Applies the callback to the built payload
*
* @param sb Payload
* @param context Custom contexts relating to the event
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload after the callback is applied
*/
const track = (
sb: PayloadData,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData => {
sb.addDict(payloadPairs);
sb.add('eid', v4());
const timestamp = getTimestamp(tstamp);
sb.add(timestamp.type, timestamp.value.toString());
const allContexts = attachGlobalContexts(sb, context);
const wrappedContexts = completeContexts(allContexts);
if (wrappedContexts !== undefined) {
sb.addJson('cx', 'co', wrappedContexts);
}
if (typeof callback === 'function') {
callback(sb);
}
try {
afterTrack && afterTrack(sb.build());
} catch (ex) {
console.warn('Snowplow: error running custom callback');
}
return sb;
};
/**
* Log an self-describing (previously unstruct) event
*
* @param properties Contains the properties and schema location for the event
* @param context Custom contexts relating to the event
* @param tstamp Timestamp of the event
* @param afterTrack A callback function triggered after event is tracked
* @return Payload
*/
const trackSelfDescribingEvent = (
properties: Record<string, unknown>,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData => {
const sb = payloadBuilder(base64);
const ueJson = {
schema: 'iglu:com.snowplowanalytics.snowplow/unstruct_event/jsonschema/1-0-0',
data: properties,
};
sb.add('e', 'ue');
sb.addJson('ue_px', 'ue_pr', ueJson);
return track(sb, context, tstamp, afterTrack);
};
/**
* Set a persistent key-value pair to be added to every payload
*
* @param key Field name
* @param value Field value
*/
const addPayloadPair = (key: string, value: string): void => {
payloadPairs[key] = value;
};
return {
addPayloadPair,
setBase64Encoding(encode: boolean): void {
base64 = encode;
},
addPayloadDict(dict: PayloadDictionary): void {
for (const key in dict) {
if (Object.prototype.hasOwnProperty.call(dict, key)) {
payloadPairs[key] = dict[key];
}
}
},
resetPayloadPairs(dict: PayloadDictionary): void {
payloadPairs = isJson(dict) ? dict : {};
},
setTrackerVersion(version: string): void {
addPayloadPair('tv', version);
},
setTrackerNamespace(name: string): void {
addPayloadPair('tna', name);
},
setAppId(appId: string): void {
addPayloadPair('aid', appId);
},
setPlatform(value: string): void {
addPayloadPair('p', value);
},
setUserId(userId: string): void {
addPayloadPair('uid', userId);
},
setScreenResolution(width: string, height: string): void {
addPayloadPair('res', width + 'x' + height);
},
setViewport(width: string, height: string): void {
addPayloadPair('vp', width + 'x' + height);
},
setColorDepth(depth: string): void {
addPayloadPair('cd', depth);
},
setTimezone(timezone: string): void {
addPayloadPair('tz', timezone);
},
setLang(lang: string): void {
addPayloadPair('lang', lang);
},
setIpAddress(ip: string): void {
addPayloadPair('ip', ip);
},
setUseragent(useragent: string): void {
addPayloadPair('ua', useragent);
},
trackUnstructEvent: trackSelfDescribingEvent,
trackSelfDescribingEvent,
trackPageView(
pageUrl: string,
pageTitle: string,
referrer: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData {
const sb = payloadBuilder(base64);
sb.add('e', 'pv'); // 'pv' for Page View
sb.add('url', pageUrl);
sb.add('page', pageTitle);
sb.add('refr', referrer);
return track(sb, context, tstamp, afterTrack);
},
trackPagePing(
pageUrl: string,
pageTitle: string,
referrer: string,
minXOffset: number,
maxXOffset: number,
minYOffset: number,
maxYOffset: number,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData {
const sb = payloadBuilder(base64);
sb.add('e', 'pp'); // 'pp' for Page Ping
sb.add('url', pageUrl);
sb.add('page', pageTitle);
sb.add('refr', referrer);
sb.add('pp_mix', minXOffset.toString());
sb.add('pp_max', maxXOffset.toString());
sb.add('pp_miy', minYOffset.toString());
sb.add('pp_may', maxYOffset.toString());
return track(sb, context, tstamp, afterTrack);
},
trackStructEvent(
category: string,
action: string,
label: string,
property: string,
value?: number,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData {
const sb = payloadBuilder(base64);
sb.add('e', 'se'); // 'se' for Structured Event
sb.add('se_ca', category);
sb.add('se_ac', action);
sb.add('se_la', label);
sb.add('se_pr', property);
sb.add('se_va', value == null ? undefined : value.toString());
return track(sb, context, tstamp, afterTrack);
},
trackEcommerceTransaction(
orderId: string,
affiliation: string,
totalValue: string,
taxValue?: string,
shipping?: string,
city?: string,
state?: string,
country?: string,
currency?: string,
context?: Array<SelfDescribingJson>,
tstamp?: Timestamp,
afterTrack?: (Payload: PayloadDictionary) => void
): PayloadData {
const sb = payloadBuilder(base64);
sb.add('e', 'tr'); // 'tr' for Transaction
sb.add('tr_id', orderId);
sb.add('tr_af', affiliation);
sb.add('tr_tt', totalValue);
sb.add('tr_tx', taxValue);
sb.add('tr_sh', shipping);
sb.add('tr_ci', city);