@gemx-dev/clarity-js 0.8.39

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 (118) hide show
  1. package/README.md +1 -0
  2. package/build/clarity.extended.js +1 -0
  3. package/build/clarity.insight.js +1 -0
  4. package/build/clarity.js +6433 -0
  5. package/build/clarity.livechat.js +1 -0
  6. package/build/clarity.min.js +1 -0
  7. package/build/clarity.module.js +6429 -0
  8. package/build/clarity.performance.js +1 -0
  9. package/build/dynamic/clarity.crisp.js +1 -0
  10. package/build/dynamic/clarity.tidio.js +1 -0
  11. package/package.json +55 -0
  12. package/rollup.config.ts +161 -0
  13. package/src/clarity.ts +71 -0
  14. package/src/core/api.ts +8 -0
  15. package/src/core/config.ts +29 -0
  16. package/src/core/copy.ts +3 -0
  17. package/src/core/dynamic.ts +57 -0
  18. package/src/core/event.ts +53 -0
  19. package/src/core/hash.ts +19 -0
  20. package/src/core/history.ts +71 -0
  21. package/src/core/index.ts +81 -0
  22. package/src/core/measure.ts +19 -0
  23. package/src/core/report.ts +35 -0
  24. package/src/core/scrub.ts +202 -0
  25. package/src/core/task.ts +181 -0
  26. package/src/core/throttle.ts +46 -0
  27. package/src/core/time.ts +26 -0
  28. package/src/core/timeout.ts +10 -0
  29. package/src/core/version.ts +2 -0
  30. package/src/data/baseline.ts +162 -0
  31. package/src/data/compress.ts +31 -0
  32. package/src/data/consent.ts +75 -0
  33. package/src/data/custom.ts +23 -0
  34. package/src/data/dimension.ts +53 -0
  35. package/src/data/encode.ts +155 -0
  36. package/src/data/envelope.ts +53 -0
  37. package/src/data/extract.ts +211 -0
  38. package/src/data/index.ts +50 -0
  39. package/src/data/limit.ts +44 -0
  40. package/src/data/metadata.ts +408 -0
  41. package/src/data/metric.ts +51 -0
  42. package/src/data/ping.ts +36 -0
  43. package/src/data/signal.ts +30 -0
  44. package/src/data/summary.ts +34 -0
  45. package/src/data/token.ts +39 -0
  46. package/src/data/upgrade.ts +44 -0
  47. package/src/data/upload.ts +333 -0
  48. package/src/data/variable.ts +84 -0
  49. package/src/diagnostic/encode.ts +40 -0
  50. package/src/diagnostic/fraud.ts +37 -0
  51. package/src/diagnostic/index.ts +13 -0
  52. package/src/diagnostic/internal.ts +28 -0
  53. package/src/diagnostic/script.ts +35 -0
  54. package/src/dynamic/agent/blank.ts +2 -0
  55. package/src/dynamic/agent/crisp.ts +40 -0
  56. package/src/dynamic/agent/encode.ts +25 -0
  57. package/src/dynamic/agent/index.ts +8 -0
  58. package/src/dynamic/agent/livechat.ts +58 -0
  59. package/src/dynamic/agent/tidio.ts +44 -0
  60. package/src/global.ts +6 -0
  61. package/src/index.ts +9 -0
  62. package/src/insight/blank.ts +14 -0
  63. package/src/insight/encode.ts +61 -0
  64. package/src/insight/snapshot.ts +115 -0
  65. package/src/interaction/change.ts +38 -0
  66. package/src/interaction/click.ts +163 -0
  67. package/src/interaction/clipboard.ts +32 -0
  68. package/src/interaction/encode.ts +207 -0
  69. package/src/interaction/focus.ts +25 -0
  70. package/src/interaction/index.ts +60 -0
  71. package/src/interaction/input.ts +58 -0
  72. package/src/interaction/pointer.ts +137 -0
  73. package/src/interaction/resize.ts +50 -0
  74. package/src/interaction/scroll.ts +129 -0
  75. package/src/interaction/selection.ts +66 -0
  76. package/src/interaction/submit.ts +30 -0
  77. package/src/interaction/timeline.ts +69 -0
  78. package/src/interaction/unload.ts +26 -0
  79. package/src/interaction/visibility.ts +28 -0
  80. package/src/layout/animation.ts +133 -0
  81. package/src/layout/custom.ts +43 -0
  82. package/src/layout/discover.ts +31 -0
  83. package/src/layout/document.ts +46 -0
  84. package/src/layout/dom.ts +439 -0
  85. package/src/layout/encode.ts +154 -0
  86. package/src/layout/index.ts +42 -0
  87. package/src/layout/mutation.ts +412 -0
  88. package/src/layout/node.ts +294 -0
  89. package/src/layout/offset.ts +19 -0
  90. package/src/layout/region.ts +151 -0
  91. package/src/layout/schema.ts +63 -0
  92. package/src/layout/selector.ts +82 -0
  93. package/src/layout/style.ts +160 -0
  94. package/src/layout/target.ts +32 -0
  95. package/src/layout/traverse.ts +28 -0
  96. package/src/performance/blank.ts +10 -0
  97. package/src/performance/encode.ts +31 -0
  98. package/src/performance/index.ts +12 -0
  99. package/src/performance/interaction.ts +125 -0
  100. package/src/performance/navigation.ts +31 -0
  101. package/src/performance/observer.ts +112 -0
  102. package/src/queue.ts +33 -0
  103. package/test/core.test.ts +139 -0
  104. package/test/helper.ts +167 -0
  105. package/test/html/core.html +34 -0
  106. package/test/stub.test.ts +7 -0
  107. package/test/tsconfig.test.json +6 -0
  108. package/tsconfig.json +21 -0
  109. package/tslint.json +33 -0
  110. package/types/agent.d.ts +39 -0
  111. package/types/core.d.ts +150 -0
  112. package/types/data.d.ts +568 -0
  113. package/types/diagnostic.d.ts +24 -0
  114. package/types/global.d.ts +30 -0
  115. package/types/index.d.ts +40 -0
  116. package/types/interaction.d.ts +174 -0
  117. package/types/layout.d.ts +277 -0
  118. package/types/performance.d.ts +31 -0
