@gem-sdk/clarity-js 0.8.94

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