swetrix 3.0.3 → 3.1.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.
@@ -35,6 +35,18 @@ export interface IPageViewPayload {
35
35
  pg: string | null | undefined;
36
36
  prev: string | null | undefined;
37
37
  }
38
+ export interface IErrorEventPayload {
39
+ name: string;
40
+ message: string | null | undefined;
41
+ lineno: number | null | undefined;
42
+ colno: number | null | undefined;
43
+ filename: string | null | undefined;
44
+ }
45
+ export interface IInternalErrorEventPayload extends IErrorEventPayload {
46
+ lc: string | undefined;
47
+ tz: string | undefined;
48
+ pg: string | null | undefined;
49
+ }
38
50
  interface IPerfPayload {
39
51
  dns: number;
40
52
  tls: number;
@@ -52,12 +64,36 @@ export interface PageActions {
52
64
  /** Stops the tracking of pages. */
53
65
  stop: () => void;
54
66
  }
67
+ /**
68
+ * The object returned by `trackErrors()`, used to stop tracking errors.
69
+ */
70
+ export interface ErrorActions {
71
+ /** Stops the tracking of errors. */
72
+ stop: () => void;
73
+ }
55
74
  export interface PageData {
56
75
  /** Current URL path. */
57
76
  path: string;
58
77
  /** The object returned by `trackPageViews()`, used to stop tracking pages. */
59
78
  actions: PageActions;
60
79
  }
80
+ export interface ErrorOptions {
81
+ /**
82
+ * A number that indicates how many errors should be sent to the server.
83
+ * Accepts values between 0 and 1. For example, if set to 0.5 - only ~50% of errors will be sent to Swetrix.
84
+ * For testing, we recommend setting this value to 1. For production, you should configure it depending on your needs as each error event counts towards your plan.
85
+ *
86
+ * The default value for this option is 1.
87
+ */
88
+ sampleRate?: number;
89
+ /**
90
+ * Callback to edit / prevent sending errors.
91
+ *
92
+ * @param payload - The error payload.
93
+ * @returns The edited payload or `false` to prevent sending the error event. If `true` is returned, the payload will be sent as-is.
94
+ */
95
+ callback?: (payload: IInternalErrorEventPayload) => Partial<IInternalErrorEventPayload> | boolean;
96
+ }
61
97
  export interface PageViewsOptions {
62
98
  /**
63
99
  * If set to `true`, only unique events will be saved.
@@ -84,7 +120,7 @@ export interface PageViewsOptions {
84
120
  */
85
121
  callback?: (payload: IPageViewPayload) => Partial<IPageViewPayload> | boolean;
86
122
  }
87
- export declare const defaultPageActions: {
123
+ export declare const defaultActions: {
88
124
  stop(): void;
89
125
  };
90
126
  export declare class Lib {
@@ -92,9 +128,14 @@ export declare class Lib {
92
128
  private options?;
93
129
  private pageData;
94
130
  private pageViewsOptions;
131
+ private errorsOptions;
95
132
  private perfStatsCollected;
96
133
  private activePage;
134
+ private errorListenerExists;
97
135
  constructor(projectID: string, options?: LibOptions | undefined);
136
+ captureError(event: ErrorEvent): void;
137
+ trackErrors(options?: ErrorOptions): ErrorActions;
138
+ submitError(payload: IErrorEventPayload, evokeCallback?: boolean): void;
98
139
  track(event: TrackEventOptions): void;
99
140
  trackPageViews(options?: PageViewsOptions): PageActions;
100
141
  getPerformanceStats(): IPerfPayload | {};
@@ -1,5 +1,5 @@
1
1
  import { isInBrowser, isLocalhost, isAutomated, getLocale, getTimezone, getReferrer, getUTMCampaign, getUTMMedium, getUTMSource, getPath, } from './utils';
2
- export const defaultPageActions = {
2
+ export const defaultActions = {
3
3
  stop() { },
4
4
  };
5
5
  const DEFAULT_API_HOST = 'https://api.swetrix.com/log';
@@ -9,10 +9,71 @@ export class Lib {
9
9
  this.options = options;
10
10
  this.pageData = null;
11
11
  this.pageViewsOptions = null;
12
+ this.errorsOptions = null;
12
13
  this.perfStatsCollected = false;
13
14
  this.activePage = null;
15
+ this.errorListenerExists = false;
14
16
  this.trackPathChange = this.trackPathChange.bind(this);
15
17
  this.heartbeat = this.heartbeat.bind(this);
18
+ this.captureError = this.captureError.bind(this);
19
+ }
20
+ captureError(event) {
21
+ if (typeof this.errorsOptions?.sampleRate === 'number' && this.errorsOptions.sampleRate > Math.random()) {
22
+ return;
23
+ }
24
+ this.submitError({
25
+ // The file in which error occured.
26
+ filename: event.filename,
27
+ // The line of code error occured on.
28
+ lineno: event.lineno,
29
+ // The column of code error occured on.
30
+ colno: event.colno,
31
+ // Name of the error, if not exists (i.e. it's a custom thrown error). The initial value of name is "Error", but just in case lets explicitly set it here too.
32
+ name: event.error?.name || 'Error',
33
+ // Description of the error. By default, we use message from Error object, is it does not contain the error name
34
+ // (we want to split error name and message so we could group them together later in dashboard).
35
+ // If message in error object does not exist - lets use a message from the Error event itself.
36
+ message: event.error?.message || event.message,
37
+ });
38
+ }
39
+ trackErrors(options) {
40
+ if (this.errorListenerExists || !this.canTrack()) {
41
+ return defaultActions;
42
+ }
43
+ this.errorsOptions = options;
44
+ window.addEventListener('error', this.captureError);
45
+ this.errorListenerExists = true;
46
+ return {
47
+ stop: () => {
48
+ window.removeEventListener('error', this.captureError);
49
+ },
50
+ };
51
+ }
52
+ submitError(payload, evokeCallback) {
53
+ const privateData = {
54
+ pid: this.projectID,
55
+ };
56
+ const errorPayload = {
57
+ pg: this.activePage ||
58
+ getPath({
59
+ hash: this.pageViewsOptions?.hash,
60
+ search: this.pageViewsOptions?.search,
61
+ }),
62
+ lc: getLocale(),
63
+ tz: getTimezone(),
64
+ ...payload,
65
+ };
66
+ if (evokeCallback && this.errorsOptions?.callback) {
67
+ const callbackResult = this.errorsOptions.callback(errorPayload);
68
+ if (callbackResult === false) {
69
+ return;
70
+ }
71
+ if (callbackResult && typeof callbackResult === 'object') {
72
+ Object.assign(errorPayload, callbackResult);
73
+ }
74
+ }
75
+ Object.assign(errorPayload, privateData);
76
+ this.sendRequest('error', errorPayload);
16
77
  }
17
78
  track(event) {
18
79
  if (!this.canTrack()) {
@@ -33,7 +94,7 @@ export class Lib {
33
94
  }
34
95
  trackPageViews(options) {
35
96
  if (!this.canTrack()) {
36
- return defaultPageActions;
97
+ return defaultActions;
37
98
  }
38
99
  if (this.pageData) {
39
100
  return this.pageData.actions;
@@ -1 +1 @@
1
- {"version":3,"file":"Lib.js","sourceRoot":"","sources":["../../src/Lib.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,WAAW,EACX,WAAW,EACX,SAAS,EACT,W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ions, PageViewsOptions, ErrorOptions, PageActions, ErrorActions, IErrorEventPayload } from './Lib';
2
2
  export declare let LIB_INSTANCE: Lib | null;
3
3
  /**
4
4
  * Initialise the tracking library instance (other methods won't work if the library is not initialised).
@@ -16,6 +16,13 @@ export declare function init(pid: string, options?: LibOptions): Lib;
16
16
  * @param {TrackEventOptions} event The options related to the custom event.
17
17
  */
18
18
  export declare function track(event: TrackEventOptions): void;
19
+ /**
20
+ * With this function you are able to automatically track pageviews across your application.
21
+ *
22
+ * @param {PageViewsOptions} options Pageviews tracking options.
23
+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
24
+ */
25
+ export declare function trackViews(options?: PageViewsOptions): Promise<PageActions>;
19
26
  /**
20
27
  * With this function you are able to track any custom events you want.
21
28
  * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.
@@ -24,7 +31,15 @@ export declare function track(event: TrackEventOptions): void;
24
31
  * @param {PageViewsOptions} options The options related to the custom event.
25
32
  * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
26
33
  */
27
- export declare function trackViews(options?: PageViewsOptions): Promise<PageActions>;
34
+ export declare function trackErrors(options?: ErrorOptions): ErrorActions;
35
+ /**
36
+ * This function is used to manually track an error event.
37
+ * It's useful if you want to track specific errors in your application.
38
+ *
39
+ * @param payload Swetrix error object to send.
40
+ * @returns void
41
+ */
42
+ export declare function trackError(payload: IErrorEventPayload): void;
28
43
  /**
29
44
  * This function is used to manually track a page view event.
30
45
  * It's useful if your application uses esoteric routing which is not supported by Swetrix by default.
@@ -1,4 +1,4 @@
1
- import { Lib, defaultPageActions } from './Lib';
1
+ import { Lib, defaultActions, } from './Lib';
2
2
  export let LIB_INSTANCE = null;
3
3
  /**
4
4
  * Initialise the tracking library instance (other methods won't work if the library is not initialised).
@@ -26,17 +26,15 @@ export function track(event) {
26
26
  LIB_INSTANCE.track(event);
27
27
  }
28
28
  /**
29
- * With this function you are able to track any custom events you want.
30
- * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.
31
- * The total number of track calls and their conversion rate will be saved.
29
+ * With this function you are able to automatically track pageviews across your application.
32
30
  *
33
- * @param {PageViewsOptions} options The options related to the custom event.
31
+ * @param {PageViewsOptions} options Pageviews tracking options.
34
32
  * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
35
33
  */
36
34
  export function trackViews(options) {
37
35
  return new Promise((resolve) => {
38
36
  if (!LIB_INSTANCE) {
39
- resolve(defaultPageActions);
37
+ resolve(defaultActions);
40
38
  return;
41
39
  }
42
40
  // We need to verify that document.readyState is complete for the performance stats to be collected correctly.
@@ -51,6 +49,32 @@ export function trackViews(options) {
51
49
  }
52
50
  });
53
51
  }
52
+ /**
53
+ * With this function you are able to track any custom events you want.
54
+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.
55
+ * The total number of track calls and their conversion rate will be saved.
56
+ *
57
+ * @param {PageViewsOptions} options The options related to the custom event.
58
+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
59
+ */
60
+ export function trackErrors(options) {
61
+ if (!LIB_INSTANCE) {
62
+ return defaultActions;
63
+ }
64
+ return LIB_INSTANCE.trackErrors(options);
65
+ }
66
+ /**
67
+ * This function is used to manually track an error event.
68
+ * It's useful if you want to track specific errors in your application.
69
+ *
70
+ * @param payload Swetrix error object to send.
71
+ * @returns void
72
+ */
73
+ export function trackError(payload) {
74
+ if (!LIB_INSTANCE)
75
+ return;
76
+ LIB_INSTANCE.submitError(payload, false);
77
+ }
54
78
  /**
55
79
  * This function is used to manually track a page view event.
56
80
  * It's useful if your application uses esoteric routing which is not supported by Swetrix by default.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAgE,kBAAkB,EAAE,MAAM,OAAO,CAAA;AAE7G,MAAM,CAAC,IAAI,YAAY,GAAe,IAAI,CAAA;AAE1C;;;;;;GAMG;AACH,MAAM,UAAU,IAAI,CA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CAAC,WAAW,CAAC,OAAO,CAAC,CAAA;AAC1C,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,OAA2B;IACpD,IAAI,CAAC,YAAY;QAAE,OAAM;IAEzB,YAAY,CAAC,WAAW,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;AAC1C,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,IAAa,EAAE,MAAgB;IACzE,IAAI,CAAC,YAAY;QAAE,OAAM;IAEzB,YAAY,CAAC,cAAc,CAAC,IAAI,EAAE,IAAI,IAAI,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,CAAA;AACtE,CAAC"}
@@ -95,7 +95,7 @@ var getPath = function (options) {
95
95
  return result;
96
96
  };
97
97
 
98
- var defaultPageActions = {
98
+ var defaultActions = {
99
99
  stop: function () { },
100
100
  };
101
101
  var DEFAULT_API_HOST = 'https://api.swetrix.com/log';
@@ -105,11 +105,70 @@ var Lib = /** @class */ (function () {
105
105
  this.options = options;
106
106
  this.pageData = null;
107
107
  this.pageViewsOptions = null;
108
+ this.errorsOptions = null;
108
109
  this.perfStatsCollected = false;
109
110
  this.activePage = null;
111
+ this.errorListenerExists = false;
110
112
  this.trackPathChange = this.trackPathChange.bind(this);
111
113
  this.heartbeat = this.heartbeat.bind(this);
114
+ this.captureError = this.captureError.bind(this);
112
115
  }
116
+ Lib.prototype.captureError = function (event) {
117
+ var _a, _b, _c;
118
+ if (typeof ((_a = this.errorsOptions) === null || _a === void 0 ? void 0 : _a.sampleRate) === 'number' && this.errorsOptions.sampleRate > Math.random()) {
119
+ return;
120
+ }
121
+ this.submitError({
122
+ // The file in which error occured.
123
+ filename: event.filename,
124
+ // The line of code error occured on.
125
+ lineno: event.lineno,
126
+ // The column of code error occured on.
127
+ colno: event.colno,
128
+ // Name of the error, if not exists (i.e. it's a custom thrown error). The initial value of name is "Error", but just in case lets explicitly set it here too.
129
+ name: ((_b = event.error) === null || _b === void 0 ? void 0 : _b.name) || 'Error',
130
+ // Description of the error. By default, we use message from Error object, is it does not contain the error name
131
+ // (we want to split error name and message so we could group them together later in dashboard).
132
+ // If message in error object does not exist - lets use a message from the Error event itself.
133
+ message: ((_c = event.error) === null || _c === void 0 ? void 0 : _c.message) || event.message,
134
+ });
135
+ };
136
+ Lib.prototype.trackErrors = function (options) {
137
+ var _this = this;
138
+ if (this.errorListenerExists || !this.canTrack()) {
139
+ return defaultActions;
140
+ }
141
+ this.errorsOptions = options;
142
+ window.addEventListener('error', this.captureError);
143
+ this.errorListenerExists = true;
144
+ return {
145
+ stop: function () {
146
+ window.removeEventListener('error', _this.captureError);
147
+ },
148
+ };
149
+ };
150
+ Lib.prototype.submitError = function (payload, evokeCallback) {
151
+ var _a, _b, _c;
152
+ var privateData = {
153
+ pid: this.projectID,
154
+ };
155
+ var errorPayload = __assign({ pg: this.activePage ||
156
+ getPath({
157
+ hash: (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.hash,
158
+ search: (_b = this.pageViewsOptions) === null || _b === void 0 ? void 0 : _b.search,
159
+ }), lc: getLocale(), tz: getTimezone() }, payload);
160
+ if (evokeCallback && ((_c = this.errorsOptions) === null || _c === void 0 ? void 0 : _c.callback)) {
161
+ var callbackResult = this.errorsOptions.callback(errorPayload);
162
+ if (callbackResult === false) {
163
+ return;
164
+ }
165
+ if (callbackResult && typeof callbackResult === 'object') {
166
+ Object.assign(errorPayload, callbackResult);
167
+ }
168
+ }
169
+ Object.assign(errorPayload, privateData);
170
+ this.sendRequest('error', errorPayload);
171
+ };
113
172
  Lib.prototype.track = function (event) {
114
173
  if (!this.canTrack()) {
115
174
  return;
@@ -119,7 +178,7 @@ var Lib = /** @class */ (function () {
119
178
  };
120
179
  Lib.prototype.trackPageViews = function (options) {
121
180
  if (!this.canTrack()) {
122
- return defaultPageActions;
181
+ return defaultActions;
123
182
  }
124
183
  if (this.pageData) {
125
184
  return this.pageData.actions;
@@ -313,17 +372,15 @@ function track(event) {
313
372
  exports.LIB_INSTANCE.track(event);
314
373
  }
315
374
  /**
316
- * With this function you are able to track any custom events you want.
317
- * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.
318
- * The total number of track calls and their conversion rate will be saved.
375
+ * With this function you are able to automatically track pageviews across your application.
319
376
  *
320
- * @param {PageViewsOptions} options The options related to the custom event.
377
+ * @param {PageViewsOptions} options Pageviews tracking options.
321
378
  * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
322
379
  */
323
380
  function trackViews(options) {
324
381
  return new Promise(function (resolve) {
325
382
  if (!exports.LIB_INSTANCE) {
326
- resolve(defaultPageActions);
383
+ resolve(defaultActions);
327
384
  return;
328
385
  }
329
386
  // We need to verify that document.readyState is complete for the performance stats to be collected correctly.
@@ -338,6 +395,32 @@ function trackViews(options) {
338
395
  }
339
396
  });
340
397
  }
398
+ /**
399
+ * With this function you are able to track any custom events you want.
400
+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.
401
+ * The total number of track calls and their conversion rate will be saved.
402
+ *
403
+ * @param {PageViewsOptions} options The options related to the custom event.
404
+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
405
+ */
406
+ function trackErrors(options) {
407
+ if (!exports.LIB_INSTANCE) {
408
+ return defaultActions;
409
+ }
410
+ return exports.LIB_INSTANCE.trackErrors(options);
411
+ }
412
+ /**
413
+ * This function is used to manually track an error event.
414
+ * It's useful if you want to track specific errors in your application.
415
+ *
416
+ * @param payload Swetrix error object to send.
417
+ * @returns void
418
+ */
419
+ function trackError(payload) {
420
+ if (!exports.LIB_INSTANCE)
421
+ return;
422
+ exports.LIB_INSTANCE.submitError(payload, false);
423
+ }
341
424
  /**
342
425
  * This function is used to manually track a page view event.
343
426
  * It's useful if your application uses esoteric routing which is not supported by Swetrix by default.
@@ -355,5 +438,7 @@ function trackPageview(path, prev, unique) {
355
438
 
356
439
  exports.init = init;
357
440
  exports.track = track;
441
+ exports.trackError = trackError;
442
+ exports.trackErrors = trackErrors;
358
443
  exports.trackPageview = trackPageview;
359
444
  exports.trackViews = trackViews;
@@ -91,7 +91,7 @@ var getPath = function (options) {
91
91
  return result;
92
92
  };
93
93
 
94
- var defaultPageActions = {
94
+ var defaultActions = {
95
95
  stop: function () { },
96
96
  };
97
97
  var DEFAULT_API_HOST = 'https://api.swetrix.com/log';
@@ -101,11 +101,70 @@ var Lib = /** @class */ (function () {
101
101
  this.options = options;
102
102
  this.pageData = null;
103
103
  this.pageViewsOptions = null;
104
+ this.errorsOptions = null;
104
105
  this.perfStatsCollected = false;
105
106
  this.activePage = null;
107
+ this.errorListenerExists = false;
106
108
  this.trackPathChange = this.trackPathChange.bind(this);
107
109
  this.heartbeat = this.heartbeat.bind(this);
110
+ this.captureError = this.captureError.bind(this);
108
111
  }
112
+ Lib.prototype.captureError = function (event) {
113
+ var _a, _b, _c;
114
+ if (typeof ((_a = this.errorsOptions) === null || _a === void 0 ? void 0 : _a.sampleRate) === 'number' && this.errorsOptions.sampleRate > Math.random()) {
115
+ return;
116
+ }
117
+ this.submitError({
118
+ // The file in which error occured.
119
+ filename: event.filename,
120
+ // The line of code error occured on.
121
+ lineno: event.lineno,
122
+ // The column of code error occured on.
123
+ colno: event.colno,
124
+ // Name of the error, if not exists (i.e. it's a custom thrown error). The initial value of name is "Error", but just in case lets explicitly set it here too.
125
+ name: ((_b = event.error) === null || _b === void 0 ? void 0 : _b.name) || 'Error',
126
+ // Description of the error. By default, we use message from Error object, is it does not contain the error name
127
+ // (we want to split error name and message so we could group them together later in dashboard).
128
+ // If message in error object does not exist - lets use a message from the Error event itself.
129
+ message: ((_c = event.error) === null || _c === void 0 ? void 0 : _c.message) || event.message,
130
+ });
131
+ };
132
+ Lib.prototype.trackErrors = function (options) {
133
+ var _this = this;
134
+ if (this.errorListenerExists || !this.canTrack()) {
135
+ return defaultActions;
136
+ }
137
+ this.errorsOptions = options;
138
+ window.addEventListener('error', this.captureError);
139
+ this.errorListenerExists = true;
140
+ return {
141
+ stop: function () {
142
+ window.removeEventListener('error', _this.captureError);
143
+ },
144
+ };
145
+ };
146
+ Lib.prototype.submitError = function (payload, evokeCallback) {
147
+ var _a, _b, _c;
148
+ var privateData = {
149
+ pid: this.projectID,
150
+ };
151
+ var errorPayload = __assign({ pg: this.activePage ||
152
+ getPath({
153
+ hash: (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.hash,
154
+ search: (_b = this.pageViewsOptions) === null || _b === void 0 ? void 0 : _b.search,
155
+ }), lc: getLocale(), tz: getTimezone() }, payload);
156
+ if (evokeCallback && ((_c = this.errorsOptions) === null || _c === void 0 ? void 0 : _c.callback)) {
157
+ var callbackResult = this.errorsOptions.callback(errorPayload);
158
+ if (callbackResult === false) {
159
+ return;
160
+ }
161
+ if (callbackResult && typeof callbackResult === 'object') {
162
+ Object.assign(errorPayload, callbackResult);
163
+ }
164
+ }
165
+ Object.assign(errorPayload, privateData);
166
+ this.sendRequest('error', errorPayload);
167
+ };
109
168
  Lib.prototype.track = function (event) {
110
169
  if (!this.canTrack()) {
111
170
  return;
@@ -115,7 +174,7 @@ var Lib = /** @class */ (function () {
115
174
  };
116
175
  Lib.prototype.trackPageViews = function (options) {
117
176
  if (!this.canTrack()) {
118
- return defaultPageActions;
177
+ return defaultActions;
119
178
  }
120
179
  if (this.pageData) {
121
180
  return this.pageData.actions;
@@ -309,17 +368,15 @@ function track(event) {
309
368
  LIB_INSTANCE.track(event);
310
369
  }
311
370
  /**
312
- * With this function you are able to track any custom events you want.
313
- * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.
314
- * The total number of track calls and their conversion rate will be saved.
371
+ * With this function you are able to automatically track pageviews across your application.
315
372
  *
316
- * @param {PageViewsOptions} options The options related to the custom event.
373
+ * @param {PageViewsOptions} options Pageviews tracking options.
317
374
  * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
318
375
  */
319
376
  function trackViews(options) {
320
377
  return new Promise(function (resolve) {
321
378
  if (!LIB_INSTANCE) {
322
- resolve(defaultPageActions);
379
+ resolve(defaultActions);
323
380
  return;
324
381
  }
325
382
  // We need to verify that document.readyState is complete for the performance stats to be collected correctly.
@@ -334,6 +391,32 @@ function trackViews(options) {
334
391
  }
335
392
  });
336
393
  }
394
+ /**
395
+ * With this function you are able to track any custom events you want.
396
+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.
397
+ * The total number of track calls and their conversion rate will be saved.
398
+ *
399
+ * @param {PageViewsOptions} options The options related to the custom event.
400
+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
401
+ */
402
+ function trackErrors(options) {
403
+ if (!LIB_INSTANCE) {
404
+ return defaultActions;
405
+ }
406
+ return LIB_INSTANCE.trackErrors(options);
407
+ }
408
+ /**
409
+ * This function is used to manually track an error event.
410
+ * It's useful if you want to track specific errors in your application.
411
+ *
412
+ * @param payload Swetrix error object to send.
413
+ * @returns void
414
+ */
415
+ function trackError(payload) {
416
+ if (!LIB_INSTANCE)
417
+ return;
418
+ LIB_INSTANCE.submitError(payload, false);
419
+ }
337
420
  /**
338
421
  * This function is used to manually track a page view event.
339
422
  * It's useful if your application uses esoteric routing which is not supported by Swetrix by default.
@@ -349,4 +432,4 @@ function trackPageview(path, prev, unique) {
349
432
  LIB_INSTANCE.submitPageView(path, prev || null, Boolean(unique), {});
350
433
  }
351
434
 
352
- export { LIB_INSTANCE, init, track, trackPageview, trackViews };
435
+ export { LIB_INSTANCE, init, track, trackError, trackErrors, trackPageview, trackViews };
package/dist/swetrix.js CHANGED
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).swetrix={})}(this,function(a){"use strict";function t(t){return(t=location.search.match(t))&&t[2]||void 0}function i(){return void 0!==navigator.languages?navigator.languages[0]:navigator.language}function r(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){}}function s(){return document.referrer||void 0}function c(){return t(n)}function u(){return t(p)}function l(){return t(h)}function o(t){var e,n=location.pathname||"";return t.hash&&(n+=-1<(e=location.hash.indexOf("?"))?location.hash.substring(0,e):location.hash),t.search&&(e=location.hash.indexOf("?"),n+=location.search||(-1<e?location.hash.substring(e):"")),n}var e=function(){return(e=Object.assign||function(t){for(var e,n=1,a=arguments.length;n<a;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t}).apply(this,arguments)},n=/[?&](ref|source|utm_source)=([^?&]+)/,h=/[?&](utm_campaign)=([^?&]+)/,p=/[?&](utm_medium)=([^?&]+)/,d={stop:function(){}},f=(g.prototype.track=function(t){this.canTrack()&&(t=e(e({},t),{pid:this.projectID,pg:this.activePage,lc:i(),tz:r(),ref:s(),so:c(),me:u(),ca:l()}),this.sendRequest("custom",t))},g.prototype.trackPageViews=function(t){var e,n,a;return this.canTrack()?(this.pageData||(null!=(this.pageViewsOptions=t)&&t.unique||(e=setInterval(this.trackPathChange,2e3)),setTimeout(this.heartbeat,3e3),n=setInterval(this.heartbeat,28e3),a=o({hash:null==t?void 0:t.hash,search:null==t?void 0:t.search}),this.pageData={path:a,actions:{stop:function(){clearInterval(e),clearInterval(n)}}},this.trackPage(a,null==t?void 0:t.unique)),this.pageData.actions):d},g.prototype.getPerformanceStats=function(){var t;return this.canTrack()&&!this.perfStatsCollected&&null!=(t=window.performance)&&t.getEntriesByType&&(t=window.performance.getEntriesByType("navigation")[0])?(this.perfStatsCollected=!0,{dns:t.domainLookupEnd-t.domainLookupStart,tls:t.secureConnectionStart?t.requestStart-t.secureConnectionStart:0,conn:t.secureConnectionStart?t.secureConnectionStart-t.connectStart:t.connectEnd-t.connectStart,response:t.responseEnd-t.responseStart,render:t.domComplete-t.domContentLoadedEventEnd,dom_load:t.domContentLoadedEventEnd-t.responseEnd,page_load:t.loadEventStart,ttfb:t.responseStart-t.requestStart}):{}},g.prototype.heartbeat=function(){var t;(null!=(t=this.pageViewsOptions)&&t.heartbeatOnBackground||"hidden"!==document.visibilityState)&&(t={pid:this.projectID},this.sendRequest("hb",t))},g.prototype.trackPathChange=function(){var t;this.pageData&&(t=o({hash:null==(t=this.pageViewsOptions)?void 0:t.hash,search:null==(t=this.pageViewsOptions)?void 0:t.search}),this.pageData.path!==t)&&this.trackPage(t,!1)},g.prototype.getPreviousPage=function(){if(this.activePage)return this.activePage;if("function"==typeof URL){var t=s();if(!t)return null;var e=location.host;try{var n=new URL(t),a=n.host,o=n.pathname;return e!==a?null:o}catch(t){}}return null},g.prototype.trackPage=function(t,e){var n,a;void 0===e&&(e=!1),this.pageData&&(this.pageData.path=t,n=this.getPerformanceStats(),a=this.getPreviousPage(),this.activePage=t,this.submitPageView(t,a,e,n,!0))},g.prototype.submitPageView=function(t,e,n,a,o){a={pid:this.projectID,perf:a,unique:n},n={lc:i(),tz:r(),ref:s(),so:c(),me:u(),ca:l(),pg:t,prev:e};if(o&&null!=(t=this.pageViewsOptions)&&t.callback){e=this.pageViewsOptions.callback(n);if(!1===e)return;e&&"object"==typeof e&&Object.assign(n,e)}Object.assign(n,a),this.sendRequest("",n)},g.prototype.canTrack=function(){var t;return!(null!=(t=this.options)&&t.disabled||"undefined"==typeof window||null!=(t=this.options)&&t.respectDNT&&"1"===(null==(t=window.navigator)?void 0:t.doNotTrack)||(null==(t=this.options)||!t.devMode)&&("localhost"===(null===location||void 0===location?void 0:location.hostname)||"127.0.0.1"===(null===location||void 0===location?void 0:location.hostname)||""===(null===location||void 0===location?void 0:location.hostname))||null!==navigator&&void 0!==navigator&&navigator.webdriver)},g.prototype.sendRequest=function(t,e){var n=(null==(n=this.options)?void 0:n.apiURL)||"https://api.swetrix.com/log",a=new XMLHttpRequest;a.open("POST","".concat(n,"/").concat(t),!0),a.setRequestHeader("Content-Type","application/json"),a.send(JSON.stringify(e))},g);function g(t,e){this.projectID=t,this.options=e,this.pageData=null,this.pageViewsOptions=null,this.perfStatsCollected=!1,this.activePage=null,this.trackPathChange=this.trackPathChange.bind(this),this.heartbeat=this.heartbeat.bind(this)}a.LIB_INSTANCE=null,a.init=function(t,e){return a.LIB_INSTANCE||(a.LIB_INSTANCE=new f(t,e)),a.LIB_INSTANCE},a.track=function(t){a.LIB_INSTANCE&&a.LIB_INSTANCE.track(t)},a.trackPageview=function(t,e,n){a.LIB_INSTANCE&&a.LIB_INSTANCE.submitPageView(t,e||null,Boolean(n),{})},a.trackViews=function(e){return new Promise(function(t){a.LIB_INSTANCE?"undefined"==typeof document||"complete"===document.readyState?t(a.LIB_INSTANCE.trackPageViews(e)):window.addEventListener("load",function(){t(a.LIB_INSTANCE.trackPageViews(e))}):t(d)})},Object.defineProperty(a,"__esModule",{value:!0})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).swetrix={})}(this,function(o){"use strict";function t(t){return(t=location.search.match(t))&&t[2]||void 0}function r(){return void 0!==navigator.languages?navigator.languages[0]:navigator.language}function a(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){}}function s(){return document.referrer||void 0}function c(){return t(e)}function u(){return t(p)}function l(){return t(n)}function i(t){var e,n=location.pathname||"";return t.hash&&(n+=-1<(e=location.hash.indexOf("?"))?location.hash.substring(0,e):location.hash),t.search&&(e=location.hash.indexOf("?"),n+=location.search||(-1<e?location.hash.substring(e):"")),n}var h=function(){return(h=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},e=/[?&](ref|source|utm_source)=([^?&]+)/,n=/[?&](utm_campaign)=([^?&]+)/,p=/[?&](utm_medium)=([^?&]+)/,d={stop:function(){}},f=(g.prototype.captureError=function(t){var e;"number"==typeof(null==(e=this.errorsOptions)?void 0:e.sampleRate)&&this.errorsOptions.sampleRate>Math.random()||this.submitError({filename:t.filename,lineno:t.lineno,colno:t.colno,name:(null==(e=t.error)?void 0:e.name)||"Error",message:(null==(e=t.error)?void 0:e.message)||t.message})},g.prototype.trackErrors=function(t){var e=this;return this.errorListenerExists||!this.canTrack()?d:(this.errorsOptions=t,window.addEventListener("error",this.captureError),this.errorListenerExists=!0,{stop:function(){window.removeEventListener("error",e.captureError)}})},g.prototype.submitError=function(t,e){var n={pid:this.projectID},o=h({pg:this.activePage||i({hash:null==(o=this.pageViewsOptions)?void 0:o.hash,search:null==(o=this.pageViewsOptions)?void 0:o.search}),lc:r(),tz:a()},t);if(e&&null!=(t=this.errorsOptions)&&t.callback){e=this.errorsOptions.callback(o);if(!1===e)return;e&&"object"==typeof e&&Object.assign(o,e)}Object.assign(o,n),this.sendRequest("error",o)},g.prototype.track=function(t){this.canTrack()&&(t=h(h({},t),{pid:this.projectID,pg:this.activePage,lc:r(),tz:a(),ref:s(),so:c(),me:u(),ca:l()}),this.sendRequest("custom",t))},g.prototype.trackPageViews=function(t){var e,n,o;return this.canTrack()?(this.pageData||(null!=(this.pageViewsOptions=t)&&t.unique||(e=setInterval(this.trackPathChange,2e3)),setTimeout(this.heartbeat,3e3),n=setInterval(this.heartbeat,28e3),o=i({hash:null==t?void 0:t.hash,search:null==t?void 0:t.search}),this.pageData={path:o,actions:{stop:function(){clearInterval(e),clearInterval(n)}}},this.trackPage(o,null==t?void 0:t.unique)),this.pageData.actions):d},g.prototype.getPerformanceStats=function(){var t;return this.canTrack()&&!this.perfStatsCollected&&null!=(t=window.performance)&&t.getEntriesByType&&(t=window.performance.getEntriesByType("navigation")[0])?(this.perfStatsCollected=!0,{dns:t.domainLookupEnd-t.domainLookupStart,tls:t.secureConnectionStart?t.requestStart-t.secureConnectionStart:0,conn:t.secureConnectionStart?t.secureConnectionStart-t.connectStart:t.connectEnd-t.connectStart,response:t.responseEnd-t.responseStart,render:t.domComplete-t.domContentLoadedEventEnd,dom_load:t.domContentLoadedEventEnd-t.responseEnd,page_load:t.loadEventStart,ttfb:t.responseStart-t.requestStart}):{}},g.prototype.heartbeat=function(){var t;(null!=(t=this.pageViewsOptions)&&t.heartbeatOnBackground||"hidden"!==document.visibilityState)&&(t={pid:this.projectID},this.sendRequest("hb",t))},g.prototype.trackPathChange=function(){var t;this.pageData&&(t=i({hash:null==(t=this.pageViewsOptions)?void 0:t.hash,search:null==(t=this.pageViewsOptions)?void 0:t.search}),this.pageData.path!==t)&&this.trackPage(t,!1)},g.prototype.getPreviousPage=function(){if(this.activePage)return this.activePage;if("function"==typeof URL){var t=s();if(!t)return null;var e=location.host;try{var n=new URL(t),o=n.host,i=n.pathname;return e!==o?null:i}catch(t){}}return null},g.prototype.trackPage=function(t,e){var n,o;void 0===e&&(e=!1),this.pageData&&(this.pageData.path=t,n=this.getPerformanceStats(),o=this.getPreviousPage(),this.activePage=t,this.submitPageView(t,o,e,n,!0))},g.prototype.submitPageView=function(t,e,n,o,i){o={pid:this.projectID,perf:o,unique:n},n={lc:r(),tz:a(),ref:s(),so:c(),me:u(),ca:l(),pg:t,prev:e};if(i&&null!=(t=this.pageViewsOptions)&&t.callback){e=this.pageViewsOptions.callback(n);if(!1===e)return;e&&"object"==typeof e&&Object.assign(n,e)}Object.assign(n,o),this.sendRequest("",n)},g.prototype.canTrack=function(){var t;return!(null!=(t=this.options)&&t.disabled||"undefined"==typeof window||null!=(t=this.options)&&t.respectDNT&&"1"===(null==(t=window.navigator)?void 0:t.doNotTrack)||(null==(t=this.options)||!t.devMode)&&("localhost"===(null===location||void 0===location?void 0:location.hostname)||"127.0.0.1"===(null===location||void 0===location?void 0:location.hostname)||""===(null===location||void 0===location?void 0:location.hostname))||null!==navigator&&void 0!==navigator&&navigator.webdriver)},g.prototype.sendRequest=function(t,e){var n=(null==(n=this.options)?void 0:n.apiURL)||"https://api.swetrix.com/log",o=new XMLHttpRequest;o.open("POST","".concat(n,"/").concat(t),!0),o.setRequestHeader("Content-Type","application/json"),o.send(JSON.stringify(e))},g);function g(t,e){this.projectID=t,this.options=e,this.pageData=null,this.pageViewsOptions=null,this.errorsOptions=null,this.perfStatsCollected=!1,this.activePage=null,this.errorListenerExists=!1,this.trackPathChange=this.trackPathChange.bind(this),this.heartbeat=this.heartbeat.bind(this),this.captureError=this.captureError.bind(this)}o.LIB_INSTANCE=null,o.init=function(t,e){return o.LIB_INSTANCE||(o.LIB_INSTANCE=new f(t,e)),o.LIB_INSTANCE},o.track=function(t){o.LIB_INSTANCE&&o.LIB_INSTANCE.track(t)},o.trackError=function(t){o.LIB_INSTANCE&&o.LIB_INSTANCE.submitError(t,!1)},o.trackErrors=function(t){return o.LIB_INSTANCE?o.LIB_INSTANCE.trackErrors(t):d},o.trackPageview=function(t,e,n){o.LIB_INSTANCE&&o.LIB_INSTANCE.submitPageView(t,e||null,Boolean(n),{})},o.trackViews=function(e){return new Promise(function(t){o.LIB_INSTANCE?"undefined"==typeof document||"complete"===document.readyState?t(o.LIB_INSTANCE.trackPageViews(e)):window.addEventListener("load",function(){t(o.LIB_INSTANCE.trackPageViews(e))}):t(d)})},Object.defineProperty(o,"__esModule",{value:!0})});
@@ -97,7 +97,7 @@
97
97
  return result;
98
98
  };
99
99
 
100
- var defaultPageActions = {
100
+ var defaultActions = {
101
101
  stop: function () { },
102
102
  };
103
103
  var DEFAULT_API_HOST = 'https://api.swetrix.com/log';
@@ -107,11 +107,70 @@
107
107
  this.options = options;
108
108
  this.pageData = null;
109
109
  this.pageViewsOptions = null;
110
+ this.errorsOptions = null;
110
111
  this.perfStatsCollected = false;
111
112
  this.activePage = null;
113
+ this.errorListenerExists = false;
112
114
  this.trackPathChange = this.trackPathChange.bind(this);
113
115
  this.heartbeat = this.heartbeat.bind(this);
116
+ this.captureError = this.captureError.bind(this);
114
117
  }
118
+ Lib.prototype.captureError = function (event) {
119
+ var _a, _b, _c;
120
+ if (typeof ((_a = this.errorsOptions) === null || _a === void 0 ? void 0 : _a.sampleRate) === 'number' && this.errorsOptions.sampleRate > Math.random()) {
121
+ return;
122
+ }
123
+ this.submitError({
124
+ // The file in which error occured.
125
+ filename: event.filename,
126
+ // The line of code error occured on.
127
+ lineno: event.lineno,
128
+ // The column of code error occured on.
129
+ colno: event.colno,
130
+ // Name of the error, if not exists (i.e. it's a custom thrown error). The initial value of name is "Error", but just in case lets explicitly set it here too.
131
+ name: ((_b = event.error) === null || _b === void 0 ? void 0 : _b.name) || 'Error',
132
+ // Description of the error. By default, we use message from Error object, is it does not contain the error name
133
+ // (we want to split error name and message so we could group them together later in dashboard).
134
+ // If message in error object does not exist - lets use a message from the Error event itself.
135
+ message: ((_c = event.error) === null || _c === void 0 ? void 0 : _c.message) || event.message,
136
+ });
137
+ };
138
+ Lib.prototype.trackErrors = function (options) {
139
+ var _this = this;
140
+ if (this.errorListenerExists || !this.canTrack()) {
141
+ return defaultActions;
142
+ }
143
+ this.errorsOptions = options;
144
+ window.addEventListener('error', this.captureError);
145
+ this.errorListenerExists = true;
146
+ return {
147
+ stop: function () {
148
+ window.removeEventListener('error', _this.captureError);
149
+ },
150
+ };
151
+ };
152
+ Lib.prototype.submitError = function (payload, evokeCallback) {
153
+ var _a, _b, _c;
154
+ var privateData = {
155
+ pid: this.projectID,
156
+ };
157
+ var errorPayload = __assign({ pg: this.activePage ||
158
+ getPath({
159
+ hash: (_a = this.pageViewsOptions) === null || _a === void 0 ? void 0 : _a.hash,
160
+ search: (_b = this.pageViewsOptions) === null || _b === void 0 ? void 0 : _b.search,
161
+ }), lc: getLocale(), tz: getTimezone() }, payload);
162
+ if (evokeCallback && ((_c = this.errorsOptions) === null || _c === void 0 ? void 0 : _c.callback)) {
163
+ var callbackResult = this.errorsOptions.callback(errorPayload);
164
+ if (callbackResult === false) {
165
+ return;
166
+ }
167
+ if (callbackResult && typeof callbackResult === 'object') {
168
+ Object.assign(errorPayload, callbackResult);
169
+ }
170
+ }
171
+ Object.assign(errorPayload, privateData);
172
+ this.sendRequest('error', errorPayload);
173
+ };
115
174
  Lib.prototype.track = function (event) {
116
175
  if (!this.canTrack()) {
117
176
  return;
@@ -121,7 +180,7 @@
121
180
  };
122
181
  Lib.prototype.trackPageViews = function (options) {
123
182
  if (!this.canTrack()) {
124
- return defaultPageActions;
183
+ return defaultActions;
125
184
  }
126
185
  if (this.pageData) {
127
186
  return this.pageData.actions;
@@ -315,17 +374,15 @@
315
374
  exports.LIB_INSTANCE.track(event);
316
375
  }
317
376
  /**
318
- * With this function you are able to track any custom events you want.
319
- * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.
320
- * The total number of track calls and their conversion rate will be saved.
377
+ * With this function you are able to automatically track pageviews across your application.
321
378
  *
322
- * @param {PageViewsOptions} options The options related to the custom event.
379
+ * @param {PageViewsOptions} options Pageviews tracking options.
323
380
  * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
324
381
  */
325
382
  function trackViews(options) {
326
383
  return new Promise(function (resolve) {
327
384
  if (!exports.LIB_INSTANCE) {
328
- resolve(defaultPageActions);
385
+ resolve(defaultActions);
329
386
  return;
330
387
  }
331
388
  // We need to verify that document.readyState is complete for the performance stats to be collected correctly.
@@ -340,6 +397,32 @@
340
397
  }
341
398
  });
342
399
  }
400
+ /**
401
+ * With this function you are able to track any custom events you want.
402
+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.
403
+ * The total number of track calls and their conversion rate will be saved.
404
+ *
405
+ * @param {PageViewsOptions} options The options related to the custom event.
406
+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
407
+ */
408
+ function trackErrors(options) {
409
+ if (!exports.LIB_INSTANCE) {
410
+ return defaultActions;
411
+ }
412
+ return exports.LIB_INSTANCE.trackErrors(options);
413
+ }
414
+ /**
415
+ * This function is used to manually track an error event.
416
+ * It's useful if you want to track specific errors in your application.
417
+ *
418
+ * @param payload Swetrix error object to send.
419
+ * @returns void
420
+ */
421
+ function trackError(payload) {
422
+ if (!exports.LIB_INSTANCE)
423
+ return;
424
+ exports.LIB_INSTANCE.submitError(payload, false);
425
+ }
343
426
  /**
344
427
  * This function is used to manually track a page view event.
345
428
  * It's useful if your application uses esoteric routing which is not supported by Swetrix by default.
@@ -357,6 +440,8 @@
357
440
 
358
441
  exports.init = init;
359
442
  exports.track = track;
443
+ exports.trackError = trackError;
444
+ exports.trackErrors = trackErrors;
360
445
  exports.trackPageview = trackPageview;
361
446
  exports.trackViews = trackViews;
362
447
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "swetrix",
3
- "version": "3.0.3",
3
+ "version": "3.1.0",
4
4
  "description": "The JavaScript analytics client for Swetrix Analytics",
5
5
  "main": "dist/swetrix.cjs.js",
6
6
  "module": "dist/swetrix.es5.js",
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "homepage": "https://docs.swetrix.com",
36
36
  "dependencies": {
37
- "@types/node": "^20.11.8",
37
+ "@types/node": "^20.12.10",
38
38
  "tslib": "^2.6.2"
39
39
  },
40
40
  "devDependencies": {
@@ -46,6 +46,6 @@
46
46
  "rollup-plugin-sourcemaps": "^0.6.3",
47
47
  "rollup-plugin-typescript2": "^0.36.0",
48
48
  "rollup-plugin-uglify": "^6.0.4",
49
- "typescript": "^5.3.3"
49
+ "typescript": "^5.4.5"
50
50
  }
51
51
  }
package/src/Lib.ts CHANGED
@@ -57,6 +57,21 @@ export interface IPageViewPayload {
57
57
  prev: string | null | undefined
58
58
  }
59
59
 
60
+ // Partial user-editable error payload
61
+ export interface IErrorEventPayload {
62
+ name: string
63
+ message: string | null | undefined
64
+ lineno: number | null | undefined
65
+ colno: number | null | undefined
66
+ filename: string | null | undefined
67
+ }
68
+
69
+ export interface IInternalErrorEventPayload extends IErrorEventPayload {
70
+ lc: string | undefined
71
+ tz: string | undefined
72
+ pg: string | null | undefined
73
+ }
74
+
60
75
  interface IPerfPayload {
61
76
  dns: number
62
77
  tls: number
@@ -76,6 +91,14 @@ export interface PageActions {
76
91
  stop: () => void
77
92
  }
78
93
 
94
+ /**
95
+ * The object returned by `trackErrors()`, used to stop tracking errors.
96
+ */
97
+ export interface ErrorActions {
98
+ /** Stops the tracking of errors. */
99
+ stop: () => void
100
+ }
101
+
79
102
  export interface PageData {
80
103
  /** Current URL path. */
81
104
  path: string
@@ -84,6 +107,25 @@ export interface PageData {
84
107
  actions: PageActions
85
108
  }
86
109
 
110
+ export interface ErrorOptions {
111
+ /**
112
+ * A number that indicates how many errors should be sent to the server.
113
+ * Accepts values between 0 and 1. For example, if set to 0.5 - only ~50% of errors will be sent to Swetrix.
114
+ * For testing, we recommend setting this value to 1. For production, you should configure it depending on your needs as each error event counts towards your plan.
115
+ *
116
+ * The default value for this option is 1.
117
+ */
118
+ sampleRate?: number
119
+
120
+ /**
121
+ * Callback to edit / prevent sending errors.
122
+ *
123
+ * @param payload - The error payload.
124
+ * @returns The edited payload or `false` to prevent sending the error event. If `true` is returned, the payload will be sent as-is.
125
+ */
126
+ callback?: (payload: IInternalErrorEventPayload) => Partial<IInternalErrorEventPayload> | boolean
127
+ }
128
+
87
129
  export interface PageViewsOptions {
88
130
  /**
89
131
  * If set to `true`, only unique events will be saved.
@@ -115,7 +157,7 @@ export interface PageViewsOptions {
115
157
  callback?: (payload: IPageViewPayload) => Partial<IPageViewPayload> | boolean
116
158
  }
117
159
 
118
- export const defaultPageActions = {
160
+ export const defaultActions = {
119
161
  stop() {},
120
162
  }
121
163
 
@@ -124,12 +166,91 @@ const DEFAULT_API_HOST = 'https://api.swetrix.com/log'
124
166
  export class Lib {
125
167
  private pageData: PageData | null = null
126
168
  private pageViewsOptions: PageViewsOptions | null | undefined = null
169
+ private errorsOptions: ErrorOptions | null | undefined = null
127
170
  private perfStatsCollected: Boolean = false
128
171
  private activePage: string | null = null
172
+ private errorListenerExists = false
129
173
 
130
174
  constructor(private projectID: string, private options?: LibOptions) {
131
175
  this.trackPathChange = this.trackPathChange.bind(this)
132
176
  this.heartbeat = this.heartbeat.bind(this)
177
+ this.captureError = this.captureError.bind(this)
178
+ }
179
+
180
+ captureError(event: ErrorEvent): void {
181
+ if (typeof this.errorsOptions?.sampleRate === 'number' && this.errorsOptions.sampleRate > Math.random()) {
182
+ return
183
+ }
184
+
185
+ this.submitError({
186
+ // The file in which error occured.
187
+ filename: event.filename,
188
+
189
+ // The line of code error occured on.
190
+ lineno: event.lineno,
191
+
192
+ // The column of code error occured on.
193
+ colno: event.colno,
194
+
195
+ // Name of the error, if not exists (i.e. it's a custom thrown error). The initial value of name is "Error", but just in case lets explicitly set it here too.
196
+ name: event.error?.name || 'Error',
197
+
198
+ // Description of the error. By default, we use message from Error object, is it does not contain the error name
199
+ // (we want to split error name and message so we could group them together later in dashboard).
200
+ // If message in error object does not exist - lets use a message from the Error event itself.
201
+ message: event.error?.message || event.message,
202
+ })
203
+ }
204
+
205
+ trackErrors(options?: ErrorOptions): ErrorActions {
206
+ if (this.errorListenerExists || !this.canTrack()) {
207
+ return defaultActions
208
+ }
209
+
210
+ this.errorsOptions = options
211
+
212
+ window.addEventListener('error', this.captureError)
213
+ this.errorListenerExists = true
214
+
215
+ return {
216
+ stop: () => {
217
+ window.removeEventListener('error', this.captureError)
218
+ },
219
+ }
220
+ }
221
+
222
+ submitError(payload: IErrorEventPayload, evokeCallback?: boolean): void {
223
+ const privateData = {
224
+ pid: this.projectID,
225
+ }
226
+
227
+ const errorPayload = {
228
+ pg:
229
+ this.activePage ||
230
+ getPath({
231
+ hash: this.pageViewsOptions?.hash,
232
+ search: this.pageViewsOptions?.search,
233
+ }),
234
+ lc: getLocale(),
235
+ tz: getTimezone(),
236
+ ...payload,
237
+ }
238
+
239
+ if (evokeCallback && this.errorsOptions?.callback) {
240
+ const callbackResult = this.errorsOptions.callback(errorPayload)
241
+
242
+ if (callbackResult === false) {
243
+ return
244
+ }
245
+
246
+ if (callbackResult && typeof callbackResult === 'object') {
247
+ Object.assign(errorPayload, callbackResult)
248
+ }
249
+ }
250
+
251
+ Object.assign(errorPayload, privateData)
252
+
253
+ this.sendRequest('error', errorPayload)
133
254
  }
134
255
 
135
256
  track(event: TrackEventOptions): void {
@@ -153,7 +274,7 @@ export class Lib {
153
274
 
154
275
  trackPageViews(options?: PageViewsOptions): PageActions {
155
276
  if (!this.canTrack()) {
156
- return defaultPageActions
277
+ return defaultActions
157
278
  }
158
279
 
159
280
  if (this.pageData) {
package/src/index.ts CHANGED
@@ -1,4 +1,14 @@
1
- import { Lib, LibOptions, TrackEventOptions, PageViewsOptions, PageActions, defaultPageActions } from './Lib'
1
+ import {
2
+ Lib,
3
+ LibOptions,
4
+ TrackEventOptions,
5
+ PageViewsOptions,
6
+ ErrorOptions,
7
+ PageActions,
8
+ ErrorActions,
9
+ defaultActions,
10
+ IErrorEventPayload,
11
+ } from './Lib'
2
12
 
3
13
  export let LIB_INSTANCE: Lib | null = null
4
14
 
@@ -31,17 +41,15 @@ export function track(event: TrackEventOptions): void {
31
41
  }
32
42
 
33
43
  /**
34
- * With this function you are able to track any custom events you want.
35
- * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.
36
- * The total number of track calls and their conversion rate will be saved.
44
+ * With this function you are able to automatically track pageviews across your application.
37
45
  *
38
- * @param {PageViewsOptions} options The options related to the custom event.
46
+ * @param {PageViewsOptions} options Pageviews tracking options.
39
47
  * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
40
48
  */
41
49
  export function trackViews(options?: PageViewsOptions): Promise<PageActions> {
42
50
  return new Promise((resolve) => {
43
51
  if (!LIB_INSTANCE) {
44
- resolve(defaultPageActions)
52
+ resolve(defaultActions)
45
53
  return
46
54
  }
47
55
 
@@ -57,6 +65,35 @@ export function trackViews(options?: PageViewsOptions): Promise<PageActions> {
57
65
  })
58
66
  }
59
67
 
68
+ /**
69
+ * With this function you are able to track any custom events you want.
70
+ * You should never send any identifiable data (like User ID, email, session cookie, etc.) as an event name.
71
+ * The total number of track calls and their conversion rate will be saved.
72
+ *
73
+ * @param {PageViewsOptions} options The options related to the custom event.
74
+ * @returns {PageActions} The actions related to the tracking. Used to stop tracking pages.
75
+ */
76
+ export function trackErrors(options?: ErrorOptions): ErrorActions {
77
+ if (!LIB_INSTANCE) {
78
+ return defaultActions
79
+ }
80
+
81
+ return LIB_INSTANCE.trackErrors(options)
82
+ }
83
+
84
+ /**
85
+ * This function is used to manually track an error event.
86
+ * It's useful if you want to track specific errors in your application.
87
+ *
88
+ * @param payload Swetrix error object to send.
89
+ * @returns void
90
+ */
91
+ export function trackError(payload: IErrorEventPayload): void {
92
+ if (!LIB_INSTANCE) return
93
+
94
+ LIB_INSTANCE.submitError(payload, false)
95
+ }
96
+
60
97
  /**
61
98
  * This function is used to manually track a page view event.
62
99
  * It's useful if your application uses esoteric routing which is not supported by Swetrix by default.