clarity-js 0.8.3 → 0.8.4-beta

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.
Files changed (102) hide show
  1. package/README.md +26 -26
  2. package/build/clarity.extended.js +1 -1
  3. package/build/clarity.insight.js +1 -1
  4. package/build/clarity.js +5563 -5538
  5. package/build/clarity.min.js +1 -1
  6. package/build/clarity.module.js +5563 -5538
  7. package/build/clarity.performance.js +1 -1
  8. package/package.json +70 -70
  9. package/rollup.config.ts +98 -98
  10. package/src/clarity.ts +60 -60
  11. package/src/core/api.ts +8 -8
  12. package/src/core/config.ts +32 -32
  13. package/src/core/copy.ts +3 -3
  14. package/src/core/event.ts +53 -53
  15. package/src/core/hash.ts +19 -19
  16. package/src/core/history.ts +73 -73
  17. package/src/core/index.ts +83 -83
  18. package/src/core/measure.ts +19 -19
  19. package/src/core/report.ts +28 -28
  20. package/src/core/scrub.ts +196 -196
  21. package/src/core/task.ts +180 -180
  22. package/src/core/time.ts +19 -19
  23. package/src/core/timeout.ts +10 -10
  24. package/src/core/version.ts +2 -2
  25. package/src/data/baseline.ts +155 -155
  26. package/src/data/compress.ts +31 -31
  27. package/src/data/consent.ts +20 -20
  28. package/src/data/custom.ts +23 -23
  29. package/src/data/dimension.ts +53 -53
  30. package/src/data/encode.ts +140 -140
  31. package/src/data/envelope.ts +53 -53
  32. package/src/data/extract.ts +211 -211
  33. package/src/data/index.ts +46 -46
  34. package/src/data/limit.ts +44 -44
  35. package/src/data/metadata.ts +356 -356
  36. package/src/data/metric.ts +51 -51
  37. package/src/data/ping.ts +36 -36
  38. package/src/data/signal.ts +30 -30
  39. package/src/data/summary.ts +34 -34
  40. package/src/data/token.ts +39 -39
  41. package/src/data/upgrade.ts +37 -37
  42. package/src/data/upload.ts +283 -283
  43. package/src/data/variable.ts +83 -83
  44. package/src/diagnostic/encode.ts +40 -40
  45. package/src/diagnostic/fraud.ts +36 -36
  46. package/src/diagnostic/index.ts +15 -15
  47. package/src/diagnostic/internal.ts +28 -28
  48. package/src/diagnostic/script.ts +37 -37
  49. package/src/global.ts +6 -6
  50. package/src/index.ts +9 -9
  51. package/src/insight/blank.ts +14 -14
  52. package/src/insight/encode.ts +60 -60
  53. package/src/insight/snapshot.ts +114 -114
  54. package/src/interaction/change.ts +40 -40
  55. package/src/interaction/click.ts +194 -162
  56. package/src/interaction/clipboard.ts +34 -34
  57. package/src/interaction/encode.ts +196 -193
  58. package/src/interaction/index.ts +59 -59
  59. package/src/interaction/input.ts +59 -59
  60. package/src/interaction/pointer.ts +139 -139
  61. package/src/interaction/resize.ts +47 -47
  62. package/src/interaction/scroll.ts +124 -124
  63. package/src/interaction/selection.ts +68 -68
  64. package/src/interaction/submit.ts +32 -32
  65. package/src/interaction/timeline.ts +65 -65
  66. package/src/interaction/unload.ts +28 -28
  67. package/src/interaction/visibility.ts +26 -26
  68. package/src/layout/animation.ts +133 -133
  69. package/src/layout/discover.ts +31 -31
  70. package/src/layout/document.ts +48 -48
  71. package/src/layout/dom.ts +437 -437
  72. package/src/layout/encode.ts +147 -147
  73. package/src/layout/index.ts +41 -41
  74. package/src/layout/mutation.ts +409 -409
  75. package/src/layout/node.ts +292 -292
  76. package/src/layout/offset.ts +19 -19
  77. package/src/layout/region.ts +153 -153
  78. package/src/layout/schema.ts +63 -63
  79. package/src/layout/selector.ts +82 -82
  80. package/src/layout/style.ts +150 -150
  81. package/src/layout/target.ts +32 -32
  82. package/src/layout/traverse.ts +27 -27
  83. package/src/performance/blank.ts +7 -7
  84. package/src/performance/encode.ts +31 -31
  85. package/src/performance/index.ts +14 -14
  86. package/src/performance/interaction.ts +125 -125
  87. package/src/performance/navigation.ts +31 -31
  88. package/src/performance/observer.ts +108 -108
  89. package/src/queue.ts +33 -33
  90. package/test/core.test.ts +139 -139
  91. package/test/helper.ts +162 -162
  92. package/test/html/core.html +27 -27
  93. package/test/tsconfig.test.json +5 -5
  94. package/tsconfig.json +21 -21
  95. package/tslint.json +32 -32
  96. package/types/core.d.ts +153 -153
  97. package/types/data.d.ts +513 -510
  98. package/types/diagnostic.d.ts +24 -24
  99. package/types/index.d.ts +39 -39
  100. package/types/interaction.d.ts +168 -165
  101. package/types/layout.d.ts +272 -272
  102. package/types/performance.d.ts +64 -64
