-
Notifications
You must be signed in to change notification settings - Fork 10
/
Avo.ts
1648 lines (1478 loc) · 56.4 KB
/
Avo.ts
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
// Generated by Avo VERSION 148.31.0. You should never have to make changes to this file.
// If you find yourself in the situation where you have to edit the file please contact us at [email protected].
// If you encounter a git conflict in this file run `avo pull` and it will be resolved automatically.
/* tslint:disable */
/* eslint-disable */
// @ts-nocheck
// fetch() polyfill
(function () {
if (typeof window === 'undefined') {
return;
}
var support = {
searchParams: 'URLSearchParams' in self,
iterable: 'Symbol' in self && 'iterator' in Symbol,
blob:
'FileReader' in self &&
'Blob' in self &&
(function () {
try {
new Blob();
return true
} catch (e) {
return false
}
})(),
formData: 'FormData' in self,
arrayBuffer: 'ArrayBuffer' in self
};
function isDataView(obj: any) {
return obj && DataView.prototype.isPrototypeOf(obj)
}
if (support.arrayBuffer) {
var viewClasses = [
'[object Int8Array]',
'[object Uint8Array]',
'[object Uint8ClampedArray]',
'[object Int16Array]',
'[object Uint16Array]',
'[object Int32Array]',
'[object Uint32Array]',
'[object Float32Array]',
'[object Float64Array]'
];
var isArrayBufferView =
ArrayBuffer.isView ||
function (obj) {
return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
};
}
function normalizeName(name: any) {
if (typeof name !== 'string') {
name = String(name);
}
if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) {
throw new TypeError('Invalid character in header field name')
}
return name.toLowerCase()
}
function normalizeValue(value: any) {
if (typeof value !== 'string') {
value = String(value);
}
return value
}
// Build a destructive iterator for the value list
function iteratorFor(items: any) {
var iterator: any = {
next: function () {
var value = items.shift();
return { done: value === undefined, value: value }
}
};
if (support.iterable) {
iterator[Symbol.iterator] = function () {
return iterator
};
}
return iterator
}
function Headers(headers: any) {
// @ts-ignore
(this as any).map = {};
if (headers instanceof Headers) {
(headers as any).forEach(function (value: any, name: any) {
// @ts-ignore
this.append(name, value);
// @ts-ignore
}, this);
} else if (Array.isArray(headers)) {
headers.forEach(function (header: any) {
// @ts-ignore
this.append(header[0], header[1]);
// @ts-ignore
}, this);
} else if (headers) {
Object.getOwnPropertyNames(headers).forEach(function (name: any) {
// @ts-ignore
this.append(name, headers[name]);
// @ts-ignore
}, this);
}
}
Headers.prototype.append = function (name: any, value: any) {
name = normalizeName(name);
value = normalizeValue(value);
var oldValue = this.map[name];
this.map[name] = oldValue ? oldValue + ', ' + value : value;
};
Headers.prototype['delete'] = function (name: any) {
delete this.map[normalizeName(name)];
};
Headers.prototype.get = function (name: any) {
name = normalizeName(name);
return this.has(name) ? this.map[name] : null
};
Headers.prototype.has = function (name: any) {
return this.map.hasOwnProperty(normalizeName(name))
};
Headers.prototype.set = function (name: any, value: any) {
this.map[normalizeName(name)] = normalizeValue(value);
};
Headers.prototype.forEach = function (callback: any, thisArg: any) {
for (var name in this.map) {
if (this.map.hasOwnProperty(name)) {
callback.call(thisArg, this.map[name], name, this);
}
}
};
Headers.prototype.keys = function () {
var items: any = [];
this.forEach(function (_value: any, name: any) {
items.push(name);
});
return iteratorFor(items)
};
Headers.prototype.values = function () {
var items: any = [];
this.forEach(function (value: any) {
items.push(value);
});
return iteratorFor(items)
};
Headers.prototype.entries = function () {
var items: any = [];
this.forEach(function (value: any, name: any) {
items.push([name, value]);
});
return iteratorFor(items)
};
if (support.iterable) {
Headers.prototype[Symbol.iterator] = Headers.prototype.entries;
}
function consumed(body: any) {
if (body.bodyUsed) {
return true;
}
body.bodyUsed = true;
return false;
}
function fileReaderReady(reader: any) {
return new Promise(function (resolve: any, reject: any) {
reader.onload = function () {
resolve(reader.result);
};
reader.onerror = function () {
reject(reader.error);
};
})
}
function readBlobAsArrayBuffer(blob: any) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsArrayBuffer(blob);
return promise
}
function readBlobAsText(blob: any) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsText(blob);
return promise
}
function readArrayBufferAsText(buf: any) {
var view = new Uint8Array(buf);
var chars = new Array(view.length);
for (var i = 0; i < view.length; i++) {
chars[i] = String.fromCharCode(view[i]!);
}
return chars.join('')
}
function bufferClone(buf: any) {
if (buf.slice) {
return buf.slice(0)
} else {
var view = new Uint8Array(buf.byteLength);
view.set(new Uint8Array(buf));
return view.buffer
}
}
function Body() {
// @ts-ignore
(this as any).bodyUsed = false;
// @ts-ignore
(this as any)._initBody = function (body: any) {
this._bodyInit = body;
if (!body) {
this._bodyText = '';
} else if (typeof body === 'string') {
this._bodyText = body;
} else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
this._bodyBlob = body;
} else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
this._bodyFormData = body;
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this._bodyText = body.toString();
} else if (support.arrayBuffer && support.blob && isDataView(body)) {
this._bodyArrayBuffer = bufferClone(body.buffer);
// IE 10-11 can't handle a DataView body.
this._bodyInit = new Blob([this._bodyArrayBuffer]);
} else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
this._bodyArrayBuffer = bufferClone(body);
} else {
this._bodyText = body = Object.prototype.toString.call(body);
}
if (!this.headers.get('content-type')) {
if (typeof body === 'string') {
this.headers.set('content-type', 'text/plain;charset=UTF-8');
} else if (this._bodyBlob && this._bodyBlob.type) {
this.headers.set('content-type', this._bodyBlob.type);
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
}
}
};
if (support.blob) {
// @ts-ignore
(this as any).blob = function () {
var rejected = consumed(this);
if (rejected) {
return Promise.reject(new TypeError('Already read'));
}
if (this._bodyBlob) {
return Promise.resolve(this._bodyBlob);
} else if (this._bodyArrayBuffer) {
return Promise.resolve(new Blob([this._bodyArrayBuffer]));
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as blob');
} else {
return Promise.resolve(new Blob([this._bodyText]));
}
};
// @ts-ignore
(this as any).arrayBuffer = function () {
if (this._bodyArrayBuffer) {
if (consumed(this)) {
return Promise.reject(new TypeError('Already read'));
} else {
return Promise.resolve(this._bodyArrayBuffer);
}
} else {
return this.blob().then(readBlobAsArrayBuffer);
}
};
}
// @ts-ignore
(this as any).text = function () {
var rejected = consumed(this);
if (rejected) {
return Promise.reject(new TypeError('Already read'));
}
if (this._bodyBlob) {
return readBlobAsText(this._bodyBlob);
} else if (this._bodyArrayBuffer) {
return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer));
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as text');
} else {
return Promise.resolve(this._bodyText);
}
};
if (support.formData) {
// @ts-ignore
(this as any).formData = function () {
return this.text().then(decode)
};
}
// @ts-ignore
(this as any).json = function () {
return this.text().then(JSON.parse)
};
// @ts-ignore
return this
}
// HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];
function normalizeMethod(method: any) {
var upcased = method.toUpperCase();
return methods.indexOf(upcased) > -1 ? upcased : method
}
function Request(input: any, options: any) {
options = options || {};
var body = options.body;
if (input instanceof Request) {
if ((input as any).bodyUsed) {
throw new TypeError('Already read')
}
// @ts-ignore
(this as any).url = (input as any).url;
// @ts-ignore
this.credentials = (input as any).credentials;
if (!options.headers) {
// @ts-ignore
this.headers = new Headers((input as any).headers);
}
// @ts-ignore
this.method = (input as any).method;
// @ts-ignore
this.mode = (input as any).mode;
// @ts-ignore
this.signal = (input as any).signal;
if (!body && (input as any)._bodyInit != null) {
body = (input as any)._bodyInit;
(input as any).bodyUsed = true;
}
} else {
// @ts-ignore
this.url = String(input);
}
// @ts-ignore
this.credentials = options.credentials || this.credentials || 'same-origin';
// @ts-ignore
if (options.headers || !this.headers) {
// @ts-ignore
this.headers = new Headers(options.headers);
}
// @ts-ignore
this.method = normalizeMethod(options.method || this.method || 'GET');
// @ts-ignore
this.mode = options.mode || this.mode || null;
// @ts-ignore
this.signal = options.signal || this.signal;
// @ts-ignore
this.referrer = null;
// @ts-ignore
if ((this.method === 'GET' || this.method === 'HEAD') && body) {
throw new TypeError('Body not allowed for GET or HEAD requests')
}
// @ts-ignore
this._initBody(body);
}
Request.prototype.clone = function () {
// @ts-ignore
return new Request(this, { body: this._bodyInit })
};
function decode(body: any) {
var form = new FormData();
body
.trim()
.split('&')
.forEach(function (bytes: any) {
if (bytes) {
var split = bytes.split('=');
var name = split.shift().replace(/\+/g, ' ');
var value = split.join('=').replace(/\+/g, ' ');
form.append(decodeURIComponent(name), decodeURIComponent(value));
}
});
return form
}
function parseHeaders(rawHeaders: any) {
// @ts-ignore
var headers = new Headers();
// Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
// https://tools.ietf.org/html/rfc7230#section-3.2
var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ');
preProcessedHeaders.split(/\r?\n/).forEach(function (line: any) {
var parts = line.split(':');
var key = parts.shift().trim();
if (key) {
var value = parts.join(':').trim();
headers.append(key, value);
}
});
return headers
}
Body.call(Request.prototype);
function Response(bodyInit: any, options: any) {
if (!options) {
options = {};
}
// @ts-ignore
this.type = 'default';
// @ts-ignore
this.status = options.status === undefined ? 200 : options.status;
// @ts-ignore
this.ok = this.status >= 200 && this.status < 300;
// @ts-ignore
this.statusText = 'statusText' in options ? options.statusText : 'OK';
// @ts-ignore
this.headers = new Headers(options.headers);
// @ts-ignore
this.url = options.url || '';
// @ts-ignore
this._initBody(bodyInit);
}
Body.call(Response.prototype);
Response.prototype.clone = function () {
// @ts-ignore
return new Response(this._bodyInit, {
status: this.status,
statusText: this.statusText,
// @ts-ignore
headers: new Headers(this.headers),
url: this.url
})
};
Response.error = function () {
// @ts-ignore
var response = new Response(null, { status: 0, statusText: '' });
response.type = 'error';
return response
};
var redirectStatuses = [301, 302, 303, 307, 308];
Response.redirect = function (url: any, status: any) {
if (redirectStatuses.indexOf(status) === -1) {
throw new RangeError('Invalid status code')
}
// @ts-ignore
return new Response(null, { status: status, headers: { location: url } })
};
(self as any).DOMException = (self as any).DOMException;
try {
new (self as any).DOMException();
} catch (err) {
(self as any).DOMException = function (message: any, name: any) {
this.message = message;
this.name = name;
var error = Error(message);
this.stack = error.stack;
};
(self as any).DOMException.prototype = Object.create(Error.prototype);
(self as any).DOMException.prototype.constructor = (self as any).DOMException;
}
function fetch(input: any, init: any) {
return new Promise(function (resolve, reject) {
// @ts-ignore
var request = new Request(input, init);
if (request.signal && request.signal.aborted) {
return reject(new (self as any).DOMException('Aborted', 'AbortError'))
}
var xhr = new XMLHttpRequest();
function abortXhr() {
xhr.abort();
}
xhr.onload = function () {
var options = {
status: xhr.status,
statusText: xhr.statusText,
headers: parseHeaders(xhr.getAllResponseHeaders() || '')
};
(options as any).url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');
var body = 'response' in xhr ? xhr.response : (xhr as any).responseText;
// @ts-ignore
resolve(new Response(body, options));
};
xhr.onerror = function () {
reject(new TypeError('Network request failed'));
};
xhr.ontimeout = function () {
reject(new TypeError('Network request failed'));
};
xhr.onabort = function () {
reject(new (self as any).DOMException('Aborted', 'AbortError'));
};
xhr.open(request.method, request.url, true);
if (request.credentials === 'include') {
xhr.withCredentials = true;
} else if (request.credentials === 'omit') {
xhr.withCredentials = false;
}
if ('responseType' in xhr && support.blob) {
xhr.responseType = 'blob';
}
request.headers.forEach(function (value: any, name: any) {
xhr.setRequestHeader(name, value);
});
if (request.signal) {
request.signal.addEventListener('abort', abortXhr);
xhr.onreadystatechange = function () {
// DONE (success or failure)
if (xhr.readyState === 4) {
request.signal.removeEventListener('abort', abortXhr);
}
};
}
xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);
})
}
fetch.polyfill = true;
if (!self.fetch) {
(self as any).fetch = fetch;
(self as any).Headers = Headers;
(self as any).Request = Request;
(self as any).Response = Response;
}
})();
export enum AvoEnv {
Prod = "prod",
Staging = "staging",
Dev = "dev",
}
export interface CustomDestination {
make?(env: AvoEnv, apiKey: string): void;
logEvent?: (eventName: string, eventProperties: Record<string, any>) => void;
setUserProperties?: (userId: string, userProperties: Record<string, any>) => void;
identify?: (userId: string) => void;
unidentify?: () => void;
logPage?: (pageName: string, eventProperties: Record<string, any>) => void;
revenue?: (amount: number, eventProperties: Record<string, any>) => void;
setGroupProperties?: (
groupType: string,
groupId: string,
groupProperties: Record<string, any>,
) => void;
addCurrentUserToGroup?: (
groupType: string,
groupId: string,
groupProperties: Record<string, any>,
) => void;
logEventWithGroups?: (
eventName: string,
eventProperties: any,
groupTypesToGroupIds: Record<string, string>,
) => void;
}
// @ts-ignore
interface AvoAssertMessage {
eventName?: string;
tag?: string;
propertyId?: string;
message?: string;
additionalProperties?: string[],
shape?: any,
shapeUserProps?: any,
actualType?: string
}
let __AVO_ENV__: AvoEnv | null = null;
// @ts-ignore
let __AVO_NOOP__: boolean = false;
// @ts-ignore
let __AVO_LOGGER__: AvoLogger | null = null;
// @ts-ignore
let __STRICT__: boolean | null = null;
// @ts-ignore
let __REPORT_FAILURE_AS__: 'error' | 'warn' | 'log' | null = null;
// @ts-ignore
let __WEB_DEBUGGER__: boolean = true;
export const avoInspectorApiKey = "mT3lTbBrUn6bYCxICbcz";
// @ts-ignore
interface AvoInspector {}
let __INSPECTOR__: AvoInspector | null = null;
// polyfill Object.assign
// @ts-ignore
declare interface ObjectConstructor {
assign: any;
}
// @ts-ignore
if (typeof Object.assign !== 'function') {
// Must be writable: true, enumerable: false, configurable: true
Object.defineProperty(Object, "assign", {
value: function assign(target: any, _varArgs: any) { // .length of function is 2
if (target == null) { // TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}
let to = Object(target);
for (let index = 1; index < arguments.length; index++) {
let nextSource = arguments[index];
if (nextSource != null) { // Skip over if undefined or null
for (let nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
},
writable: true,
configurable: true
});
}
interface AvoLogger {
logDebug(env: AvoEnv | null, message: string): boolean;
logWarn(env: AvoEnv | null, message: string): boolean;
logError(env: AvoEnv | null, error: string): boolean;
}
enum webDebuggerArea {
BottomRight = "BottomRight",
BottomLeft = "BottomLeft",
TopRight = "TopRight",
TopLeft = "TopLeft"
}
interface bottomRightParameters {
bottom: number;
right: number;
}
interface bottomLeftParameters {
bottom: number;
left: number;
}
interface topRightParameters {
top: number;
right: number;
}
interface topLeftParameters {
top: number;
left: number;
}
interface webDebuggerPosition {
position: webDebuggerArea;
top?: number;
right?: number;
bottom?: number;
left?: number;
}
interface webDebuggerOptions {
position?: webDebuggerPosition;
}
interface WebDebuggerPositionSetter {
BottomRight(p: bottomRightParameters): webDebuggerPosition;
BottomLeft(p: bottomLeftParameters): webDebuggerPosition;
TopRight(p: topRightParameters): webDebuggerPosition;
TopLeft(p: topLeftParameters): webDebuggerPosition;
}
export const WebDebuggerPosition: WebDebuggerPositionSetter = {
BottomRight: ({ bottom, right }) => ({
position: webDebuggerArea.BottomRight,
bottom,
right,
}),
BottomLeft: ({ bottom, left }) => ({
position: webDebuggerArea.BottomLeft,
bottom,
left,
}),
TopRight: ({ top, right }) => ({
position: webDebuggerArea.TopRight,
top,
right,
}),
TopLeft: ({ top, left }) => ({
position: webDebuggerArea.TopLeft,
top,
left,
}),
}
let InternalAvoLogger: any = {
logEventSent: function logEventSent(eventName: string, eventProperties: any, userProperties: any) {
const message = "Event Sent:" + eventName + "Event Props:" + JSON.stringify(eventProperties) + "User Props:" + JSON.stringify(userProperties);
if (__AVO_LOGGER__ && __AVO_LOGGER__.logDebug && __AVO_LOGGER__.logDebug(__AVO_ENV__, message)) {
return
}
typeof console !== 'undefined' && console.log("[avo] Event Sent:", eventName, "Event Props:", eventProperties, "User Props:", userProperties);
},
log: function log(message: string) {
if (__AVO_LOGGER__ && __AVO_LOGGER__.logDebug && __AVO_LOGGER__.logDebug(__AVO_ENV__, message)) {
return
}
typeof console !== 'undefined' && console.log("[avo] " + message);
},
warn: function warn(message: string) {
if (__AVO_LOGGER__ && __AVO_LOGGER__.logWarn && __AVO_LOGGER__.logWarn(__AVO_ENV__, message)) {
return
}
typeof console !== 'undefined' && console.warn("[avo] " + message);
},
error: function error(message: string, error: string) {
if (__AVO_LOGGER__ && __AVO_LOGGER__.logError && __AVO_LOGGER__.logError(__AVO_ENV__, message + error)) {
return
}
typeof console !== 'undefined' && console.error("[avo] " + message, error);
}
};
function convertPropertiesArrayToMap(propertiesArray: [{id: string, name: string, value: string}]): {string: string | null | undefined} {
let result: {string: string} = {}
propertiesArray.forEach(value => {
result[value.name] = value.value
})
return result
}
// @ts-ignore
let array_difference: any;
// @ts-ignore
let AvoAssert: any;
array_difference = function array_difference(a1: any[], a2: any[]) {
let result: any[] = [];
for (let i = 0; i < a1.length; i++) {
if (a2.indexOf(a1[i]) === -1) {
result.push(a1[i]);
}
}
return result;
}
AvoAssert = {
assertObject: function assertObject(propertyId: string, propName: string, obj: any) {
if (typeof obj !== 'object') {
let message = propName +
' should be of type object but you provided type ' +
typeof obj +
' with value ' +
JSON.stringify(obj);
return [{tag: 'expectedObjectType', propertyId, message, actualType: typeof obj}];
} else {
return [];
}
},
assertString: function assertString(propertyId: string, propName: string, str: string) {
if (typeof str !== 'string') {
let message = propName +
' should be of type string but you provided type ' +
typeof str +
' with value ' +
JSON.stringify(str);
return [{tag: 'expectedStringType', propertyId, message, actualType: typeof str}];
} else {
return [];
}
},
assertInt: function assertInt(propertyId: string, propName: string, int: number) {
if (typeof int === 'number' && int !== Math.round(int)) {
let message = propName +
' should be of type int but you provided type float with value ' +
JSON.stringify(int);
return [{tag: 'expectedIntType', propertyId, message, actualType: 'float'}];
} else if (typeof int !== 'number') {
let message = propName +
' should be of type int but you provided type ' +
typeof int +
' with value ' +
JSON.stringify(int);
return [{tag: 'expectedIntType', propertyId, message, actualType: typeof int}];
} else {
return [];
}
},
assertLong: function assertLong(propertyId: string, propName: string, long: number) {
if (typeof long === 'number' && long !== Math.round(long)) {
let message = propName +
' should be of type long but you provided type float with value ' +
JSON.stringify(long);
return [{tag: 'expectedLongType', propertyId, message, actualType: 'float'}];
} else if (typeof long !== 'number') {
let message = propName +
' should be of type long but you provided type ' +
typeof long +
' with value ' +
JSON.stringify(long);
return [{tag: 'expectedLongType', propertyId, message, actualType: typeof long}];
} else {
return [];
}
},
assertFloat: function assertFloat(propertyId: string, propName: string, float: number) {
if (typeof float !== 'number') {
let message = propName +
' should be of type float but you provided type ' +
typeof float +
' with value ' +
JSON.stringify(float);
return [{tag: 'expectedFloatType', propertyId, message, actualType: typeof float}];
} else {
return [];
}
},
assertBool: function assertBool(propertyId: string, propName: string, bool: boolean) {
if (typeof bool !== 'boolean') {
let message = propName +
' should be of type boolean but you provided type ' +
typeof bool +
' with value ' +
JSON.stringify(bool);
return [{tag: 'expectedBoolType', propertyId, message, actualType: typeof bool}];
} else {
return [];
}
},
assertMax: function assertMax(
propertyId: string,
propName: string,
max: number,
value: number
) {
if (value > max) {
let message = propName +
' has a maximum value of ' +
max +
' but you provided the value ' +
JSON.stringify(value);
return [{tag: 'expectedMax', propertyId, message}];
} else {
return [];
}
},
assertMin: function assertMin(
propertyId: string,
propName: string,
min: number,
value: number
) {
if (value < min) {
let message = propName +
' has a minimum value of ' +
min +
' but you provided the value ' +
JSON.stringify(value);
return [{tag: 'expectedMin', propertyId, message}];
} else {
return [];
}
},
assertList: function assertList(propertyId: string, propName: string, value: any) {
if (!Array.isArray(value)) {
let message = propName + ' should be of type list but you provided type ' + typeof value;
return [{tag: 'expectedList', propertyId, message}];
} else {
return [];
}
},
assertNoAdditionalProperties: function assertNoAdditionalProperties(eventName: string, input: string[], spec: string[]) {
let additionalKeys = array_difference(input, spec);
if (additionalKeys.length) {
let message = "Additional properties when sending event " + eventName + ": " + JSON.stringify(additionalKeys);
return [{tag: 'expectedNoAdditionalProperties', additionalProperties: additionalKeys, message: message}];
} else {
return [];
}
},
assertNoAdditionalUserProperties: function assertNoAdditionalProperties(eventName: string, input: string[], spec: string[]) {
let additionalKeys = array_difference(input, spec);
if (additionalKeys.length) {
let message = "Additional user properties when sending event " + eventName + ": " + JSON.stringify(additionalKeys);
return [{tag: 'expectedNoAdditionalUserProperties', additionalProperties: additionalKeys, message: message}];
} else {
return [];
}
},
};
let _avo_invoke: any;
let _avo_invoke_meta: any;
let _avo_sampling_rate = 1.0;
_avo_invoke = function _avo_invoke(env: AvoEnv, eventId: string, hash: string, messages: {tag: string, propertyId: string}[], origin: string) {
// @ts-ignore
if (typeof (window as any) === 'undefined') { return; }
if (_avo_sampling_rate > 0) {
if (Math.random() < _avo_sampling_rate) {
// @ts-ignore
fetch("https://api.avo.app/i", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
"ac": "I2FzPf8uoLHMTBgUe4FQ",
"br": "D8s8L98F2",
"en": env,
"ev": eventId,
"ha": hash,
"sc": "fwtXqAc0fCLy7b7oGW40",
"se": (new Date()).toISOString(),
"so": "0j7LzMlx1",
"va": messages.length === 0,
"me": messages,
"or": origin
})
}).then(function(res: any) { return res.json(); }).then(function(data: any) { _avo_sampling_rate = data.sa; }).catch(function() {});
}
}
}
_avo_invoke_meta = function _avo_invoke_meta(env: AvoEnv, type: string, messages: {tag: string, propertyId: string}[], origin: string) {
// @ts-ignore
if (typeof (window as any) === 'undefined') { return; }
if (_avo_sampling_rate > 0) {
if (Math.random() < _avo_sampling_rate) {
// @ts-ignore