@@ -0,0 +1,333 @@
1
+ import { UploadCallback } from "@clarity-types/core";
2
+ import { BooleanFlag, Check, Code, Constant, EncodedPayload, Event, Metric, Setting, Severity, 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 internal from "@src/diagnostic/internal";
17
+ import * as timeline from "@src/interaction/timeline";
18
+ import * as region from "@src/layout/region";
19
+ import * as extract from "@src/data/extract";
20
+ import * as style from "@src/layout/style";
21
+ import { report } from "@src/core/report";
22
+ import { signalsEvent } from "@src/data/signal";
23
+ import { snapshot } from "@src/insight/snapshot";
24
+ import * as dynamic from "@src/core/dynamic";
25
+
26
+ let discoverBytes: number = 0;
27
+ let playbackBytes: number = 0;
28
+ let playback: string[];
29
+ let analysis: string[];
30
+ let timeout: number = null;
31
+ let transit: Transit;
32
+ let active: boolean;
33
+ let queuedTime: number = 0;
34
+ let leanLimit = false;
35
+ export let track: UploadData;
36
+
37
+ export function start(): void {
38
+ active = true;
39
+ discoverBytes = 0;
40
+ playbackBytes = 0;
41
+ leanLimit = false;
42
+ queuedTime = 0;
43
+ playback = [];
44
+ analysis = [];
45
+ transit = {};
46
+ track = null;
47
+ }
48
+
49
+ export function queue(tokens: Token[], transmit: boolean = true): void {
50
+ if (!active) {
51
+ return;
52
+ }
53
+
54
+ let now = time();
55
+ let type = tokens.length > 1 ? tokens[1] : null;
56
+ let event = JSON.stringify(tokens);
57
+
58
+ if (!config.lean) {
59
+ leanLimit = false;
60
+ } else if (!leanLimit && playbackBytes + event.length > Setting.PlaybackBytesLimit) {
61
+ internal.log(Code.LeanLimit, Severity.Info);
62
+ leanLimit = true;
63
+ }
64
+
65
+ switch (type) {
66
+ case Event.Discover:
67
+ if (leanLimit) { break; }
68
+ discoverBytes += event.length;
69
+ case Event.Box:
70
+ case Event.Mutation:
71
+ case Event.Snapshot:
72
+ case Event.StyleSheetAdoption:
73
+ case Event.StyleSheetUpdate:
74
+ case Event.Animation:
75
+ case Event.CustomElement:
76
+ if (leanLimit) { break; }
77
+ playbackBytes += event.length;
78
+ playback.push(event);
79
+ break;
80
+ default:
81
+ analysis.push(event);
82
+ break;
83
+ }
84
+
85
+ // Increment event count metric
86
+ metric.count(Metric.EventCount);
87
+
88
+ // Following two checks are precautionary and act as a fail safe mechanism to get out of unexpected situations.
89
+ // Check 1: If for any reason the upload hasn't happened after waiting for 2x the config.delay time,
90
+ // reset the timer. This allows Clarity to attempt an upload again.
91
+ let gap = delay();
92
+ if (now - queuedTime > (gap * 2)) {
93
+ clearTimeout(timeout);
94
+ timeout = null;
95
+ }
96
+
97
+ // Transmit Check: When transmit is set to true (default), it indicates that we should schedule an upload
98
+ // However, in certain scenarios - like metric calculation - which are triggered as part of an existing upload
99
+ // We enrich the data going out with the existing upload. In these cases, call to upload comes with 'transmit' set to false.
100
+ if (transmit && timeout === null) {
101
+ if (type !== Event.Ping) { ping.reset(); }
102
+ timeout = setTimeout(upload, gap);
103
+ queuedTime = now;
104
+ limit.check(playbackBytes);
105
+ }
106
+ }
107
+
108
+ export function stop(): void {
109
+ clearTimeout(timeout);
110
+ upload(true);
111
+ discoverBytes = 0;
112
+ playbackBytes = 0;
113
+ leanLimit = false;
114
+ queuedTime = 0;
115
+ playback = [];
116
+ analysis = [];
117
+ transit = {};
118
+ track = null;
119
+ active = false;
120
+ }
121
+
122
+ async function upload(final: boolean = false): Promise<void> {
123
+ if (!active) {
124
+ return;
125
+ }
126
+
127
+ timeout = null;
128
+
129
+ // Check if we can send playback bytes over the wire or not
130
+ // For better instrumentation coverage, we send playback bytes from second sequence onwards
131
+ // And, we only send playback metric when we are able to send the playback bytes back to server
132
+ let sendPlaybackBytes = config.lean === false && playbackBytes > 0 && (playbackBytes < Setting.MaxFirstPayloadBytes || envelope.data.sequence > 0);
133
+ if (sendPlaybackBytes) { metric.max(Metric.Playback, BooleanFlag.True); }
134
+
135
+ // CAUTION: Ensure "transmit" is set to false in the queue function for following events
136
+ // Otherwise you run a risk of infinite loop.
137
+ region.compute();
138
+ timeline.compute();
139
+ data.compute();
140
+ style.compute();
141
+
142
+ // Treat this as the last payload only if final boolean was explicitly set to true.
143
+ // In real world tests, we noticed that certain third party scripts (e.g. https://www.npmjs.com/package/raven-js)
144
+ // could inject function arguments for internal tracking (likely stack traces for script errors).
145
+ // For these edge cases, we want to ensure that an injected object (e.g. {"key": "value"}) isn't mistaken to be true.
146
+ let last = final === true;
147
+
148
+ // In some cases envelope has null data because it's part of the shutdown process while there's one upload call queued which might introduce runtime error
149
+ if(!envelope.data) return;
150
+
151
+ let e = JSON.stringify(envelope.envelope(last));
152
+ let a = `[${analysis.join()}]`;
153
+
154
+ let p = sendPlaybackBytes ? `[${playback.join()}]` : Constant.Empty;
155
+
156
+ // For final (beacon) payloads, If size is too large, we need to remove playback data
157
+ if (last && p.length > 0 && (e.length + a.length + p.length > Setting.MaxBeaconPayloadBytes)) {
158
+ p = Constant.Empty;
159
+ }
160
+
161
+ let encoded: EncodedPayload = {e, a, p};
162
+
163
+ // Get the payload ready for sending over the wire
164
+ // We also attempt to compress the payload if it is not the last payload and the browser supports it
165
+ // In all other cases, we continue to send back string value
166
+ let payload = stringify(encoded);
167
+ let zipped = last ? null : await compress(payload);
168
+ metric.sum(Metric.TotalBytes, zipped ? zipped.length : payload.length);
169
+ send(payload, zipped, envelope.data.sequence, last);
170
+
171
+ // Clear out events now that payload has been dispatched
172
+ analysis = [];
173
+ if (sendPlaybackBytes) {
174
+ playback = [];
175
+ playbackBytes = 0;
176
+ discoverBytes = 0;
177
+ leanLimit = false;
178
+ }
179
+ }
180
+
181
+ function stringify(encoded: EncodedPayload): string {
182
+ return encoded.p.length > 0 ? `{"e":${encoded.e},"a":${encoded.a},"p":${encoded.p}}` : `{"e":${encoded.e},"a":${encoded.a}}`;
183
+ }
184
+
185
+ function send(payload: string, zipped: Uint8Array, sequence: number, beacon: boolean = false): void {
186
+ // Upload data if a valid URL is defined in the config
187
+ if (typeof config.upload === Constant.String) {
188
+ const url = config.upload as string;
189
+ let dispatched = false;
190
+
191
+ // If it's the last payload, attempt to upload using sendBeacon first.
192
+ // The advantage to using sendBeacon is that browser can decide to upload asynchronously, improving chances of success
193
+ // However, we don't want to rely on it for every payload, since we have no ability to retry if the upload failed.
194
+ // Also, in case of sendBeacon, we do not have a way to alter HTTP headers and therefore can't send compressed payload
195
+ if (beacon && navigator && navigator["sendBeacon"]) {
196
+ try {
197
+ // Navigator needs to be bound to sendBeacon before it is used to avoid errors in some browsers
198
+ dispatched = navigator.sendBeacon.bind(navigator)(url, payload);
199
+ if (dispatched) {
200
+ done(sequence);
201
+ }
202
+ } catch(error) {
203
+ // If sendBeacon fails, we do nothing and continue with XHR upload
204
+ }
205
+ }
206
+
207
+ // Before initiating XHR upload, we check if the data has already been uploaded using sendBeacon
208
+ // There are two cases when dispatched could still be false:
209
+ // a) It's not the last payload, and therefore we didn't attempt sending sendBeacon
210
+ // b) It's the last payload, however, we failed to queue sendBeacon call and need to now fall back to XHR.
211
+ // E.g. if data is over 64KB, several user agents (like Chrome) will reject to queue the sendBeacon call.
212
+ if (dispatched === false) {
213
+ // While tracking payload for retry, we only track string value of the payload to err on the safe side
214
+ // Not all browsers support compression API and the support for it in supported browsers is still experimental
215
+ if (sequence in transit) { transit[sequence].attempts++; } else { transit[sequence] = { data: payload, attempts: 1 }; }
216
+ let xhr = new XMLHttpRequest();
217
+ xhr.open("POST", url, true);
218
+ xhr.timeout = Setting.UploadTimeout;
219
+ xhr.ontimeout = () => { report(new Error(`${Constant.Timeout} : ${url}`)) };
220
+ if (sequence !== null) { xhr.onreadystatechange = (): void => { measure(check)(xhr, sequence); }; }
221
+ xhr.withCredentials = true;
222
+ if (zipped) {
223
+ // If we do have valid compressed array, send it with appropriate HTTP headers so server can decode it appropriately
224
+ xhr.setRequestHeader(Constant.Accept, Constant.ClarityGzip);
225
+ xhr.send(zipped);
226
+ } else {
227
+ // In all other cases, continue sending string back to the server
228
+ xhr.send(payload);
229
+ }
230
+ }
231
+ } else if (config.upload) {
232
+ const callback = config.upload as UploadCallback;
233
+ callback(payload);
234
+ done(sequence);
235
+ }
236
+ }
237
+
238
+ function check(xhr: XMLHttpRequest, sequence: number): void {
239
+ var transitData = transit[sequence];
240
+ if (xhr && xhr.readyState === XMLReadyState.Done && transitData) {
241
+ // Attempt send payload again (as configured in settings) if we do not receive a success (2XX) response code back from the server
242
+ if ((xhr.status < 200 || xhr.status > 208) && transitData.attempts <= Setting.RetryLimit) {
243
+ // We re-attempt in all cases except when server explicitly rejects our request with 4XX error
244
+ if (xhr.status >= 400 && xhr.status < 500) {
245
+ // In case of a 4XX response from the server, we bail out instead of trying again
246
+ limit.trigger(Check.Server);
247
+ } else {
248
+ // Browser will send status = 0 when it refuses to put network request over the wire
249
+ // This could happen for several reasons, couple of known ones are:
250
+ // 1: Browsers block upload because of content security policy violation
251
+ // 2: Safari will terminate pending XHR requests with status code 0 if the user navigates away from the page
252
+ // In any case, we switch the upload URL to fallback configuration (if available) before re-trying one more time
253
+ if (xhr.status === 0) { config.upload = config.fallback ? config.fallback : config.upload; }
254
+ // Capture the status code and number of attempts so we can report it back to the server
255
+ track = { sequence, attempts: transitData.attempts, status: xhr.status };
256
+ encode(Event.Upload);
257
+ // In all other cases, re-attempt sending the same data
258
+ // For retry we always fallback to string payload, even though we may have attempted
259
+ // sending zipped payload earlier
260
+ send(transitData.data, null, sequence);
261
+ }
262
+ } else {
263
+ track = { sequence, attempts: transitData.attempts, status: xhr.status };
264
+ // Send back an event only if we were not successful in our first attempt
265
+ if (transitData.attempts > 1) { encode(Event.Upload); }
266
+ // Handle response if it was a 200 response with a valid body
267
+ if (xhr.status === 200 && xhr.responseText) { response(xhr.responseText); }
268
+ // If we exhausted our retries then trigger Clarity's shutdown for this page since the data will be incomplete
269
+ if (xhr.status === 0) {
270
+ // And, right before we terminate the session, we will attempt one last time to see if we can use
271
+ // different transport option (sendBeacon vs. XHR) to get this data to the server for analysis purposes
272
+ send(transitData.data, null, sequence, true);
273
+ limit.trigger(Check.Retry);
274
+ }
275
+ // Signal that this request completed successfully
276
+ if (xhr.status >= 200 && xhr.status <= 208) { done(sequence); }
277
+ // Stop tracking this payload now that it's all done
278
+ delete transit[sequence];
279
+ }
280
+ }
281
+ }
282
+
283
+ function done(sequence: number): void {
284
+ // If we everything went successfully, and it is the first sequence, save this session for future reference
285
+ if (sequence === 1) {
286
+ metadata.save();
287
+ metadata.callback();
288
+ }
289
+ }
290
+
291
+ function delay(): number {
292
+ // Progressively increase delay as we continue to send more payloads from the client to the server
293
+ // If we are not uploading data to a server, and instead invoking UploadCallback, in that case keep returning configured value
294
+ let gap = config.lean === false && discoverBytes > 0 ? Setting.MinUploadDelay : envelope.data.sequence * config.delay;
295
+ return typeof config.upload === Constant.String ? Math.max(Math.min(gap, Setting.MaxUploadDelay), Setting.MinUploadDelay) : config.delay;
296
+ }
297
+
298
+ function response(payload: string): void {
299
+ let lines = payload && payload.length > 0 ? payload.split("\n") : [];
300
+ for (var line of lines)
301
+ {
302
+ let parts = line && line.length > 0 ? line.split(/ (.*)/) : [Constant.Empty];
303
+ switch (parts[0]) {
304
+ case Constant.End:
305
+ // Clear out session storage and end the session so we can start fresh the next time
306
+ limit.trigger(Check.Server);
307
+ break;
308
+ case Constant.Upgrade:
309
+ // Upgrade current session to send back playback information
310
+ clarity.upgrade(Constant.Auto);
311
+ break;
312
+ case Constant.Action:
313
+ // Invoke action callback, if configured and has a valid value
314
+ if (config.action && parts.length > 1) { config.action(parts[1]); }
315
+ break;
316
+ case Constant.Extract:
317
+ if (parts.length > 1) { extract.trigger(parts[1]); }
318
+ break;
319
+ case Constant.Signal:
320
+ if (parts.length > 1) { signalsEvent(parts[1]); }
321
+ break;
322
+ case Constant.Module:
323
+ if (parts.length > 1) {
324
+ dynamic.event(parts[1]);
325
+ }
326
+ break;
327
+ case Constant.Snapshot:
328
+ config.lean = false; // Disable lean mode to ensure we can send playback information to server.
329
+ snapshot();
330
+ break;
331
+ }
332
+ }
333
+ }
@@ -0,0 +1,84 @@
1
+ import { Constant, Event, IdentityData, Setting, VariableData } from "@clarity-types/data";
2
+ import * as core from "@src/core";
3
+ import { scrub } from "@src/core/scrub";
4
+ import encode from "./encode";
5
+
6
+ export let data: VariableData = null;
7
+
8
+ export function start(): void {
9
+ reset();
10
+ }
11
+
12
+ export function set(variable: string, value: string | string[]): void {
13
+ let values = typeof value === Constant.String ? [value as string] : value as string[];
14
+ log(variable, values);
15
+ }
16
+
17
+ export async function identify(userId: string, sessionId: string = null, pageId: string = null, userHint: string = null): Promise<IdentityData> {
18
+ let output: IdentityData = { userId: await sha256(userId), userHint: userHint || redact(userId) };
19
+
20
+ // By default, hash custom userId using SHA256 algorithm on the client to preserve privacy
21
+ log(Constant.UserId, [output.userId]);
22
+
23
+ // Optional non-identifying name for the user
24
+ // If name is not explicitly provided, we automatically generate a redacted version of the userId
25
+ log(Constant.UserHint, [output.userHint]);
26
+ log(Constant.UserType, [detect(userId)]);
27
+
28
+ // Log sessionId and pageId if provided
29
+ if (sessionId) {
30
+ log(Constant.SessionId, [sessionId]);
31
+ output.sessionId = sessionId;
32
+ }
33
+ if (pageId) {
34
+ log(Constant.PageId, [pageId]);
35
+ output.pageId = pageId;
36
+ }
37
+
38
+ return output;
39
+ }
40
+
41
+ function log(variable: string, value: string[]): void {
42
+ if (core.active() &&
43
+ variable &&
44
+ value &&
45
+ typeof variable === Constant.String &&
46
+ variable.length < 255) {
47
+ let validValues = variable in data ? data[variable] : [];
48
+ for (let i = 0; i < value.length; i++) {
49
+ if (typeof value[i] === Constant.String && value[i].length < 255) { validValues.push(value[i]); }
50
+ }
51
+ data[variable] = validValues;
52
+ }
53
+ }
54
+
55
+ export function compute(): void {
56
+ encode(Event.Variable);
57
+ }
58
+
59
+ export function reset(): void {
60
+ data = {};
61
+ }
62
+
63
+ export function stop(): void {
64
+ reset();
65
+ }
66
+
67
+ function redact(input: string): string {
68
+ return input && input.length >= Setting.WordLength ?
69
+ `${input.substring(0,2)}${scrub(input.substring(2), Constant.Asterix, Constant.Asterix)}` : scrub(input, Constant.Asterix, Constant.Asterix);
70
+ }
71
+
72
+ async function sha256(input: string): Promise<string> {
73
+ try {
74
+ if (crypto && input) {
75
+ // Reference: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#converting_a_digest_to_a_hex_string
76
+ const buffer = await crypto.subtle.digest(Constant.SHA256, new TextEncoder().encode(input));
77
+ return Array.prototype.map.call(new Uint8Array(buffer), (x: any) =>(('00'+x.toString(16)).slice(-2))).join('');
78
+ } else { return Constant.Empty; }
79
+ } catch { return Constant.Empty; }
80
+ }
81
+
82
+ function detect(input: string): string {
83
+ return input && input.indexOf(Constant.At) > 0 ? Constant.Email : Constant.String;
84
+ }
@@ -0,0 +1,40 @@
1
+ import { Event, Token } from "@clarity-types/data";
2
+ import * as scrub from "@src/core/scrub";
3
+ import { time } from "@src/core/time";
4
+ import { queue } from "@src/data/upload";
5
+ import * as fraud from "@src/diagnostic/fraud";
6
+ import * as internal from "@src/diagnostic/internal";
7
+ import * as script from "@src/diagnostic/script";
8
+
9
+ export default async function (type: Event): Promise<void> {
10
+ let tokens: Token[] = [time(), type];
11
+
12
+ switch (type) {
13
+ case Event.ScriptError:
14
+ tokens.push(script.data.message);
15
+ tokens.push(script.data.line);
16
+ tokens.push(script.data.column);
17
+ tokens.push(script.data.stack);
18
+ tokens.push(scrub.url(script.data.source));
19
+ queue(tokens);
20
+ break;
21
+ case Event.Log:
22
+ if (internal.data) {
23
+ tokens.push(internal.data.code);
24
+ tokens.push(internal.data.name);
25
+ tokens.push(internal.data.message);
26
+ tokens.push(internal.data.stack);
27
+ tokens.push(internal.data.severity);
28
+ queue(tokens, false);
29
+ }
30
+ break;
31
+ case Event.Fraud:
32
+ if (fraud.data) {
33
+ tokens.push(fraud.data.id);
34
+ tokens.push(fraud.data.target);
35
+ tokens.push(fraud.data.checksum);
36
+ queue(tokens, false);
37
+ }
38
+ break;
39
+ }
40
+ }
@@ -0,0 +1,37 @@
1
+ import { BooleanFlag, Event, IframeStatus, Metric, Setting } from "@clarity-types/data";
2
+ import { FraudData } from "@clarity-types/diagnostic";
3
+ import config from "@src/core/config";
4
+ import hash from "@src/core/hash";
5
+ import * as metric from "@src/data/metric";
6
+ import encode from "./encode";
7
+
8
+ let history = [];
9
+ export let data: FraudData;
10
+
11
+ export function start(): void {
12
+ history = [];
13
+ metric.max(Metric.Automation, navigator.webdriver ? BooleanFlag.True : BooleanFlag.False);
14
+ try {
15
+ // some sites (unintentionally) overwrite the window.self property, so we also check for the main window object
16
+ metric.max(Metric.Iframed, window.top == window.self || window.top == window ? IframeStatus.TopFrame : IframeStatus.Iframe);
17
+ } catch (ex) {
18
+ metric.max(Metric.Iframed, IframeStatus.Unknown);
19
+ }
20
+
21
+ }
22
+
23
+ export function check(id: number, target: number, input: string): void {
24
+ // Compute hash for fraud detection, if enabled. Hash is computed only if input meets the minimum length criteria
25
+ if (config.fraud && id !== null && input && input.length >= Setting.WordLength) {
26
+ data = { id, target, checksum: hash(input, Setting.ChecksumPrecision) };
27
+ // Only encode this event if we haven't already reported this hash
28
+ if (history.indexOf(data.checksum) < 0) {
29
+ history.push(data.checksum);
30
+ encode(Event.Fraud);
31
+ }
32
+ }
33
+ }
34
+
35
+ export function stop(): void {
36
+ history = [];
37
+ }
@@ -0,0 +1,13 @@
1
+ import * as fraud from "@src/diagnostic/fraud";
2
+ import * as internal from "@src/diagnostic/internal";
3
+ import * as script from "@src/diagnostic/script";
4
+
5
+ export function start(): void {
6
+ fraud.start();
7
+ script.start();
8
+ internal.start();
9
+ }
10
+
11
+ export function stop(): void {
12
+ internal.stop();
13
+ }
@@ -0,0 +1,28 @@
1
+ import { Code, Event, Severity } from "@clarity-types/data";
2
+ import { LogData } from "@clarity-types/diagnostic";
3
+ import encode from "./encode";
4
+
5
+ let history: { [key: number]: string[] } = {};
6
+ export let data: LogData;
7
+
8
+ export function start(): void {
9
+ history = {};
10
+ }
11
+
12
+ export function log(code: Code, severity: Severity, name: string = null, message: string = null, stack: string = null): void {
13
+ let key = name ? `${name}|${message}`: "";
14
+ // While rare, it's possible for code to fail repeatedly during the lifetime of the same page
15
+ // In those cases, we only want to log the failure once and not spam logs with redundant information.
16
+ if (code in history && history[code].indexOf(key) >= 0) { return; }
17
+
18
+ data = { code, name, message, stack, severity };
19
+
20
+ // Maintain history of errors in memory to avoid sending redundant information
21
+ if (code in history) { history[code].push(key); } else { history[code] = [key]; }
22
+
23
+ encode(Event.Log);
24
+ }
25
+
26
+ export function stop(): void {
27
+ history = {};
28
+ }
@@ -0,0 +1,35 @@
1
+ import { Event, Setting } from "@clarity-types/data";
2
+ import { ScriptErrorData } from "@clarity-types/diagnostic";
3
+ import { bind } from "@src/core/event";
4
+ import encode from "./encode";
5
+
6
+ let history: { [key: string]: number } = {};
7
+ export let data: ScriptErrorData;
8
+
9
+ export function start(): void {
10
+ bind(window, "error", handler);
11
+ history = {};
12
+ }
13
+
14
+ function handler(error: ErrorEvent): boolean {
15
+ let e = error["error"] || error;
16
+ // While rare, it's possible for code to fail repeatedly during the lifetime of the same page
17
+ // In those cases, we only want to log the failure first few times and not spam logs with redundant information.
18
+ if (!(e.message in history)) { history[e.message] = 0; }
19
+ if (history[e.message]++ >= Setting.ScriptErrorLimit) { return true; }
20
+
21
+ // Send back information only if the handled error has valid information
22
+ if (e && e.message) {
23
+ data = {
24
+ message: e.message,
25
+ line: error["lineno"],
26
+ column: error["colno"],
27
+ stack: e.stack,
28
+ source: error["filename"]
29
+ };
30
+
31
+ encode(Event.ScriptError);
32
+ }
33
+
34
+ return true;
35
+ }
@@ -0,0 +1,2 @@
1
+ export function start(): void {}
2
+ export function stop(): void {}
@@ -0,0 +1,40 @@
1
+ import { Action } from "@clarity-types/agent";
2
+ import encode from "./encode";
3
+
4
+ function open() {
5
+ encode(Action.AgentMaximized);
6
+ }
7
+
8
+ function close() {
9
+ encode(Action.AgentMinimized);
10
+ }
11
+
12
+ function human() {
13
+ encode(Action.HumanMessage);
14
+ }
15
+
16
+ function agent() {
17
+ encode(Action.AgentMessage);
18
+ }
19
+
20
+ export function start(): void {
21
+ if (window.$crisp) {
22
+ window.$crisp.push(["on", "chat:opened", open]);
23
+ window.$crisp.push(["on", "chat:closed", close]);
24
+ window.$crisp.push(["on", "message:sent", human]);
25
+ window.$crisp.push(["on", "message:received", agent]);
26
+ }
27
+ // Register stop callback with main Clarity
28
+ if (typeof window !== "undefined" && (window as any).clarity) {
29
+ (window as any).clarity("register", stop);
30
+ }
31
+ }
32
+
33
+ export function stop(): void {
34
+ if (window.$crisp) {
35
+ window.$crisp.push(["off", "chat:opened", open]);
36
+ window.$crisp.push(["off", "chat:closed", close]);
37
+ window.$crisp.push(["off", "message:sent", human]);
38
+ window.$crisp.push(["off", "message:received", agent]);
39
+ }
40
+ }
@@ -0,0 +1,25 @@
1
+ import { Event, Token } from "@clarity-types/data";
2
+ import { Action } from "@clarity-types/agent";
3
+
4
+ export default function (event: Action): void {
5
+ const t = (window as any).clarity("time");
6
+ let tokens: Token[] = [t, Event.Chat];
7
+ switch (event) {
8
+ case Action.AgentOnline:
9
+ case Action.AgentOffline:
10
+ case Action.AgentHidden:
11
+ case Action.AgentMaximized:
12
+ case Action.AgentMinimized:
13
+ case Action.AgentMessage:
14
+ case Action.HumanMessage:
15
+ tokens.push(event);
16
+ break;
17
+ }
18
+ queueTokens(tokens);
19
+ }
20
+
21
+ function queueTokens(tokens: Token[]) {
22
+ if (typeof window !== "undefined" && (window as any).clarity) {
23
+ (window as any).clarity("queue", tokens);
24
+ }
25
+ }
@@ -0,0 +1,8 @@
1
+ import * as livechat from "@src/dynamic/agent/livechat";
2
+ import * as tidio from "@src/dynamic/agent/tidio";
3
+ import * as crisp from "@src/dynamic/agent/crisp";
4
+ (function () {
5
+ livechat.start();
6
+ tidio.start();
7
+ crisp.start();
8
+ })();