clarity-js 0.8.42 → 0.8.43

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 (114) 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 +6043 -6030
  5. package/build/clarity.min.js +1 -1
  6. package/build/clarity.module.js +6043 -6030
  7. package/build/clarity.performance.js +1 -1
  8. package/package.json +70 -70
  9. package/rollup.config.ts +161 -161
  10. package/src/clarity.ts +65 -65
  11. package/src/core/api.ts +8 -8
  12. package/src/core/config.ts +29 -29
  13. package/src/core/copy.ts +3 -3
  14. package/src/core/dynamic.ts +13 -7
  15. package/src/core/event.ts +53 -53
  16. package/src/core/hash.ts +19 -19
  17. package/src/core/history.ts +71 -71
  18. package/src/core/index.ts +81 -81
  19. package/src/core/measure.ts +19 -19
  20. package/src/core/report.ts +28 -28
  21. package/src/core/scrub.ts +204 -202
  22. package/src/core/task.ts +181 -181
  23. package/src/core/throttle.ts +46 -46
  24. package/src/core/time.ts +26 -26
  25. package/src/core/timeout.ts +10 -10
  26. package/src/core/version.ts +2 -2
  27. package/src/data/baseline.ts +162 -162
  28. package/src/data/compress.ts +31 -31
  29. package/src/data/consent.ts +77 -77
  30. package/src/data/custom.ts +23 -23
  31. package/src/data/dimension.ts +53 -53
  32. package/src/data/encode.ts +155 -155
  33. package/src/data/envelope.ts +53 -53
  34. package/src/data/extract.ts +211 -211
  35. package/src/data/index.ts +50 -50
  36. package/src/data/limit.ts +44 -44
  37. package/src/data/metadata.ts +411 -408
  38. package/src/data/metric.ts +51 -51
  39. package/src/data/ping.ts +36 -36
  40. package/src/data/signal.ts +30 -30
  41. package/src/data/summary.ts +34 -34
  42. package/src/data/token.ts +39 -39
  43. package/src/data/upgrade.ts +44 -44
  44. package/src/data/upload.ts +333 -333
  45. package/src/data/variable.ts +83 -83
  46. package/src/diagnostic/encode.ts +40 -40
  47. package/src/diagnostic/fraud.ts +36 -36
  48. package/src/diagnostic/index.ts +13 -13
  49. package/src/diagnostic/internal.ts +28 -28
  50. package/src/diagnostic/script.ts +35 -35
  51. package/src/dynamic/agent/blank.ts +2 -2
  52. package/src/dynamic/agent/crisp.ts +40 -40
  53. package/src/dynamic/agent/encode.ts +25 -25
  54. package/src/dynamic/agent/index.ts +8 -8
  55. package/src/dynamic/agent/livechat.ts +58 -58
  56. package/src/dynamic/agent/tidio.ts +44 -44
  57. package/src/global.ts +6 -6
  58. package/src/index.ts +9 -9
  59. package/src/insight/blank.ts +14 -14
  60. package/src/insight/encode.ts +60 -60
  61. package/src/insight/snapshot.ts +114 -114
  62. package/src/interaction/change.ts +38 -38
  63. package/src/interaction/click.ts +173 -173
  64. package/src/interaction/clipboard.ts +32 -32
  65. package/src/interaction/encode.ts +210 -210
  66. package/src/interaction/index.ts +60 -60
  67. package/src/interaction/input.ts +57 -57
  68. package/src/interaction/pointer.ts +137 -137
  69. package/src/interaction/resize.ts +50 -50
  70. package/src/interaction/scroll.ts +129 -129
  71. package/src/interaction/selection.ts +66 -66
  72. package/src/interaction/submit.ts +30 -30
  73. package/src/interaction/timeline.ts +69 -69
  74. package/src/interaction/unload.ts +26 -26
  75. package/src/interaction/visibility.ts +27 -27
  76. package/src/layout/animation.ts +133 -133
  77. package/src/layout/custom.ts +42 -42
  78. package/src/layout/discover.ts +31 -31
  79. package/src/layout/document.ts +46 -46
  80. package/src/layout/dom.ts +439 -439
  81. package/src/layout/encode.ts +154 -154
  82. package/src/layout/index.ts +42 -42
  83. package/src/layout/mutation.ts +411 -411
  84. package/src/layout/node.ts +294 -294
  85. package/src/layout/offset.ts +19 -19
  86. package/src/layout/region.ts +151 -151
  87. package/src/layout/schema.ts +63 -63
  88. package/src/layout/selector.ts +82 -82
  89. package/src/layout/style.ts +159 -159
  90. package/src/layout/target.ts +32 -32
  91. package/src/layout/traverse.ts +27 -27
  92. package/src/performance/blank.ts +9 -9
  93. package/src/performance/encode.ts +31 -31
  94. package/src/performance/index.ts +12 -12
  95. package/src/performance/interaction.ts +125 -125
  96. package/src/performance/navigation.ts +31 -31
  97. package/src/performance/observer.ts +112 -112
  98. package/src/queue.ts +33 -33
  99. package/test/core.test.ts +139 -139
  100. package/test/helper.ts +162 -162
  101. package/test/html/core.html +27 -27
  102. package/test/stub.test.ts +7 -7
  103. package/test/tsconfig.test.json +5 -5
  104. package/tsconfig.json +21 -21
  105. package/tslint.json +32 -32
  106. package/types/agent.d.ts +39 -39
  107. package/types/core.d.ts +150 -150
  108. package/types/data.d.ts +572 -571
  109. package/types/diagnostic.d.ts +24 -24
  110. package/types/global.d.ts +30 -30
  111. package/types/index.d.ts +40 -40
  112. package/types/interaction.d.ts +177 -177
  113. package/types/layout.d.ts +276 -276
  114. package/types/performance.d.ts +31 -31