@@ -1,283 +1,283 @@
1
- import { UploadCallback } from "@clarity-types/core";
2
- import { BooleanFlag, Check, Constant, EncodedPayload, Event, Metric, Setting, Token, Transit, UploadData, XMLReadyState } from "@clarity-types/data";
3
- import * as clarity from "@src/clarity";
4
- import config from "@src/core/config";
5
- import measure from "@src/core/measure";
6
- import { time } from "@src/core/time";
7
- import { clearTimeout, setTimeout } from "@src/core/timeout";
8
- import compress from "@src/data/compress";
9
- import encode from "@src/data/encode";
10
- import * as envelope from "@src/data/envelope";
11
- import * as data from "@src/data/index";
12
- import * as limit from "@src/data/limit";
13
- import * as metadata from "@src/data/metadata";
14
- import * as metric from "@src/data/metric";
15
- import * as ping from "@src/data/ping";
16
- import * as timeline from "@src/interaction/timeline";
17
- import * as region from "@src/layout/region";
18
- import * as extract from "@src/data/extract";
19
- import * as style from "@src/layout/style";
20
- import { report } from "@src/core/report";
21
- import { signalsEvent } from "@src/data/signal";
22
-
23
- let discoverBytes: number = 0;
24
- let playbackBytes: number = 0;
25
- let playback: string[];
26
- let analysis: string[];
27
- let timeout: number = null;
28
- let transit: Transit;
29
- let active: boolean;
30
- let queuedTime: number = 0;
31
- export let track: UploadData;
32
-
33
- export function start(): void {
34
- active = true;
35
- discoverBytes = 0;
36
- playbackBytes = 0;
37
- queuedTime = 0;
38
- playback = [];
39
- analysis = [];
40
- transit = {};
41
- track = null;
42
- }
43
-
44
- export function queue(tokens: Token[], transmit: boolean = true): void {
45
- if (active) {
46
- let now = time();
47
- let type = tokens.length > 1 ? tokens[1] : null;
48
- let event = JSON.stringify(tokens);
49
-
50
- switch (type) {
51
- case Event.Discover:
52
- discoverBytes += event.length;
53
- case Event.Box:
54
- case Event.Mutation:
55
- case Event.Snapshot:
56
- case Event.StyleSheetAdoption:
57
- case Event.StyleSheetUpdate:
58
- playbackBytes += event.length;
59
- playback.push(event);
60
- break;
61
- default:
62
- analysis.push(event);
63
- break;
64
- }
65
-
66
- // Increment event count metric
67
- metric.count(Metric.EventCount);
68
-
69
- // Following two checks are precautionary and act as a fail safe mechanism to get out of unexpected situations.
70
- // Check 1: If for any reason the upload hasn't happened after waiting for 2x the config.delay time,
71
- // reset the timer. This allows Clarity to attempt an upload again.
72
- let gap = delay();
73
- if (now - queuedTime > (gap * 2)) {
74
- clearTimeout(timeout);
75
- timeout = null;
76
- }
77
-
78
- // Transmit Check: When transmit is set to true (default), it indicates that we should schedule an upload
79
- // However, in certain scenarios - like metric calculation - which are triggered as part of an existing upload
80
- // We enrich the data going out with the existing upload. In these cases, call to upload comes with 'transmit' set to false.
81
- if (transmit && timeout === null) {
82
- if (type !== Event.Ping) { ping.reset(); }
83
- timeout = setTimeout(upload, gap);
84
- queuedTime = now;
85
- limit.check(playbackBytes);
86
- }
87
- }
88
- }
89
-
90
- export function stop(): void {
91
- clearTimeout(timeout);
92
- upload(true);
93
- discoverBytes = 0;
94
- playbackBytes = 0;
95
- queuedTime = 0;
96
- playback = [];
97
- analysis = [];
98
- transit = {};
99
- track = null;
100
- active = false;
101
- }
102
-
103
- async function upload(final: boolean = false): Promise<void> {
104
- timeout = null;
105
-
106
- // Check if we can send playback bytes over the wire or not
107
- // For better instrumentation coverage, we send playback bytes from second sequence onwards
108
- // And, we only send playback metric when we are able to send the playback bytes back to server
109
- let sendPlaybackBytes = config.lean === false && playbackBytes > 0 && (playbackBytes < Setting.MaxFirstPayloadBytes || envelope.data.sequence > 0);
110
- if (sendPlaybackBytes) { metric.max(Metric.Playback, BooleanFlag.True); }
111
-
112
- // CAUTION: Ensure "transmit" is set to false in the queue function for following events
113
- // Otherwise you run a risk of infinite loop.
114
- region.compute();
115
- timeline.compute();
116
- data.compute();
117
- style.compute();
118
-
119
- // Treat this as the last payload only if final boolean was explicitly set to true.
120
- // In real world tests, we noticed that certain third party scripts (e.g. https://www.npmjs.com/package/raven-js)
121
- // could inject function arguments for internal tracking (likely stack traces for script errors).
122
- // For these edge cases, we want to ensure that an injected object (e.g. {"key": "value"}) isn't mistaken to be true.
123
- let last = final === true;
124
- let e = JSON.stringify(envelope.envelope(last));
125
- let a = `[${analysis.join()}]`;
126
-
127
- let p = sendPlaybackBytes ? `[${playback.join()}]` : Constant.Empty;
128
- let encoded: EncodedPayload = {e, a, p};
129
-
130
- // Get the payload ready for sending over the wire
131
- // We also attempt to compress the payload if it is not the last payload and the browser supports it
132
- // In all other cases, we continue to send back string value
133
- let payload = stringify(encoded);
134
- let zipped = last ? null : await compress(payload)
135
- metric.sum(Metric.TotalBytes, zipped ? zipped.length : payload.length);
136
- send(payload, zipped, envelope.data.sequence, last);
137
-
138
- // Clear out events now that payload has been dispatched
139
- analysis = [];
140
- if (sendPlaybackBytes) {
141
- playback = [];
142
- playbackBytes = 0;
143
- discoverBytes = 0;
144
- }
145
- }
146
-
147
- function stringify(encoded: EncodedPayload): string {
148
- return encoded.p.length > 0 ? `{"e":${encoded.e},"a":${encoded.a},"p":${encoded.p}}` : `{"e":${encoded.e},"a":${encoded.a}}`;
149
- }
150
-
151
- function send(payload: string, zipped: Uint8Array, sequence: number, beacon: boolean = false): void {
152
- // Upload data if a valid URL is defined in the config
153
- if (typeof config.upload === Constant.String) {
154
- const url = config.upload as string;
155
- let dispatched = false;
156
-
157
- // If it's the last payload, attempt to upload using sendBeacon first.
158
- // The advantage to using sendBeacon is that browser can decide to upload asynchronously, improving chances of success
159
- // However, we don't want to rely on it for every payload, since we have no ability to retry if the upload failed.
160
- // Also, in case of sendBeacon, we do not have a way to alter HTTP headers and therefore can't send compressed payload
161
- if (beacon && "sendBeacon" in navigator) {
162
- try {
163
- // Navigator needs to be bound to sendBeacon before it is used to avoid errors in some browsers
164
- dispatched = navigator.sendBeacon.bind(navigator)(url, payload);
165
- if (dispatched) { done(sequence); }
166
- } catch { /* do nothing - and we will automatically fallback to XHR below */ }
167
- }
168
-
169
- // Before initiating XHR upload, we check if the data has already been uploaded using sendBeacon
170
- // There are two cases when dispatched could still be false:
171
- // a) It's not the last payload, and therefore we didn't attempt sending sendBeacon
172
- // b) It's the last payload, however, we failed to queue sendBeacon call and need to now fall back to XHR.
173
- // E.g. if data is over 64KB, several user agents (like Chrome) will reject to queue the sendBeacon call.
174
- if (dispatched === false) {
175
- // While tracking payload for retry, we only track string value of the payload to err on the safe side
176
- // Not all browsers support compression API and the support for it in supported browsers is still experimental
177
- if (sequence in transit) { transit[sequence].attempts++; } else { transit[sequence] = { data: payload, attempts: 1 }; }
178
- let xhr = new XMLHttpRequest();
179
- xhr.open("POST", url, true);
180
- xhr.timeout = Setting.UploadTimeout;
181
- xhr.ontimeout = () => { report(new Error(`${Constant.Timeout} : ${url}`)) };
182
- if (sequence !== null) { xhr.onreadystatechange = (): void => { measure(check)(xhr, sequence); }; }
183
- xhr.withCredentials = true;
184
- if (zipped) {
185
- // If we do have valid compressed array, send it with appropriate HTTP headers so server can decode it appropriately
186
- xhr.setRequestHeader(Constant.Accept, Constant.ClarityGzip);
187
- xhr.send(zipped);
188
- } else {
189
- // In all other cases, continue sending string back to the server
190
- xhr.send(payload);
191
- }
192
- }
193
- } else if (config.upload) {
194
- const callback = config.upload as UploadCallback;
195
- callback(payload);
196
- done(sequence);
197
- }
198
- }
199
-
200
- function check(xhr: XMLHttpRequest, sequence: number): void {
201
- var transitData = transit[sequence];
202
- if (xhr && xhr.readyState === XMLReadyState.Done && transitData) {
203
- // Attempt send payload again (as configured in settings) if we do not receive a success (2XX) response code back from the server
204
- if ((xhr.status < 200 || xhr.status > 208) && transitData.attempts <= Setting.RetryLimit) {
205
- // We re-attempt in all cases except when server explicitly rejects our request with 4XX error
206
- if (xhr.status >= 400 && xhr.status < 500) {
207
- // In case of a 4XX response from the server, we bail out instead of trying again
208
- limit.trigger(Check.Server);
209
- } else {
210
- // Browser will send status = 0 when it refuses to put network request over the wire
211
- // This could happen for several reasons, couple of known ones are:
212
- // 1: Browsers block upload because of content security policy violation
213
- // 2: Safari will terminate pending XHR requests with status code 0 if the user navigates away from the page
214
- // In any case, we switch the upload URL to fallback configuration (if available) before re-trying one more time
215
- if (xhr.status === 0) { config.upload = config.fallback ? config.fallback : config.upload; }
216
- // In all other cases, re-attempt sending the same data
217
- // For retry we always fallback to string payload, even though we may have attempted
218
- // sending zipped payload earlier
219
- send(transitData.data, null, sequence);
220
- }
221
- } else {
222
- track = { sequence, attempts: transitData.attempts, status: xhr.status };
223
- // Send back an event only if we were not successful in our first attempt
224
- if (transitData.attempts > 1) { encode(Event.Upload); }
225
- // Handle response if it was a 200 response with a valid body
226
- if (xhr.status === 200 && xhr.responseText) { response(xhr.responseText); }
227
- // If we exhausted our retries then trigger Clarity's shutdown for this page since the data will be incomplete
228
- if (xhr.status === 0) {
229
- // And, right before we terminate the session, we will attempt one last time to see if we can use
230
- // different transport option (sendBeacon vs. XHR) to get this data to the server for analysis purposes
231
- send(transitData.data, null, sequence, true);
232
- limit.trigger(Check.Retry);
233
- }
234
- // Signal that this request completed successfully
235
- if (xhr.status >= 200 && xhr.status <= 208) { done(sequence); }
236
- // Stop tracking this payload now that it's all done
237
- delete transit[sequence];
238
- }
239
- }
240
- }
241
-
242
- function done(sequence: number): void {
243
- // If we everything went successfully, and it is the first sequence, save this session for future reference
244
- if (sequence === 1) {
245
- metadata.save();
246
- metadata.callback();
247
- }
248
- }
249
-
250
- function delay(): number {
251
- // Progressively increase delay as we continue to send more payloads from the client to the server
252
- // If we are not uploading data to a server, and instead invoking UploadCallback, in that case keep returning configured value
253
- let gap = config.lean === false && discoverBytes > 0 ? Setting.MinUploadDelay : envelope.data.sequence * config.delay;
254
- return typeof config.upload === Constant.String ? Math.max(Math.min(gap, Setting.MaxUploadDelay), Setting.MinUploadDelay) : config.delay;
255
- }
256
-
257
- function response(payload: string): void {
258
- let lines = payload && payload.length > 0 ? payload.split("\n") : [];
259
- for (var line of lines)
260
- {
261
- let parts = line && line.length > 0 ? line.split(/ (.*)/) : [Constant.Empty];
262
- switch (parts[0]) {
263
- case Constant.End:
264
- // Clear out session storage and end the session so we can start fresh the next time
265
- limit.trigger(Check.Server);
266
- break;
267
- case Constant.Upgrade:
268
- // Upgrade current session to send back playback information
269
- clarity.upgrade(Constant.Auto);
270
- break;
271
- case Constant.Action:
272
- // Invoke action callback, if configured and has a valid value
273
- if (config.action && parts.length > 1) { config.action(parts[1]); }
274
- break;
275
- case Constant.Extract:
276
- if (parts.length > 1) { extract.trigger(parts[1]); }
277
- break;
278
- case Constant.Signal:
279
- if (parts.length > 1) { signalsEvent(parts[1]); }
280
- break;
281
- }
282
- }
283
- }
1
+ import { UploadCallback } from "@clarity-types/core";
2
+ import { BooleanFlag, Check, Constant, EncodedPayload, Event, Metric, Setting, Token, Transit, UploadData, XMLReadyState } from "@clarity-types/data";
3
+ import * as clarity from "@src/clarity";
4
+ import config from "@src/core/config";
5
+ import measure from "@src/core/measure";
6
+ import { time } from "@src/core/time";
7
+ import { clearTimeout, setTimeout } from "@src/core/timeout";
8
+ import compress from "@src/data/compress";
9
+ import encode from "@src/data/encode";
10
+ import * as envelope from "@src/data/envelope";
11
+ import * as data from "@src/data/index";
12
+ import * as limit from "@src/data/limit";
13
+ import * as metadata from "@src/data/metadata";
14
+ import * as metric from "@src/data/metric";
15
+ import * as ping from "@src/data/ping";
16
+ import * as timeline from "@src/interaction/timeline";
17
+ import * as region from "@src/layout/region";
18
+ import * as extract from "@src/data/extract";
19
+ import * as style from "@src/layout/style";
20
+ import { report } from "@src/core/report";
21
+ import { signalsEvent } from "@src/data/signal";
22
+
23
+ let discoverBytes: number = 0;
24
+ let playbackBytes: number = 0;
25
+ let playback: string[];
26
+ let analysis: string[];
27
+ let timeout: number = null;
28
+ let transit: Transit;
29
+ let active: boolean;
30
+ let queuedTime: number = 0;
31
+ export let track: UploadData;
32
+
33
+ export function start(): void {
34
+ active = true;
35
+ discoverBytes = 0;
36
+ playbackBytes = 0;
37
+ queuedTime = 0;
38
+ playback = [];
39
+ analysis = [];
40
+ transit = {};
41
+ track = null;
42
+ }
43
+
44
+ export function queue(tokens: Token[], transmit: boolean = true): void {
45
+ if (active) {
46
+ let now = time();
47
+ let type = tokens.length > 1 ? tokens[1] : null;
48
+ let event = JSON.stringify(tokens);
49
+
50
+ switch (type) {
51
+ case Event.Discover:
52
+ discoverBytes += event.length;
53
+ case Event.Box:
54
+ case Event.Mutation:
55
+ case Event.Snapshot:
56
+ case Event.StyleSheetAdoption:
57
+ case Event.StyleSheetUpdate:
58
+ playbackBytes += event.length;
59
+ playback.push(event);
60
+ break;
61
+ default:
62
+ analysis.push(event);
63
+ break;
64
+ }
65
+
66
+ // Increment event count metric
67
+ metric.count(Metric.EventCount);
68
+
69
+ // Following two checks are precautionary and act as a fail safe mechanism to get out of unexpected situations.
70
+ // Check 1: If for any reason the upload hasn't happened after waiting for 2x the config.delay time,
71
+ // reset the timer. This allows Clarity to attempt an upload again.
72
+ let gap = delay();
73
+ if (now - queuedTime > (gap * 2)) {
74
+ clearTimeout(timeout);
75
+ timeout = null;
76
+ }
77
+
78
+ // Transmit Check: When transmit is set to true (default), it indicates that we should schedule an upload
79
+ // However, in certain scenarios - like metric calculation - which are triggered as part of an existing upload
80
+ // We enrich the data going out with the existing upload. In these cases, call to upload comes with 'transmit' set to false.
81
+ if (transmit && timeout === null) {
82
+ if (type !== Event.Ping) { ping.reset(); }
83
+ timeout = setTimeout(upload, gap);
84
+ queuedTime = now;
85
+ limit.check(playbackBytes);
86
+ }
87
+ }
88
+ }
89
+
90
+ export function stop(): void {
91
+ clearTimeout(timeout);
92
+ upload(true);
93
+ discoverBytes = 0;
94
+ playbackBytes = 0;
95
+ queuedTime = 0;
96
+ playback = [];
97
+ analysis = [];
98
+ transit = {};
99
+ track = null;
100
+ active = false;
101
+ }
102
+
103
+ async function upload(final: boolean = false): Promise<void> {
104
+ timeout = null;
105
+
106
+ // Check if we can send playback bytes over the wire or not
107
+ // For better instrumentation coverage, we send playback bytes from second sequence onwards
108
+ // And, we only send playback metric when we are able to send the playback bytes back to server
109
+ let sendPlaybackBytes = config.lean === false && playbackBytes > 0 && (playbackBytes < Setting.MaxFirstPayloadBytes || envelope.data.sequence > 0);
110
+ if (sendPlaybackBytes) { metric.max(Metric.Playback, BooleanFlag.True); }
111
+
112
+ // CAUTION: Ensure "transmit" is set to false in the queue function for following events
113
+ // Otherwise you run a risk of infinite loop.
114
+ region.compute();
115
+ timeline.compute();
116
+ data.compute();
117
+ style.compute();
118
+
119
+ // Treat this as the last payload only if final boolean was explicitly set to true.
120
+ // In real world tests, we noticed that certain third party scripts (e.g. https://www.npmjs.com/package/raven-js)
121
+ // could inject function arguments for internal tracking (likely stack traces for script errors).
122
+ // For these edge cases, we want to ensure that an injected object (e.g. {"key": "value"}) isn't mistaken to be true.
123
+ let last = final === true;
124
+ let e = JSON.stringify(envelope.envelope(last));
125
+ let a = `[${analysis.join()}]`;
126
+
127
+ let p = sendPlaybackBytes ? `[${playback.join()}]` : Constant.Empty;
128
+ let encoded: EncodedPayload = {e, a, p};
129
+
130
+ // Get the payload ready for sending over the wire
131
+ // We also attempt to compress the payload if it is not the last payload and the browser supports it
132
+ // In all other cases, we continue to send back string value
133
+ let payload = stringify(encoded);
134
+ let zipped = last ? null : await compress(payload)
135
+ metric.sum(Metric.TotalBytes, zipped ? zipped.length : payload.length);
136
+ send(payload, zipped, envelope.data.sequence, last);
137
+
138
+ // Clear out events now that payload has been dispatched
139
+ analysis = [];
140
+ if (sendPlaybackBytes) {
141
+ playback = [];
142
+ playbackBytes = 0;
143
+ discoverBytes = 0;
144
+ }
145
+ }
146
+
147
+ function stringify(encoded: EncodedPayload): string {
148
+ return encoded.p.length > 0 ? `{"e":${encoded.e},"a":${encoded.a},"p":${encoded.p}}` : `{"e":${encoded.e},"a":${encoded.a}}`;
149
+ }
150
+
151
+ function send(payload: string, zipped: Uint8Array, sequence: number, beacon: boolean = false): void {
152
+ // Upload data if a valid URL is defined in the config
153
+ if (typeof config.upload === Constant.String) {
154
+ const url = config.upload as string;
155
+ let dispatched = false;
156
+
157
+ // If it's the last payload, attempt to upload using sendBeacon first.
158
+ // The advantage to using sendBeacon is that browser can decide to upload asynchronously, improving chances of success
159
+ // However, we don't want to rely on it for every payload, since we have no ability to retry if the upload failed.
160
+ // Also, in case of sendBeacon, we do not have a way to alter HTTP headers and therefore can't send compressed payload
161
+ if (beacon && "sendBeacon" in navigator) {
162
+ try {
163
+ // Navigator needs to be bound to sendBeacon before it is used to avoid errors in some browsers
164
+ dispatched = navigator.sendBeacon.bind(navigator)(url, payload);
165
+ if (dispatched) { done(sequence); }
166
+ } catch { /* do nothing - and we will automatically fallback to XHR below */ }
167
+ }
168
+
169
+ // Before initiating XHR upload, we check if the data has already been uploaded using sendBeacon
170
+ // There are two cases when dispatched could still be false:
171
+ // a) It's not the last payload, and therefore we didn't attempt sending sendBeacon
172
+ // b) It's the last payload, however, we failed to queue sendBeacon call and need to now fall back to XHR.
173
+ // E.g. if data is over 64KB, several user agents (like Chrome) will reject to queue the sendBeacon call.
174
+ if (dispatched === false) {
175
+ // While tracking payload for retry, we only track string value of the payload to err on the safe side
176
+ // Not all browsers support compression API and the support for it in supported browsers is still experimental
177
+ if (sequence in transit) { transit[sequence].attempts++; } else { transit[sequence] = { data: payload, attempts: 1 }; }
178
+ let xhr = new XMLHttpRequest();
179
+ xhr.open("POST", url, true);
180
+ xhr.timeout = Setting.UploadTimeout;
181
+ xhr.ontimeout = () => { report(new Error(`${Constant.Timeout} : ${url}`)) };
182
+ if (sequence !== null) { xhr.onreadystatechange = (): void => { measure(check)(xhr, sequence); }; }
183
+ xhr.withCredentials = true;
184
+ if (zipped) {
185
+ // If we do have valid compressed array, send it with appropriate HTTP headers so server can decode it appropriately
186
+ xhr.setRequestHeader(Constant.Accept, Constant.ClarityGzip);
187
+ xhr.send(zipped);
188
+ } else {
189
+ // In all other cases, continue sending string back to the server
190
+ xhr.send(payload);
191
+ }
192
+ }
193
+ } else if (config.upload) {
194
+ const callback = config.upload as UploadCallback;
195
+ callback(payload);
196
+ done(sequence);
197
+ }
198
+ }
199
+
200
+ function check(xhr: XMLHttpRequest, sequence: number): void {
201
+ var transitData = transit[sequence];
202
+ if (xhr && xhr.readyState === XMLReadyState.Done && transitData) {
203
+ // Attempt send payload again (as configured in settings) if we do not receive a success (2XX) response code back from the server
204
+ if ((xhr.status < 200 || xhr.status > 208) && transitData.attempts <= Setting.RetryLimit) {
205
+ // We re-attempt in all cases except when server explicitly rejects our request with 4XX error
206
+ if (xhr.status >= 400 && xhr.status < 500) {
207
+ // In case of a 4XX response from the server, we bail out instead of trying again
208
+ limit.trigger(Check.Server);
209
+ } else {
210
+ // Browser will send status = 0 when it refuses to put network request over the wire
211
+ // This could happen for several reasons, couple of known ones are:
212
+ // 1: Browsers block upload because of content security policy violation
213
+ // 2: Safari will terminate pending XHR requests with status code 0 if the user navigates away from the page
214
+ // In any case, we switch the upload URL to fallback configuration (if available) before re-trying one more time
215
+ if (xhr.status === 0) { config.upload = config.fallback ? config.fallback : config.upload; }
216
+ // In all other cases, re-attempt sending the same data
217
+ // For retry we always fallback to string payload, even though we may have attempted
218
+ // sending zipped payload earlier
219
+ send(transitData.data, null, sequence);
220
+ }
221
+ } else {
222
+ track = { sequence, attempts: transitData.attempts, status: xhr.status };
223
+ // Send back an event only if we were not successful in our first attempt
224
+ if (transitData.attempts > 1) { encode(Event.Upload); }
225
+ // Handle response if it was a 200 response with a valid body
226
+ if (xhr.status === 200 && xhr.responseText) { response(xhr.responseText); }
227
+ // If we exhausted our retries then trigger Clarity's shutdown for this page since the data will be incomplete
228
+ if (xhr.status === 0) {
229
+ // And, right before we terminate the session, we will attempt one last time to see if we can use
230
+ // different transport option (sendBeacon vs. XHR) to get this data to the server for analysis purposes
231
+ send(transitData.data, null, sequence, true);
232
+ limit.trigger(Check.Retry);
233
+ }
234
+ // Signal that this request completed successfully
235
+ if (xhr.status >= 200 && xhr.status <= 208) { done(sequence); }
236
+ // Stop tracking this payload now that it's all done
237
+ delete transit[sequence];
238
+ }
239
+ }
240
+ }
241
+
242
+ function done(sequence: number): void {
243
+ // If we everything went successfully, and it is the first sequence, save this session for future reference
244
+ if (sequence === 1) {
245
+ metadata.save();
246
+ metadata.callback();
247
+ }
248
+ }
249
+
250
+ function delay(): number {
251
+ // Progressively increase delay as we continue to send more payloads from the client to the server
252
+ // If we are not uploading data to a server, and instead invoking UploadCallback, in that case keep returning configured value
253
+ let gap = config.lean === false && discoverBytes > 0 ? Setting.MinUploadDelay : envelope.data.sequence * config.delay;
254
+ return typeof config.upload === Constant.String ? Math.max(Math.min(gap, Setting.MaxUploadDelay), Setting.MinUploadDelay) : config.delay;
255
+ }
256
+
257
+ function response(payload: string): void {
258
+ let lines = payload && payload.length > 0 ? payload.split("\n") : [];
259
+ for (var line of lines)
260
+ {
261
+ let parts = line && line.length > 0 ? line.split(/ (.*)/) : [Constant.Empty];
262
+ switch (parts[0]) {
263
+ case Constant.End:
264
+ // Clear out session storage and end the session so we can start fresh the next time
265
+ limit.trigger(Check.Server);
266
+ break;
267
+ case Constant.Upgrade:
268
+ // Upgrade current session to send back playback information
269
+ clarity.upgrade(Constant.Auto);
270
+ break;
271
+ case Constant.Action:
272
+ // Invoke action callback, if configured and has a valid value
273
+ if (config.action && parts.length > 1) { config.action(parts[1]); }
274
+ break;
275
+ case Constant.Extract:
276
+ if (parts.length > 1) { extract.trigger(parts[1]); }
277
+ break;
278
+ case Constant.Signal:
279
+ if (parts.length > 1) { signalsEvent(parts[1]); }
280
+ break;
281
+ }
282
+ }
283
+ }