package/src/core/task.ts CHANGED
@@ -1,181 +1,181 @@
1
- import { AsyncTask, Priority, RequestIdleCallbackDeadline, RequestIdleCallbackOptions, Task, Timer } from "@clarity-types/core";
2
- import { TaskFunction, TaskResolve, Tasks } from "@clarity-types/core";
3
- import { Code, Metric, Setting, Severity } from "@clarity-types/data";
4
- import * as metadata from "@src/data/metadata";
5
- import * as metric from "@src/data/metric";
6
- import * as internal from "@src/diagnostic/internal";
7
-
8
- // Track the start time to be able to compute duration at the end of the task
9
- const idleTimeout = 5000;
10
- let tracker: Tasks = {};
11
- let queuedTasks: AsyncTask[] = [];
12
- let activeTask: AsyncTask = null;
13
- let pauseTask: Promise<void> = null;
14
- let resumeResolve: TaskResolve = null;
15
-
16
- export function pause(): void {
17
- if (pauseTask === null) {
18
- pauseTask = new Promise<void>((resolve: TaskResolve): void => {
19
- resumeResolve = resolve;
20
- });
21
- }
22
- }
23
-
24
- export function resume(): void {
25
- if (pauseTask) {
26
- resumeResolve();
27
- pauseTask = null;
28
- if (activeTask === null) { run(); }
29
- }
30
- }
31
-
32
- export function reset(): void {
33
- tracker = {};
34
- queuedTasks = [];
35
- activeTask = null;
36
- pauseTask = null;
37
- }
38
-
39
- export async function schedule(task: TaskFunction, priority: Priority = Priority.Normal): Promise<void> {
40
- // If this task is already scheduled, skip it
41
- for (let q of queuedTasks) {
42
- if (q.task === task) {
43
- return;
44
- }
45
- }
46
-
47
- let promise = new Promise<void>((resolve: TaskResolve): void => {
48
- let insert = priority === Priority.High ? "unshift" : "push";
49
- // Queue this task for asynchronous execution later
50
- // We also store a unique page identifier (id) along with the task to ensure
51
- // ensure that we do not accidentally execute this task in context of a different page
52
- queuedTasks[insert]({ task, resolve, id: metadata.id() });
53
- });
54
-
55
- // If there is no active task running, and Clarity is not in pause state,
56
- // invoke the first task in the queue synchronously. This ensures that we don't yield the thread during unload event
57
- if (activeTask === null && pauseTask === null) { run(); }
58
-
59
- return promise;
60
- }
61
-
62
- function run(): void {
63
- let entry = queuedTasks.shift();
64
- if (entry) {
65
- activeTask = entry;
66
- entry.task().then((): void => {
67
- // Bail out if the context in which this task was operating is different from the current page
68
- // An example scenario where task could span across pages is Single Page Applications (SPA)
69
- // A task that started on page #1, but completes on page #2
70
- if (entry.id !== metadata.id()) { return; }
71
- entry.resolve();
72
- activeTask = null; // Reset active task back to null now that the promise is resolved
73
- run();
74
- }).catch((error: Error): void => {
75
- // If one of the scheduled tasks failed, log, recover and continue processing rest of the tasks
76
- if (entry.id !== metadata.id()) { return; }
77
- if (error) { internal.log(Code.RunTask, Severity.Warning, error.name, error.message, error.stack); }
78
- activeTask = null;
79
- run();
80
- });
81
- }
82
- }
83
-
84
- export function state(timer: Timer): Task {
85
- let id = key(timer);
86
- if (id in tracker) {
87
- let elapsed = performance.now() - tracker[id].start;
88
- return (elapsed > tracker[id].yield) ? Task.Wait : Task.Run;
89
- }
90
- // If this task is no longer being tracked, send stop message to the caller
91
- return Task.Stop;
92
- }
93
-
94
- export function start(timer: Timer): void {
95
- tracker[key(timer)] = { start: performance.now(), calls: 0, yield: Setting.LongTask };
96
- }
97
-
98
- function restart(timer: Timer): void {
99
- let id = key(timer);
100
- if (tracker && tracker[id]) {
101
- let c = tracker[id].calls;
102
- let y = tracker[id].yield;
103
- start(timer);
104
- tracker[id].calls = c + 1;
105
- tracker[id].yield = y;
106
- }
107
- }
108
-
109
- export function stop(timer: Timer): void {
110
- let end = performance.now();
111
- let id = key(timer);
112
- let duration = end - tracker[id].start;
113
- metric.sum(timer.cost, duration);
114
- metric.count(Metric.InvokeCount);
115
-
116
- // For the first execution, which is synchronous, time is automatically counted towards TotalDuration.
117
- // However, for subsequent asynchronous runs, we need to manually update TotalDuration metric.
118
- if (tracker[id].calls > 0) { metric.sum(Metric.TotalCost, duration); }
119
- }
120
-
121
- export async function suspend(timer: Timer): Promise<Task> {
122
- // Suspend and yield the thread only if the task is still being tracked
123
- // It's possible that Clarity is wrapping up instrumentation on a page and we are still in the middle of an async task.
124
- // In that case, we do not wish to continue yielding thread.
125
- // Instead, we will turn async task into a sync task and maximize our chances of getting some data back.
126
- let id = key(timer);
127
- if (id in tracker) {
128
- stop(timer);
129
- // some customer polyfills for requestIdleCallback return null
130
- tracker[id].yield = (await wait())?.timeRemaining() || Setting.LongTask;
131
- restart(timer);
132
- }
133
- // After we are done with suspending task, ensure that we are still operating in the right context
134
- // If the task is still being tracked, continue running the task, otherwise ask caller to stop execution
135
- return id in tracker ? Task.Run : Task.Stop;
136
- }
137
-
138
- function key(timer: Timer): string {
139
- return `${timer.id}.${timer.cost}`;
140
- }
141
-
142
- async function wait(): Promise<RequestIdleCallbackDeadline> {
143
- if (pauseTask) { await pauseTask; }
144
- return new Promise<RequestIdleCallbackDeadline>((resolve: (deadline: RequestIdleCallbackDeadline) => void): void => {
145
- requestIdleCallback(resolve, { timeout: idleTimeout });
146
- });
147
- }
148
-
149
- // Use native implementation of requestIdleCallback if it exists.
150
- // Otherwise, fall back to a custom implementation using requestAnimationFrame & MessageChannel.
151
- // While it's not possible to build a perfect polyfill given the nature of this API, the following code attempts to get close.
152
- // Background context: requestAnimationFrame invokes the js code right before: style, layout and paint computation within the frame.
153
- // This means, that any code that runs as part of requestAnimationFrame will by default be blocking in nature. Not what we want.
154
- // For non-blocking behavior, We need to know when browser has finished painting. This can be accomplished in two different ways (hacks):
155
- // (1) Use MessageChannel to pass the message, and browser will receive the message right after paint event has occured.
156
- // (2) Use setTimeout call within requestAnimationFrame. This also works, but there's a risk that browser may throttle setTimeout calls.
157
- // Given this information, we are currently using (1) from above. More information on (2) as well as some additional context is below:
158
- // https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Performance_best_practices_for_Firefox_fe_engineers
159
- function requestIdleCallbackPolyfill(callback: (deadline: RequestIdleCallbackDeadline) => void, options: RequestIdleCallbackOptions): void {
160
- const startTime = performance.now();
161
- const channel = new MessageChannel();
162
- const incoming = channel.port1;
163
- const outgoing = channel.port2;
164
- incoming.onmessage = (event: MessageEvent): void => {
165
- let currentTime = performance.now();
166
- let elapsed = currentTime - startTime;
167
- let duration = currentTime - event.data;
168
- if (duration > Setting.LongTask && elapsed < options.timeout) {
169
- requestAnimationFrame((): void => { outgoing.postMessage(currentTime); });
170
- } else {
171
- let didTimeout = elapsed > options.timeout;
172
- callback({
173
- didTimeout,
174
- timeRemaining: (): number => didTimeout ? Setting.LongTask : Math.max(0, Setting.LongTask - duration)
175
- });
176
- }
177
- };
178
- requestAnimationFrame((): void => { outgoing.postMessage(performance.now()); });
179
- }
180
-
181
- let requestIdleCallback = window["requestIdleCallback"] || requestIdleCallbackPolyfill;
1
+ import { AsyncTask, Priority, RequestIdleCallbackDeadline, RequestIdleCallbackOptions, Task, Timer } from "@clarity-types/core";
2
+ import { TaskFunction, TaskResolve, Tasks } from "@clarity-types/core";
3
+ import { Code, Metric, Setting, Severity } from "@clarity-types/data";
4
+ import * as metadata from "@src/data/metadata";
5
+ import * as metric from "@src/data/metric";
6
+ import * as internal from "@src/diagnostic/internal";
7
+
8
+ // Track the start time to be able to compute duration at the end of the task
9
+ const idleTimeout = 5000;
10
+ let tracker: Tasks = {};
11
+ let queuedTasks: AsyncTask[] = [];
12
+ let activeTask: AsyncTask = null;
13
+ let pauseTask: Promise<void> = null;
14
+ let resumeResolve: TaskResolve = null;
15
+
16
+ export function pause(): void {
17
+ if (pauseTask === null) {
18
+ pauseTask = new Promise<void>((resolve: TaskResolve): void => {
19
+ resumeResolve = resolve;
20
+ });
21
+ }
22
+ }
23
+
24
+ export function resume(): void {
25
+ if (pauseTask) {
26
+ resumeResolve();
27
+ pauseTask = null;
28
+ if (activeTask === null) { run(); }
29
+ }
30
+ }
31
+
32
+ export function reset(): void {
33
+ tracker = {};
34
+ queuedTasks = [];
35
+ activeTask = null;
36
+ pauseTask = null;
37
+ }
38
+
39
+ export async function schedule(task: TaskFunction, priority: Priority = Priority.Normal): Promise<void> {
40
+ // If this task is already scheduled, skip it
41
+ for (let q of queuedTasks) {
42
+ if (q.task === task) {
43
+ return;
44
+ }
45
+ }
46
+
47
+ let promise = new Promise<void>((resolve: TaskResolve): void => {
48
+ let insert = priority === Priority.High ? "unshift" : "push";
49
+ // Queue this task for asynchronous execution later
50
+ // We also store a unique page identifier (id) along with the task to ensure
51
+ // ensure that we do not accidentally execute this task in context of a different page
52
+ queuedTasks[insert]({ task, resolve, id: metadata.id() });
53
+ });
54
+
55
+ // If there is no active task running, and Clarity is not in pause state,
56
+ // invoke the first task in the queue synchronously. This ensures that we don't yield the thread during unload event
57
+ if (activeTask === null && pauseTask === null) { run(); }
58
+
59
+ return promise;
60
+ }
61
+
62
+ function run(): void {
63
+ let entry = queuedTasks.shift();
64
+ if (entry) {
65
+ activeTask = entry;
66
+ entry.task().then((): void => {
67
+ // Bail out if the context in which this task was operating is different from the current page
68
+ // An example scenario where task could span across pages is Single Page Applications (SPA)
69
+ // A task that started on page #1, but completes on page #2
70
+ if (entry.id !== metadata.id()) { return; }
71
+ entry.resolve();
72
+ activeTask = null; // Reset active task back to null now that the promise is resolved
73
+ run();
74
+ }).catch((error: Error): void => {
75
+ // If one of the scheduled tasks failed, log, recover and continue processing rest of the tasks
76
+ if (entry.id !== metadata.id()) { return; }
77
+ if (error) { internal.log(Code.RunTask, Severity.Warning, error.name, error.message, error.stack); }
78
+ activeTask = null;
79
+ run();
80
+ });
81
+ }
82
+ }
83
+
84
+ export function state(timer: Timer): Task {
85
+ let id = key(timer);
86
+ if (id in tracker) {
87
+ let elapsed = performance.now() - tracker[id].start;
88
+ return (elapsed > tracker[id].yield) ? Task.Wait : Task.Run;
89
+ }
90
+ // If this task is no longer being tracked, send stop message to the caller
91
+ return Task.Stop;
92
+ }
93
+
94
+ export function start(timer: Timer): void {
95
+ tracker[key(timer)] = { start: performance.now(), calls: 0, yield: Setting.LongTask };
96
+ }
97
+
98
+ function restart(timer: Timer): void {
99
+ let id = key(timer);
100
+ if (tracker && tracker[id]) {
101
+ let c = tracker[id].calls;
102
+ let y = tracker[id].yield;
103
+ start(timer);
104
+ tracker[id].calls = c + 1;
105
+ tracker[id].yield = y;
106
+ }
107
+ }
108
+
109
+ export function stop(timer: Timer): void {
110
+ let end = performance.now();
111
+ let id = key(timer);
112
+ let duration = end - tracker[id].start;
113
+ metric.sum(timer.cost, duration);
114
+ metric.count(Metric.InvokeCount);
115
+
116
+ // For the first execution, which is synchronous, time is automatically counted towards TotalDuration.
117
+ // However, for subsequent asynchronous runs, we need to manually update TotalDuration metric.
118
+ if (tracker[id].calls > 0) { metric.sum(Metric.TotalCost, duration); }
119
+ }
120
+
121
+ export async function suspend(timer: Timer): Promise<Task> {
122
+ // Suspend and yield the thread only if the task is still being tracked
123
+ // It's possible that Clarity is wrapping up instrumentation on a page and we are still in the middle of an async task.
124
+ // In that case, we do not wish to continue yielding thread.
125
+ // Instead, we will turn async task into a sync task and maximize our chances of getting some data back.
126
+ let id = key(timer);
127
+ if (id in tracker) {
128
+ stop(timer);
129
+ // some customer polyfills for requestIdleCallback return null
130
+ tracker[id].yield = (await wait())?.timeRemaining() || Setting.LongTask;
131
+ restart(timer);
132
+ }
133
+ // After we are done with suspending task, ensure that we are still operating in the right context
134
+ // If the task is still being tracked, continue running the task, otherwise ask caller to stop execution
135
+ return id in tracker ? Task.Run : Task.Stop;
136
+ }
137
+
138
+ function key(timer: Timer): string {
139
+ return `${timer.id}.${timer.cost}`;
140
+ }
141
+
142
+ async function wait(): Promise<RequestIdleCallbackDeadline> {
143
+ if (pauseTask) { await pauseTask; }
144
+ return new Promise<RequestIdleCallbackDeadline>((resolve: (deadline: RequestIdleCallbackDeadline) => void): void => {
145
+ requestIdleCallback(resolve, { timeout: idleTimeout });
146
+ });
147
+ }
148
+
149
+ // Use native implementation of requestIdleCallback if it exists.
150
+ // Otherwise, fall back to a custom implementation using requestAnimationFrame & MessageChannel.
151
+ // While it's not possible to build a perfect polyfill given the nature of this API, the following code attempts to get close.
152
+ // Background context: requestAnimationFrame invokes the js code right before: style, layout and paint computation within the frame.
153
+ // This means, that any code that runs as part of requestAnimationFrame will by default be blocking in nature. Not what we want.
154
+ // For non-blocking behavior, We need to know when browser has finished painting. This can be accomplished in two different ways (hacks):
155
+ // (1) Use MessageChannel to pass the message, and browser will receive the message right after paint event has occured.
156
+ // (2) Use setTimeout call within requestAnimationFrame. This also works, but there's a risk that browser may throttle setTimeout calls.
157
+ // Given this information, we are currently using (1) from above. More information on (2) as well as some additional context is below:
158
+ // https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Performance_best_practices_for_Firefox_fe_engineers
159
+ function requestIdleCallbackPolyfill(callback: (deadline: RequestIdleCallbackDeadline) => void, options: RequestIdleCallbackOptions): void {
160
+ const startTime = performance.now();
161
+ const channel = new MessageChannel();
162
+ const incoming = channel.port1;
163
+ const outgoing = channel.port2;
164
+ incoming.onmessage = (event: MessageEvent): void => {
165
+ let currentTime = performance.now();
166
+ let elapsed = currentTime - startTime;
167
+ let duration = currentTime - event.data;
168
+ if (duration > Setting.LongTask && elapsed < options.timeout) {
169
+ requestAnimationFrame((): void => { outgoing.postMessage(currentTime); });
170
+ } else {
171
+ let didTimeout = elapsed > options.timeout;
172
+ callback({
173
+ didTimeout,
174
+ timeRemaining: (): number => didTimeout ? Setting.LongTask : Math.max(0, Setting.LongTask - duration)
175
+ });
176
+ }
177
+ };
178
+ requestAnimationFrame((): void => { outgoing.postMessage(performance.now()); });
179
+ }
180
+
181
+ let requestIdleCallback = window["requestIdleCallback"] || requestIdleCallbackPolyfill;
@@ -1,46 +1,46 @@
1
- /**
2
- * Creates a throttled version of the provided function that only executes at most once
3
- * every specified duration in milliseconds, ensuring the last event is not lost.
4
- * @param func - The function to throttle.
5
- * @param duration - The duration in milliseconds to wait before allowing the next execution.
6
- * @returns A throttled version of the provided function with a cleanup method.
7
- */
8
- export default function throttle<T extends (...args: any[]) => void>(func: T, duration: number): T & { cleanup: () => void } {
9
- let lastExecutionTime = 0;
10
- let timeoutId: ReturnType<typeof setTimeout> | null = null;
11
- let lastArgs: Parameters<T> | null = null;
12
-
13
- function throttledFunction(...args: Parameters<T>) {
14
- const now = performance.now();
15
- const timeSinceLastExecution = now - lastExecutionTime;
16
-
17
- // If the function is called during the throttling period, store the arguments to ensure we don't drop the last event
18
- if (lastExecutionTime !== 0 && timeSinceLastExecution < duration) {
19
- lastArgs = args;
20
-
21
- if (timeoutId) return;
22
-
23
- timeoutId = setTimeout(() => {
24
- lastExecutionTime = performance.now();
25
- func.apply(this, lastArgs!);
26
- lastArgs = null;
27
- timeoutId = null;
28
- }, duration - timeSinceLastExecution);
29
- } else {
30
- // Execute immediately if outside the throttling period (including the first run)
31
- lastExecutionTime = now;
32
- func.apply(this, args);
33
- }
34
- }
35
-
36
- // Add cleanup method to clear pending timeouts
37
- throttledFunction.cleanup = function () {
38
- if (timeoutId) {
39
- clearTimeout(timeoutId);
40
- timeoutId = null;
41
- lastArgs = null;
42
- }
43
- };
44
-
45
- return throttledFunction as T & { cleanup: () => void };
46
- }
1
+ /**
2
+ * Creates a throttled version of the provided function that only executes at most once
3
+ * every specified duration in milliseconds, ensuring the last event is not lost.
4
+ * @param func - The function to throttle.
5
+ * @param duration - The duration in milliseconds to wait before allowing the next execution.
6
+ * @returns A throttled version of the provided function with a cleanup method.
7
+ */
8
+ export default function throttle<T extends (...args: any[]) => void>(func: T, duration: number): T & { cleanup: () => void } {
9
+ let lastExecutionTime = 0;
10
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
11
+ let lastArgs: Parameters<T> | null = null;
12
+
13
+ function throttledFunction(...args: Parameters<T>) {
14
+ const now = performance.now();
15
+ const timeSinceLastExecution = now - lastExecutionTime;
16
+
17
+ // If the function is called during the throttling period, store the arguments to ensure we don't drop the last event
18
+ if (lastExecutionTime !== 0 && timeSinceLastExecution < duration) {
19
+ lastArgs = args;
20
+
21
+ if (timeoutId) return;
22
+
23
+ timeoutId = setTimeout(() => {
24
+ lastExecutionTime = performance.now();
25
+ func.apply(this, lastArgs!);
26
+ lastArgs = null;
27
+ timeoutId = null;
28
+ }, duration - timeSinceLastExecution);
29
+ } else {
30
+ // Execute immediately if outside the throttling period (including the first run)
31
+ lastExecutionTime = now;
32
+ func.apply(this, args);
33
+ }
34
+ }
35
+
36
+ // Add cleanup method to clear pending timeouts
37
+ throttledFunction.cleanup = function () {
38
+ if (timeoutId) {
39
+ clearTimeout(timeoutId);
40
+ timeoutId = null;
41
+ lastArgs = null;
42
+ }
43
+ };
44
+
45
+ return throttledFunction as T & { cleanup: () => void };
46
+ }
package/src/core/time.ts CHANGED
@@ -1,26 +1,26 @@
1
- let startTime = 0;
2
-
3
- function computeStartTime(): number {
4
- return performance.now() + performance.timeOrigin;
5
- }
6
-
7
- export function start(): void {
8
- startTime = computeStartTime();
9
- }
10
-
11
- // event.timestamp is number of milliseconds elapsed since the document was loaded
12
- // since iframes can be loaded later the event timestamp is not the same as performance.now()
13
- // converting everything to absolute time by adding timeorigin of the event view
14
- // to synchronize times before calculating the difference with start time
15
- export function time(event: UIEvent | PageTransitionEvent = null): number {
16
- // If startTime is 0, Clarity hasn't been started or has been stopped
17
- // Use a local baseline to maintain relative timing semantics without affecting global state
18
- let baseline = startTime === 0 ? computeStartTime() : startTime;
19
- let ts = event && event.timeStamp > 0 ? event.timeStamp : performance.now();
20
- let origin = event && (event as UIEvent).view ? (event as UIEvent).view.performance.timeOrigin : performance.timeOrigin;
21
- return Math.max(Math.round(ts + origin - baseline), 0);
22
- }
23
-
24
- export function stop(): void {
25
- startTime = 0;
26
- }
1
+ let startTime = 0;
2
+
3
+ function computeStartTime(): number {
4
+ return performance.now() + performance.timeOrigin;
5
+ }
6
+
7
+ export function start(): void {
8
+ startTime = computeStartTime();
9
+ }
10
+
11
+ // event.timestamp is number of milliseconds elapsed since the document was loaded
12
+ // since iframes can be loaded later the event timestamp is not the same as performance.now()
13
+ // converting everything to absolute time by adding timeorigin of the event view
14
+ // to synchronize times before calculating the difference with start time
15
+ export function time(event: UIEvent | PageTransitionEvent = null): number {
16
+ // If startTime is 0, Clarity hasn't been started or has been stopped
17
+ // Use a local baseline to maintain relative timing semantics without affecting global state
18
+ let baseline = startTime === 0 ? computeStartTime() : startTime;
19
+ let ts = event && event.timeStamp > 0 ? event.timeStamp : performance.now();
20
+ let origin = event && (event as UIEvent).view ? (event as UIEvent).view.performance.timeOrigin : performance.timeOrigin;
21
+ return Math.max(Math.round(ts + origin - baseline), 0);
22
+ }
23
+
24
+ export function stop(): void {
25
+ startTime = 0;
26
+ }
@@ -1,10 +1,10 @@
1
- import { Event } from "@clarity-types/data";
2
- import measure from "./measure";
3
-
4
- export function setTimeout(handler: (event?: Event | boolean) => void, timeout?: number, event?: Event): number {
5
- return window.setTimeout(measure(handler), timeout, event);
6
- }
7
-
8
- export function clearTimeout(handle: number): void {
9
- return window.clearTimeout(handle);
10
- }
1
+ import { Event } from "@clarity-types/data";
2
+ import measure from "./measure";
3
+
4
+ export function setTimeout(handler: (event?: Event | boolean) => void, timeout?: number, event?: Event): number {
5
+ return window.setTimeout(measure(handler), timeout, event);
6
+ }
7
+
8
+ export function clearTimeout(handle: number): void {
9
+ return window.clearTimeout(handle);
10
+ }
@@ -1,2 +1,2 @@
1
- let version = "0.8.42";
2
- export default version;
1
+ let version = "0.8.43";
2
+ export default version;